home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 5 Edit / 05-Edit.zip / browser2.zip / cl-macs.el < prev    next >
Lisp/Scheme  |  1995-02-10  |  104KB  |  2,612 lines

  1. ;; cl-macs.el --- Common Lisp extensions for GNU Emacs Lisp (part four)
  2.  
  3. ;; Copyright (C) 1993 Free Software Foundation, Inc.
  4.  
  5. ;; Author: Dave Gillespie <daveg@synaptics.com>
  6. ;; Version: 2.02
  7. ;; Keywords: extensions
  8.  
  9. ;; This file is part of GNU Emacs.
  10.  
  11. ;; GNU Emacs is free software; you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation; either version 1, or (at your option)
  14. ;; any later version.
  15.  
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. ;; GNU General Public License for more details.
  20.  
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  23. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  24.  
  25. ;; Commentary:
  26.  
  27. ;; These are extensions to Emacs Lisp that provide a degree of
  28. ;; Common Lisp compatibility, beyond what is already built-in
  29. ;; in Emacs Lisp.
  30. ;;
  31. ;; This package was written by Dave Gillespie; it is a complete
  32. ;; rewrite of Cesar Quiroz's original cl.el package of December 1986.
  33. ;;
  34. ;; This package works with Emacs 18, Emacs 19, and Lucid Emacs 19.
  35. ;;
  36. ;; Bug reports, comments, and suggestions are welcome!
  37.  
  38. ;; This file contains the portions of the Common Lisp extensions
  39. ;; package which should be autoloaded, but need only be present
  40. ;; if the compiler or interpreter is used---this file is not
  41. ;; necessary for executing compiled code.
  42.  
  43. ;; See cl.el for Change Log.
  44.  
  45.  
  46. ;; Code:
  47.  
  48. (or (memq 'cl-19 features)
  49.     (error "Tried to load `cl-macs' before `cl'!"))
  50.  
  51.  
  52. ;;; We define these here so that this file can compile without having
  53. ;;; loaded the cl.el file already.
  54.  
  55. (defmacro cl-push (x place) (list 'setq place (list 'cons x place)))
  56. (defmacro cl-pop (place)
  57.   (list 'car (list 'prog1 place (list 'setq place (list 'cdr place)))))
  58. (defmacro cl-pop2 (place)
  59.   (list 'prog1 (list 'car (list 'cdr place))
  60.     (list 'setq place (list 'cdr (list 'cdr place)))))
  61. (put 'cl-push 'edebug-form-spec 'edebug-sexps)
  62. (put 'cl-pop 'edebug-form-spec 'edebug-sexps)
  63. (put 'cl-pop2 'edebug-form-spec 'edebug-sexps)
  64.  
  65. (defvar cl-emacs-type)
  66. (defvar cl-optimize-safety)
  67. (defvar cl-optimize-speed)
  68.  
  69.  
  70. ;;; This kludge allows macros which use cl-transform-function-property
  71. ;;; to be called at compile-time.
  72.  
  73. (require
  74.  (progn
  75.    (or (fboundp 'defalias) (fset 'defalias 'fset))
  76.    (or (fboundp 'cl-transform-function-property)
  77.        (defalias 'cl-transform-function-property
  78.      (function (lambda (n p f)
  79.              (list 'put (list 'quote n) (list 'quote p)
  80.                (list 'function (cons 'lambda f)))))))
  81.    (car (or features (setq features (list 'cl-kludge))))))
  82.  
  83.  
  84. ;;; Initialization.
  85.  
  86. (defvar cl-old-bc-file-form nil)
  87.  
  88. ;; Patch broken Emacs 18 compiler (re top-level macros).
  89. ;; Emacs 19 compiler doesn't need this patch.
  90. ;; Also, undo broken definition of `eql' that uses same bytecode as `eq'.
  91. (defun cl-compile-time-init ()
  92.   (setq cl-old-bc-file-form (symbol-function 'byte-compile-file-form))
  93.   (or (fboundp 'byte-compile-flush-pending)   ; Emacs 19 compiler?
  94.       (defalias 'byte-compile-file-form
  95.     (function
  96.      (lambda (form)
  97. ;       (setq form (macroexpand form byte-compile-macro-environment))
  98.        (setq form (macroexpand (compiler-macroexpand form) byte-compile-macro-environment))
  99.        (if (eq (car-safe form) 'progn)
  100.            (cons 'progn (mapcar 'byte-compile-file-form (cdr form)))
  101.          (funcall cl-old-bc-file-form form))))))
  102.   (put 'eql 'byte-compile 'cl-byte-compile-compiler-macro)
  103.   (run-hooks 'cl-hack-bytecomp-hook))
  104.  
  105.  
  106. ;;; Symbols.
  107.  
  108. (defvar *gensym-counter*)
  109. (defun gensym (&optional arg)
  110.   "Generate a new uninterned symbol.
  111. The name is made by appending a number to PREFIX, default \"G\"."
  112.   (let ((prefix (if (stringp arg) arg "G"))
  113.     (num (if (integerp arg) arg
  114.            (prog1 *gensym-counter*
  115.          (setq *gensym-counter* (1+ *gensym-counter*))))))
  116.     (make-symbol (format "%s%d" prefix num))))
  117.  
  118. (defun gentemp (&optional arg)
  119.   "Generate a new interned symbol with a unique name.
  120. The name is made by appending a number to PREFIX, default \"G\"."
  121.   (let ((prefix (if (stringp arg) arg "G"))
  122.     name)
  123.     (while (intern-soft (setq name (format "%s%d" prefix *gensym-counter*)))
  124.       (setq *gensym-counter* (1+ *gensym-counter*)))
  125.     (intern name)))
  126.  
  127.  
  128. ;;; Program structure.
  129.  
  130. (defmacro defun* (name args &rest body)
  131.   "(defun* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
  132. Like normal `defun', except ARGLIST allows full Common Lisp conventions,
  133. and BODY is implicitly surrounded by (block NAME ...)."
  134.   (let* ((res (cl-transform-lambda (cons args body) name))
  135.      (form (list* 'defun name (cdr res))))
  136.     (if (car res) (list 'progn (car res) form) form)))
  137.  
  138. (defmacro defmacro* (name args &rest body)
  139.   "(defmacro* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a macro.
  140. Like normal `defmacro', except ARGLIST allows full Common Lisp conventions,
  141. and BODY is implicitly surrounded by (block NAME ...)."
  142.   (let* ((res (cl-transform-lambda (cons args body) name))
  143.      (form (list* 'defmacro name (cdr res))))
  144.     (if (car res) (list 'progn (car res) form) form)))
  145.  
  146. (defmacro function* (func)
  147.   "(function* SYMBOL-OR-LAMBDA): introduce a function.
  148. Like normal `function', except that if argument is a lambda form, its
  149. ARGLIST allows full Common Lisp conventions."
  150.   (if (eq (car-safe func) 'lambda)
  151.       (let* ((res (cl-transform-lambda (cdr func) 'cl-none))
  152.          (form (list 'function (cons 'lambda (cdr res)))))
  153.     (if (car res) (list 'progn (car res) form) form))
  154.     (list 'function func)))
  155.  
  156. (defun cl-transform-function-property (func prop form)
  157.   (let ((res (cl-transform-lambda form func)))
  158.     (append '(progn) (cdr (cdr (car res)))
  159.         (list (list 'put (list 'quote func) (list 'quote prop)
  160.             (list 'function (cons 'lambda (cdr res))))))))
  161.  
  162. (defconst lambda-list-keywords
  163.   '(&optional &rest &key &allow-other-keys &aux &whole &body &environment))
  164.  
  165. (defvar cl-macro-environment nil)
  166. (defvar bind-block) (defvar bind-defs) (defvar bind-enquote)
  167. (defvar bind-inits) (defvar bind-lets) (defvar bind-forms)
  168.  
  169. (defun cl-transform-lambda (form bind-block)
  170.   (let* ((args (car form)) (body (cdr form))
  171.      (bind-defs nil) (bind-enquote nil)
  172.      (bind-inits nil) (bind-lets nil) (bind-forms nil)
  173.      (header nil) (simple-args nil))
  174.     (while (or (stringp (car body)) (eq (car-safe (car body)) 'interactive))
  175.       (cl-push (cl-pop body) header))
  176.     (setq args (if (listp args) (copy-list args) (list '&rest args)))
  177.     (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
  178.     (if (setq bind-defs (cadr (memq '&cl-defs args)))
  179.     (setq args (delq '&cl-defs (delq bind-defs args))
  180.           bind-defs (cadr bind-defs)))
  181.     (if (setq bind-enquote (memq '&cl-quote args))
  182.     (setq args (delq '&cl-quote args)))
  183.     (if (memq '&whole args) (error "&whole not currently implemented"))
  184.     (let* ((p (memq '&environment args)) (v (cadr p)))
  185.       (if p (setq args (nconc (delq (car p) (delq v args))
  186.                   (list '&aux (list v 'cl-macro-environment))))))
  187.     (while (and args (symbolp (car args))
  188.         (not (memq (car args) '(nil &rest &body &key &aux)))
  189.         (not (and (eq (car args) '&optional)
  190.               (or bind-defs (consp (cadr args))))))
  191.       (cl-push (cl-pop args) simple-args))
  192.     (or (eq bind-block 'cl-none)
  193.     (setq body (list (list* 'block bind-block body))))
  194.     (if (null args)
  195.     (list* nil (nreverse simple-args) (nconc (nreverse header) body))
  196.       (if (memq '&optional simple-args) (cl-push '&optional args))
  197.       (cl-do-arglist args nil (- (length simple-args)
  198.                  (if (memq '&optional simple-args) 1 0)))
  199.       (setq bind-lets (nreverse bind-lets))
  200.       (list* (and bind-inits (list* 'eval-when '(compile load eval)
  201.                     (nreverse bind-inits)))
  202.          (nconc (nreverse simple-args)
  203.             (list '&rest (car (cl-pop bind-lets))))
  204.          (nconc (nreverse header)
  205.             (list (nconc (list 'let* bind-lets)
  206.                  (nreverse bind-forms) body)))))))
  207.  
  208. (defun cl-do-arglist (args expr &optional num)   ; uses bind-*
  209.   (if (nlistp args)
  210.       (if (or (memq args lambda-list-keywords) (not (symbolp args)))
  211.       (error "Invalid argument name: %s" args)
  212.     (cl-push (list args expr) bind-lets))
  213.     (setq args (copy-list args))
  214.     (let ((p (last args))) (if (cdr p) (setcdr p (list '&rest (cdr p)))))
  215.     (let ((p (memq '&body args))) (if p (setcar p '&rest)))
  216.     (if (memq '&environment args) (error "&environment used incorrectly"))
  217.     (let ((save-args args)
  218.       (restarg (memq '&rest args))
  219.       (safety (if (cl-compiling-file) cl-optimize-safety 3))
  220.       (keys nil)
  221.       (laterarg nil) (exactarg nil) minarg)
  222.       (or num (setq num 0))
  223.       (if (listp (cadr restarg))
  224.       (setq restarg (gensym "--rest--"))
  225.     (setq restarg (cadr restarg)))
  226.       (cl-push (list restarg expr) bind-lets)
  227.       (if (eq (car args) '&whole)
  228.       (cl-push (list (cl-pop2 args) restarg) bind-lets))
  229.       (let ((p args))
  230.     (setq minarg restarg)
  231.     (while (and p (not (memq (car p) lambda-list-keywords)))
  232.       (or (eq p args) (setq minarg (list 'cdr minarg)))
  233.       (setq p (cdr p)))
  234.     (if (memq (car p) '(nil &aux))
  235.         (setq minarg (list '= (list 'length restarg)
  236.                    (length (ldiff args p)))
  237.           exactarg (not (eq args p)))))
  238.       (while (and args (not (memq (car args) lambda-list-keywords)))
  239.     (let ((poparg (list (if (or (cdr args) (not exactarg)) 'pop 'car)
  240.                 restarg)))
  241.       (cl-do-arglist
  242.        (cl-pop args)
  243.        (if (or laterarg (= safety 0)) poparg
  244.          (list 'if minarg poparg
  245.            (list 'signal '(quote wrong-number-of-arguments)
  246.              (list 'list (and (not (eq bind-block 'cl-none))
  247.                       (list 'quote bind-block))
  248.                    (list 'length restarg)))))))
  249.     (setq num (1+ num) laterarg t))
  250.       (while (and (eq (car args) '&optional) (cl-pop args))
  251.     (while (and args (not (memq (car args) lambda-list-keywords)))
  252.       (let ((arg (cl-pop args)))
  253.         (or (consp arg) (setq arg (list arg)))
  254.         (if (cddr arg) (cl-do-arglist (nth 2 arg) (list 'and restarg t)))
  255.         (let ((def (if (cdr arg) (nth 1 arg)
  256.              (or (car bind-defs)
  257.                  (nth 1 (assq (car arg) bind-defs)))))
  258.           (poparg (list 'pop restarg)))
  259.           (and def bind-enquote (setq def (list 'quote def)))
  260.           (cl-do-arglist (car arg)
  261.                  (if def (list 'if restarg poparg def) poparg))
  262.           (setq num (1+ num))))))
  263.       (if (eq (car args) '&rest)
  264.       (let ((arg (cl-pop2 args)))
  265.         (if (consp arg) (cl-do-arglist arg restarg)))
  266.     (or (eq (car args) '&key) (= safety 0) exactarg
  267.         (cl-push (list 'if restarg
  268.                (list 'signal '(quote wrong-number-of-arguments)
  269.                  (list 'list
  270.                        (and (not (eq bind-block 'cl-none))
  271.                         (list 'quote bind-block))
  272.                        (list '+ num (list 'length restarg)))))
  273.              bind-forms)))
  274.       (while (and (eq (car args) '&key) (cl-pop args))
  275.     (while (and args (not (memq (car args) lambda-list-keywords)))
  276.       (let ((arg (cl-pop args)))
  277.         (or (consp arg) (setq arg (list arg)))
  278.         (let* ((karg (if (consp (car arg)) (caar arg)
  279.                (intern (format ":%s" (car arg)))))
  280.            (varg (if (consp (car arg)) (cadar arg) (car arg)))
  281.            (def (if (cdr arg) (cadr arg)
  282.               (or (car bind-defs) (cadr (assq varg bind-defs)))))
  283.            (look (list 'memq (list 'quote karg) restarg)))
  284.           (and def bind-enquote (setq def (list 'quote def)))
  285.           (if (cddr arg)
  286.           (let* ((temp (or (nth 2 arg) (gensym)))
  287.              (val (list 'car (list 'cdr temp))))
  288.             (cl-do-arglist temp look)
  289.             (cl-do-arglist varg
  290.                    (list 'if temp
  291.                      (list 'prog1 val (list 'setq temp t))
  292.                      def)))
  293.         (cl-do-arglist
  294.          varg
  295.          (list 'car
  296.                (list 'cdr
  297.                  (if (null def)
  298.                  look
  299.                    (list 'or look
  300.                      (if (eq (cl-const-expr-p def) t)
  301.                      (list
  302.                       'quote
  303.                       (list nil (cl-const-expr-val def)))
  304.                        (list 'list nil def))))))))
  305.           (cl-push karg keys)
  306.           (if (= (aref (symbol-name karg) 0) ?:)
  307.           (progn (set karg karg)
  308.              (cl-push (list 'setq karg (list 'quote karg))
  309.                   bind-inits)))))))
  310.       (setq keys (nreverse keys))
  311.       (or (and (eq (car args) '&allow-other-keys) (cl-pop args))
  312.       (null keys) (= safety 0)
  313.       (let* ((var (gensym "--keys--"))
  314.          (allow '(:allow-other-keys))
  315.          (check (list
  316.              'while var
  317.              (list
  318.               'cond
  319.               (list (list 'memq (list 'car var)
  320.                       (list 'quote (append keys allow)))
  321.                 (list 'setq var (list 'cdr (list 'cdr var))))
  322.               (list (list 'car
  323.                       (list 'cdr
  324.                         (list 'memq (cons 'quote allow)
  325.                           restarg)))
  326.                 (list 'setq var nil))
  327.               (list t
  328.                 (list
  329.                  'error
  330.                  (format "Keyword argument %%s not one of %s"
  331.                      keys)
  332.                  (list 'car var)))))))
  333.         (cl-push (list 'let (list (list var restarg)) check) bind-forms)))
  334.       (while (and (eq (car args) '&aux) (cl-pop args))
  335.     (while (and args (not (memq (car args) lambda-list-keywords)))
  336.       (if (consp (car args))
  337.           (if (and bind-enquote (cadar args))
  338.           (cl-do-arglist (caar args)
  339.                  (list 'quote (cadr (cl-pop args))))
  340.         (cl-do-arglist (caar args) (cadr (cl-pop args))))
  341.         (cl-do-arglist (cl-pop args) nil))))
  342.       (if args (error "Malformed argument list %s" save-args)))))
  343.  
  344. (defun cl-arglist-args (args)
  345.   (if (nlistp args) (list args)
  346.     (let ((res nil) (kind nil) arg)
  347.       (while (consp args)
  348.     (setq arg (cl-pop args))
  349.     (if (memq arg lambda-list-keywords) (setq kind arg)
  350.       (if (eq arg '&cl-defs) (cl-pop args)
  351.         (and (consp arg) kind (setq arg (car arg)))
  352.         (and (consp arg) (cdr arg) (eq kind '&key) (setq arg (cadr arg)))
  353.         (setq res (nconc res (cl-arglist-args arg))))))
  354.       (nconc res (and args (list args))))))
  355.  
  356. (defmacro destructuring-bind (args expr &rest body)
  357.   (let* ((bind-lets nil) (bind-forms nil) (bind-inits nil)
  358.      (bind-defs nil) (bind-block 'cl-none))
  359.     (cl-do-arglist (or args '(&aux)) expr)
  360.     (append '(progn) bind-inits
  361.         (list (nconc (list 'let* (nreverse bind-lets))
  362.              (nreverse bind-forms) body)))))
  363.  
  364.  
  365. ;;; The `eval-when' form.
  366.  
  367. (defvar cl-not-toplevel nil)
  368.  
  369. (defmacro eval-when (when &rest body)
  370.   "(eval-when (WHEN...) BODY...): control when BODY is evaluated.
  371. If `compile' is in WHEN, BODY is evaluated when compiled at top-level.
  372. If `load' is in WHEN, BODY is evaluated when loaded after top-level compile.
  373. If `eval' is in WHEN, BODY is evaluated when interpreted or at non-top-level."
  374.   (if (and (fboundp 'cl-compiling-file) (cl-compiling-file)
  375.        (not cl-not-toplevel) (not (boundp 'for-effect)))  ; horrible kludge
  376.       (let ((comp (or (memq 'compile when) (memq ':compile-toplevel when)))
  377.         (cl-not-toplevel t))
  378.     (if (or (memq 'load when) (memq ':load-toplevel when))
  379.         (if comp (cons 'progn (mapcar 'cl-compile-time-too body))
  380.           (list* 'if nil nil body))
  381.       (progn (if comp (eval (cons 'progn body))) nil)))
  382.     (and (or (memq 'eval when) (memq ':execute when))
  383.      (cons 'progn body))))
  384.  
  385. (defun cl-compile-time-too (form)
  386.   (or (and (symbolp (car-safe form)) (get (car-safe form) 'byte-hunk-handler))
  387.       (setq form (macroexpand
  388.           form (cons '(eval-when) byte-compile-macro-environment))))
  389.   (cond ((eq (car-safe form) 'progn)
  390.      (cons 'progn (mapcar 'cl-compile-time-too (cdr form))))
  391.     ((eq (car-safe form) 'eval-when)
  392.      (let ((when (nth 1 form)))
  393.        (if (or (memq 'eval when) (memq ':execute when))
  394.            (list* 'eval-when (cons 'compile when) (cddr form))
  395.          form)))
  396.     (t (eval form) form)))
  397.  
  398. (or (and (fboundp 'eval-when-compile)
  399.      (not (eq (car-safe (symbol-function 'eval-when-compile)) 'autoload)))
  400.     (eval '(defmacro eval-when-compile (&rest body)
  401.          "Like `progn', but evaluates the body at compile time.
  402. The result of the body appears to the compiler as a quoted constant."
  403.          (list 'quote (eval (cons 'progn body))))))
  404.  
  405. (defmacro load-time-value (form &optional read-only)
  406.   "Like `progn', but evaluates the body at load time.
  407. The result of the body appears to the compiler as a quoted constant."
  408.   (if (cl-compiling-file)
  409.       (let* ((temp (gentemp "--cl-load-time--"))
  410.          (set (list 'set (list 'quote temp) form)))
  411.     (if (and (fboundp 'byte-compile-file-form-defmumble)
  412.          (boundp 'this-kind) (boundp 'that-one))
  413.         (fset 'byte-compile-file-form
  414.           (list 'lambda '(form)
  415.             (list 'fset '(quote byte-compile-file-form)
  416.                   (list 'quote
  417.                     (symbol-function 'byte-compile-file-form)))
  418.             (list 'byte-compile-file-form (list 'quote set))
  419.             '(byte-compile-file-form form)))
  420.       (print set (symbol-value 'outbuffer)))
  421.     (list 'symbol-value (list 'quote temp)))
  422.     (list 'quote (eval form))))
  423.  
  424.  
  425. ;;; Conditional control structures.
  426.  
  427. (defmacro case (expr &rest clauses)
  428.   "(case EXPR CLAUSES...): evals EXPR, chooses from CLAUSES on that value.
  429. Each clause looks like (KEYLIST BODY...).  EXPR is evaluated and compared
  430. against each key in each KEYLIST; the corresponding BODY is evaluated.
  431. If no clause succeeds, case returns nil.  A single atom may be used in
  432. place of a KEYLIST of one atom.  A KEYLIST of `t' or `otherwise' is
  433. allowed only in the final clause, and matches if no other keys match.
  434. Key values are compared by `eql'."
  435.   (let* ((temp (if (cl-simple-expr-p expr 3) expr (gensym)))
  436.      (head-list nil)
  437.      (body (cons
  438.         'cond
  439.         (mapcar
  440.          (function
  441.           (lambda (c)
  442.             (cons (cond ((memq (car c) '(t otherwise)) t)
  443.                 ((eq (car c) 'ecase-error-flag)
  444.                  (list 'error "ecase failed: %s, %s"
  445.                        temp (list 'quote (reverse head-list))))
  446.                 ((listp (car c))
  447.                  (setq head-list (append (car c) head-list))
  448.                  (list 'member* temp (list 'quote (car c))))
  449.                 (t
  450.                  (if (memq (car c) head-list)
  451.                      (error "Duplicate key in case: %s"
  452.                         (car c)))
  453.                  (cl-push (car c) head-list)
  454.                  (list 'eql temp (list 'quote (car c)))))
  455.               (or (cdr c) '(nil)))))
  456.          clauses))))
  457.     (if (eq temp expr) body
  458.       (list 'let (list (list temp expr)) body))))
  459.  
  460. (defmacro ecase (expr &rest clauses)
  461.   "(ecase EXPR CLAUSES...): like `case', but error if no case fits.
  462. `otherwise'-clauses are not allowed."
  463.   (list* 'case expr (append clauses '((ecase-error-flag)))))
  464.  
  465. (defmacro typecase (expr &rest clauses)
  466.   "(typecase EXPR CLAUSES...): evals EXPR, chooses from CLAUSES on that value.
  467. Each clause looks like (TYPE BODY...).  EXPR is evaluated and, if it
  468. satisfies TYPE, the corresponding BODY is evaluated.  If no clause succeeds,
  469. typecase returns nil.  A TYPE of `t' or `otherwise' is allowed only in the
  470. final clause, and matches if no other keys match."
  471.   (let* ((temp (if (cl-simple-expr-p expr 3) expr (gensym)))
  472.      (type-list nil)
  473.      (body (cons
  474.         'cond
  475.         (mapcar
  476.          (function
  477.           (lambda (c)
  478.             (cons (cond ((eq (car c) 'otherwise) t)
  479.                 ((eq (car c) 'ecase-error-flag)
  480.                  (list 'error "etypecase failed: %s, %s"
  481.                        temp (list 'quote (reverse type-list))))
  482.                 (t
  483.                  (cl-push (car c) type-list)
  484.                  (cl-make-type-test temp (car c))))
  485.               (or (cdr c) '(nil)))))
  486.          clauses))))
  487.     (if (eq temp expr) body
  488.       (list 'let (list (list temp expr)) body))))
  489.  
  490. (defmacro etypecase (expr &rest clauses)
  491.   "(etypecase EXPR CLAUSES...): like `typecase', but error if no case fits.
  492. `otherwise'-clauses are not allowed."
  493.   (list* 'typecase expr (append clauses '((ecase-error-flag)))))
  494.  
  495.  
  496. ;;; Blocks and exits.
  497.  
  498. (defmacro block (name &rest body)
  499.   "(block NAME BODY...): define a lexically-scoped block named NAME.
  500. NAME may be any symbol.  Code inside the BODY forms can call `return-from'
  501. to jump prematurely out of the block.  This differs from `catch' and `throw'
  502. in two respects:  First, the NAME is an unevaluated symbol rather than a
  503. quoted symbol or other form; and second, NAME is lexically rather than
  504. dynamically scoped:  Only references to it within BODY will work.  These
  505. references may appear inside macro expansions, but not inside functions
  506. called from BODY."
  507.   (if (cl-safe-expr-p (cons 'progn body)) (cons 'progn body)
  508.     (list 'cl-block-wrapper
  509.       (list* 'catch (list 'quote (intern (format "--cl-block-%s--" name)))
  510.          body))))
  511.  
  512. (defvar cl-active-block-names nil)
  513.  
  514. (put 'cl-block-wrapper 'byte-compile 'cl-byte-compile-block)
  515. (defun cl-byte-compile-block (cl-form)
  516.   (if (fboundp 'byte-compile-form-do-effect)  ; Check for optimizing compiler
  517.       (progn
  518.     (let* ((cl-entry (cons (nth 1 (nth 1 (nth 1 cl-form))) nil))
  519.            (cl-active-block-names (cons cl-entry cl-active-block-names))
  520.            (cl-body (byte-compile-top-level
  521.              (cons 'progn (cddr (nth 1 cl-form))))))
  522.       (if (cdr cl-entry)
  523.           (byte-compile-form (list 'catch (nth 1 (nth 1 cl-form)) cl-body))
  524.         (byte-compile-form cl-body))))
  525.     (byte-compile-form (nth 1 cl-form))))
  526.  
  527. (put 'cl-block-throw 'byte-compile 'cl-byte-compile-throw)
  528. (defun cl-byte-compile-throw (cl-form)
  529.   (let ((cl-found (assq (nth 1 (nth 1 cl-form)) cl-active-block-names)))
  530.     (if cl-found (setcdr cl-found t)))
  531.   (byte-compile-normal-call (cons 'throw (cdr cl-form))))
  532.  
  533. (defmacro return (&optional res)
  534.   "(return [RESULT]): return from the block named nil.
  535. This is equivalent to `(return-from nil RESULT)'."
  536.   (list 'return-from nil res))
  537.  
  538. (defmacro return-from (name &optional res)
  539.   "(return-from NAME [RESULT]): return from the block named NAME.
  540. This jump out to the innermost enclosing `(block NAME ...)' form,
  541. returning RESULT from that form (or nil if RESULT is omitted).
  542. This is compatible with Common Lisp, but note that `defun' and
  543. `defmacro' do not create implicit blocks as they do in Common Lisp."
  544.   (let ((name2 (intern (format "--cl-block-%s--" name))))
  545.     (list 'cl-block-throw (list 'quote name2) res)))
  546.  
  547.  
  548. ;;; The "loop" macro.
  549.  
  550. (defvar args) (defvar loop-accum-var) (defvar loop-accum-vars)
  551. (defvar loop-bindings) (defvar loop-body) (defvar loop-destr-temps)
  552. (defvar loop-finally) (defvar loop-finish-flag) (defvar loop-first-flag)
  553. (defvar loop-initially) (defvar loop-map-form) (defvar loop-name)
  554. (defvar loop-result) (defvar loop-result-explicit)
  555. (defvar loop-result-var) (defvar loop-steps) (defvar loop-symbol-macs)
  556.  
  557. (defmacro loop (&rest args)
  558.   "(loop CLAUSE...): The Common Lisp `loop' macro.
  559. Valid clauses are:
  560.   for VAR from/upfrom/downfrom NUM to/upto/downto/above/below NUM by NUM,
  561.   for VAR in LIST by FUNC, for VAR on LIST by FUNC, for VAR = INIT then EXPR,
  562.   for VAR across ARRAY, repeat NUM, with VAR = INIT, while COND, until COND,
  563.   always COND, never COND, thereis COND, collect EXPR into VAR,
  564.   append EXPR into VAR, nconc EXPR into VAR, sum EXPR into VAR,
  565.   count EXPR into VAR, maximize EXPR into VAR, minimize EXPR into VAR,
  566.   if COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
  567.   unless COND CLAUSE [and CLAUSE]... else CLAUSE [and CLAUSE...],
  568.   do EXPRS..., initially EXPRS..., finally EXPRS..., return EXPR,
  569.   finally return EXPR, named NAME."
  570.   (if (not (memq t (mapcar 'symbolp (delq nil (delq t (copy-list args))))))
  571.       (list 'block nil (list* 'while t args))
  572.     (let ((loop-name nil)    (loop-bindings nil)
  573.       (loop-body nil)    (loop-steps nil)
  574.       (loop-result nil)    (loop-result-explicit nil)
  575.       (loop-result-var nil) (loop-finish-flag nil)
  576.       (loop-accum-var nil)    (loop-accum-vars nil)
  577.       (loop-initially nil)    (loop-finally nil)
  578.       (loop-map-form nil)   (loop-first-flag nil)
  579.       (loop-destr-temps nil) (loop-symbol-macs nil))
  580.       (setq args (append args '(cl-end-loop)))
  581.       (while (not (eq (car args) 'cl-end-loop)) (cl-parse-loop-clause))
  582.       (if loop-finish-flag
  583.       (cl-push (list (list loop-finish-flag t)) loop-bindings))
  584.       (if loop-first-flag
  585.       (progn (cl-push (list (list loop-first-flag t)) loop-bindings)
  586.          (cl-push (list 'setq loop-first-flag nil) loop-steps)))
  587.       (let* ((epilogue (nconc (nreverse loop-finally)
  588.                   (list (or loop-result-explicit loop-result))))
  589.          (ands (cl-loop-build-ands (nreverse loop-body)))
  590.          (while-body (nconc (cadr ands) (nreverse loop-steps)))
  591.          (body (append
  592.             (nreverse loop-initially)
  593.             (list (if loop-map-form
  594.                   (list 'block '--cl-finish--
  595.                     (subst
  596.                      (if (eq (car ands) t) while-body
  597.                        (cons (list 'or (car ands)
  598.                            '(return-from --cl-finish--
  599.                               nil))
  600.                          while-body))
  601.                      '--cl-map loop-map-form))
  602.                 (list* 'while (car ands) while-body)))
  603.             (if loop-finish-flag
  604.             (if (equal epilogue '(nil)) (list loop-result-var)
  605.               (list (list 'if loop-finish-flag
  606.                       (cons 'progn epilogue) loop-result-var)))
  607.               epilogue))))
  608.     (if loop-result-var (cl-push (list loop-result-var) loop-bindings))
  609.     (while loop-bindings
  610.       (if (cdar loop-bindings)
  611.           (setq body (list (cl-loop-let (cl-pop loop-bindings) body t)))
  612.         (let ((lets nil))
  613.           (while (and loop-bindings
  614.               (not (cdar loop-bindings)))
  615.         (cl-push (car (cl-pop loop-bindings)) lets))
  616.           (setq body (list (cl-loop-let lets body nil))))))
  617.     (if loop-symbol-macs
  618.         (setq body (list (list* 'symbol-macrolet loop-symbol-macs body))))
  619.     (list* 'block loop-name body)))))
  620.  
  621. (defun cl-parse-loop-clause ()   ; uses args, loop-*
  622.   (let ((word (cl-pop args))
  623.     (hash-types '(hash-key hash-keys hash-value hash-values))
  624.     (key-types '(key-code key-codes key-seq key-seqs
  625.              key-binding key-bindings)))
  626.     (cond
  627.  
  628.      ((null args)
  629.       (error "Malformed `loop' macro"))
  630.  
  631.      ((eq word 'named)
  632.       (setq loop-name (cl-pop args)))
  633.  
  634.      ((eq word 'initially)
  635.       (if (memq (car args) '(do doing)) (cl-pop args))
  636.       (or (consp (car args)) (error "Syntax error on `initially' clause"))
  637.       (while (consp (car args))
  638.     (cl-push (cl-pop args) loop-initially)))
  639.  
  640.      ((eq word 'finally)
  641.       (if (eq (car args) 'return)
  642.       (setq loop-result-explicit (or (cl-pop2 args) '(quote nil)))
  643.     (if (memq (car args) '(do doing)) (cl-pop args))
  644.     (or (consp (car args)) (error "Syntax error on `finally' clause"))
  645.     (if (and (eq (caar args) 'return) (null loop-name))
  646.         (setq loop-result-explicit (or (nth 1 (cl-pop args)) '(quote nil)))
  647.       (while (consp (car args))
  648.         (cl-push (cl-pop args) loop-finally)))))
  649.  
  650.      ((memq word '(for as))
  651.       (let ((loop-for-bindings nil) (loop-for-sets nil) (loop-for-steps nil)
  652.         (ands nil))
  653.     (while
  654.         (let ((var (or (cl-pop args) (gensym))))
  655.           (setq word (cl-pop args))
  656.           (if (eq word 'being) (setq word (cl-pop args)))
  657.           (if (memq word '(the each)) (setq word (cl-pop args)))
  658.           (if (memq word '(buffer buffers))
  659.           (setq word 'in args (cons '(buffer-list) args)))
  660.           (cond
  661.  
  662.            ((memq word '(from downfrom upfrom to downto upto
  663.                  above below by))
  664.         (cl-push word args)
  665.         (if (memq (car args) '(downto above))
  666.             (error "Must specify `from' value for downward loop"))
  667.         (let* ((down (or (eq (car args) 'downfrom)
  668.                  (memq (caddr args) '(downto above))))
  669.                (excl (or (memq (car args) '(above below))
  670.                  (memq (caddr args) '(above below))))
  671.                (start (and (memq (car args) '(from upfrom downfrom))
  672.                    (cl-pop2 args)))
  673.                (end (and (memq (car args)
  674.                        '(to upto downto above below))
  675.                  (cl-pop2 args)))
  676.                (step (and (eq (car args) 'by) (cl-pop2 args)))
  677.                (end-var (and (not (cl-const-expr-p end)) (gensym)))
  678.                (step-var (and (not (cl-const-expr-p step))
  679.                       (gensym))))
  680.           (and step (numberp step) (<= step 0)
  681.                (error "Loop `by' value is not positive: %s" step))
  682.           (cl-push (list var (or start 0)) loop-for-bindings)
  683.           (if end-var (cl-push (list end-var end) loop-for-bindings))
  684.           (if step-var (cl-push (list step-var step)
  685.                     loop-for-bindings))
  686.           (if end
  687.               (cl-push (list
  688.                 (if down (if excl '> '>=) (if excl '< '<=))
  689.                 var (or end-var end)) loop-body))
  690.           (cl-push (list var (list (if down '- '+) var
  691.                        (or step-var step 1)))
  692.                loop-for-steps)))
  693.  
  694.            ((memq word '(in in-ref on))
  695.         (let* ((on (eq word 'on))
  696.                (temp (if (and on (symbolp var)) var (gensym))))
  697.           (cl-push (list temp (cl-pop args)) loop-for-bindings)
  698.           (cl-push (list 'consp temp) loop-body)
  699.           (if (eq word 'in-ref)
  700.               (cl-push (list var (list 'car temp)) loop-symbol-macs)
  701.             (or (eq temp var)
  702.             (progn
  703.               (cl-push (list var nil) loop-for-bindings)
  704.               (cl-push (list var (if on temp (list 'car temp)))
  705.                    loop-for-sets))))
  706.           (cl-push (list temp
  707.                  (if (eq (car args) 'by)
  708.                      (let ((step (cl-pop2 args)))
  709.                        (if (and (memq (car-safe step)
  710.                               '(quote function
  711.                                   function*))
  712.                         (symbolp (nth 1 step)))
  713.                        (list (nth 1 step) temp)
  714.                      (list 'funcall step temp)))
  715.                    (list 'cdr temp)))
  716.                loop-for-steps)))
  717.  
  718.            ((eq word '=)
  719.         (let* ((start (cl-pop args))
  720.                (then (if (eq (car args) 'then) (cl-pop2 args) start)))
  721.           (cl-push (list var nil) loop-for-bindings)
  722.           (if (or ands (eq (car args) 'and))
  723.               (progn
  724.             (cl-push (list var
  725.                        (list 'if
  726.                          (or loop-first-flag
  727.                          (setq loop-first-flag
  728.                                (gensym)))
  729.                          start var))
  730.                  loop-for-sets)
  731.             (cl-push (list var then) loop-for-steps))
  732.             (cl-push (list var
  733.                    (if (eq start then) start
  734.                      (list 'if
  735.                        (or loop-first-flag
  736.                            (setq loop-first-flag (gensym)))
  737.                        start then)))
  738.                  loop-for-sets))))
  739.  
  740.            ((memq word '(across across-ref))
  741.         (let ((temp-vec (gensym)) (temp-idx (gensym)))
  742.           (cl-push (list temp-vec (cl-pop args)) loop-for-bindings)
  743.           (cl-push (list temp-idx -1) loop-for-bindings)
  744.           (cl-push (list '< (list 'setq temp-idx (list '1+ temp-idx))
  745.                  (list 'length temp-vec)) loop-body)
  746.           (if (eq word 'across-ref)
  747.               (cl-push (list var (list 'aref temp-vec temp-idx))
  748.                    loop-symbol-macs)
  749.             (cl-push (list var nil) loop-for-bindings)
  750.             (cl-push (list var (list 'aref temp-vec temp-idx))
  751.                  loop-for-sets))))
  752.  
  753.            ((memq word '(element elements))
  754.         (let ((ref (or (memq (car args) '(in-ref of-ref))
  755.                    (and (not (memq (car args) '(in of)))
  756.                     (error "Expected `of'"))))
  757.               (seq (cl-pop2 args))
  758.               (temp-seq (gensym))
  759.               (temp-idx (if (eq (car args) 'using)
  760.                     (if (and (= (length (cadr args)) 2)
  761.                          (eq (caadr args) 'index))
  762.                     (cadr (cl-pop2 args))
  763.                       (error "Bad `using' clause"))
  764.                   (gensym))))
  765.           (cl-push (list temp-seq seq) loop-for-bindings)
  766.           (cl-push (list temp-idx 0) loop-for-bindings)
  767.           (if ref
  768.               (let ((temp-len (gensym)))
  769.             (cl-push (list temp-len (list 'length temp-seq))
  770.                  loop-for-bindings)
  771.             (cl-push (list var (list 'elt temp-seq temp-idx))
  772.                  loop-symbol-macs)
  773.             (cl-push (list '< temp-idx temp-len) loop-body))
  774.             (cl-push (list var nil) loop-for-bindings)
  775.             (cl-push (list 'and temp-seq
  776.                    (list 'or (list 'consp temp-seq)
  777.                      (list '< temp-idx
  778.                            (list 'length temp-seq))))
  779.                  loop-body)
  780.             (cl-push (list var (list 'if (list 'consp temp-seq)
  781.                          (list 'pop temp-seq)
  782.                          (list 'aref temp-seq temp-idx)))
  783.                  loop-for-sets))
  784.           (cl-push (list temp-idx (list '1+ temp-idx))
  785.                loop-for-steps)))
  786.  
  787.            ((memq word hash-types)
  788.         (or (memq (car args) '(in of)) (error "Expected `of'"))
  789.         (let* ((table (cl-pop2 args))
  790.                (other (if (eq (car args) 'using)
  791.                   (if (and (= (length (cadr args)) 2)
  792.                        (memq (caadr args) hash-types)
  793.                        (not (eq (caadr args) word)))
  794.                       (cadr (cl-pop2 args))
  795.                     (error "Bad `using' clause"))
  796.                 (gensym))))
  797.           (if (memq word '(hash-value hash-values))
  798.               (setq var (prog1 other (setq other var))))
  799.           (setq loop-map-form
  800.             (list 'maphash (list 'function
  801.                          (list* 'lambda (list var other)
  802.                             '--cl-map)) table))))
  803.  
  804.            ((memq word '(symbol present-symbol external-symbol
  805.                  symbols present-symbols external-symbols))
  806.         (let ((ob (and (memq (car args) '(in of)) (cl-pop2 args))))
  807.           (setq loop-map-form
  808.             (list 'mapatoms (list 'function
  809.                           (list* 'lambda (list var)
  810.                              '--cl-map)) ob))))
  811.  
  812.            ((memq word '(overlay overlays extent extents))
  813.         (let ((buf nil) (from nil) (to nil))
  814.           (while (memq (car args) '(in of from to))
  815.             (cond ((eq (car args) 'from) (setq from (cl-pop2 args)))
  816.               ((eq (car args) 'to) (setq to (cl-pop2 args)))
  817.               (t (setq buf (cl-pop2 args)))))
  818.           (setq loop-map-form
  819.             (list 'cl-map-extents
  820.                   (list 'function (list 'lambda (list var (gensym))
  821.                             '(progn . --cl-map) nil))
  822.                   buf from to))))
  823.  
  824.            ((memq word '(interval intervals))
  825.         (let ((buf nil) (prop nil) (from nil) (to nil)
  826.               (var1 (gensym)) (var2 (gensym)))
  827.           (while (memq (car args) '(in of property from to))
  828.             (cond ((eq (car args) 'from) (setq from (cl-pop2 args)))
  829.               ((eq (car args) 'to) (setq to (cl-pop2 args)))
  830.               ((eq (car args) 'property)
  831.                (setq prop (cl-pop2 args)))
  832.               (t (setq buf (cl-pop2 args)))))
  833.           (if (and (consp var) (symbolp (car var)) (symbolp (cdr var)))
  834.               (setq var1 (car var) var2 (cdr var))
  835.             (cl-push (list var (list 'cons var1 var2)) loop-for-sets))
  836.           (setq loop-map-form
  837.             (list 'cl-map-intervals
  838.                   (list 'function (list 'lambda (list var1 var2)
  839.                             '(progn . --cl-map)))
  840.                   buf prop from to))))
  841.  
  842.            ((memq word key-types)
  843.         (or (memq (car args) '(in of)) (error "Expected `of'"))
  844.         (let ((map (cl-pop2 args))
  845.               (other (if (eq (car args) 'using)
  846.                  (if (and (= (length (cadr args)) 2)
  847.                       (memq (caadr args) key-types)
  848.                       (not (eq (caadr args) word)))
  849.                      (cadr (cl-pop2 args))
  850.                    (error "Bad `using' clause"))
  851.                    (gensym))))
  852.           (if (memq word '(key-binding key-bindings))
  853.               (setq var (prog1 other (setq other var))))
  854.           (setq loop-map-form
  855.             (list (if (memq word '(key-seq key-seqs))
  856.                   'cl-map-keymap-recursively 'cl-map-keymap)
  857.                   (list 'function (list* 'lambda (list var other)
  858.                              '--cl-map)) map))))
  859.  
  860.            ((memq word '(frame frames screen screens))
  861.         (let ((temp (gensym)))
  862.           (cl-push (list var (if (eq cl-emacs-type 'lucid)
  863.                      '(selected-screen) '(selected-frame)))
  864.                loop-for-bindings)
  865.           (cl-push (list temp nil) loop-for-bindings)
  866.           (cl-push (list 'prog1 (list 'not (list 'eq var temp))
  867.                  (list 'or temp (list 'setq temp var)))
  868.                loop-body)
  869.           (cl-push (list var (list (if (eq cl-emacs-type 'lucid)
  870.                            'next-screen 'next-frame) var))
  871.                loop-for-steps)))
  872.  
  873.            ((memq word '(window windows))
  874.         (let ((scr (and (memq (car args) '(in of)) (cl-pop2 args)))
  875.               (temp (gensym)))
  876.           (cl-push (list var (if scr
  877.                      (list (if (eq cl-emacs-type 'lucid)
  878.                            'screen-selected-window
  879.                          'frame-selected-window) scr)
  880.                        '(selected-window)))
  881.                loop-for-bindings)
  882.           (cl-push (list temp nil) loop-for-bindings)
  883.           (cl-push (list 'prog1 (list 'not (list 'eq var temp))
  884.                  (list 'or temp (list 'setq temp var)))
  885.                loop-body)
  886.           (cl-push (list var (list 'next-window var)) loop-for-steps)))
  887.  
  888.            (t
  889.         (let ((handler (and (symbolp word)
  890.                     (get word 'cl-loop-for-handler))))
  891.           (if handler
  892.               (funcall handler var)
  893.             (error "Expected a `for' preposition, found %s" word)))))
  894.           (eq (car args) 'and))
  895.       (setq ands t)
  896.       (cl-pop args))
  897.     (if (and ands loop-for-bindings)
  898.         (cl-push (nreverse loop-for-bindings) loop-bindings)
  899.       (setq loop-bindings (nconc (mapcar 'list loop-for-bindings)
  900.                      loop-bindings)))
  901.     (if loop-for-sets
  902.         (cl-push (list 'progn
  903.                (cl-loop-let (nreverse loop-for-sets) 'setq ands)
  904.                t) loop-body))
  905.     (if loop-for-steps
  906.         (cl-push (cons (if ands 'psetq 'setq)
  907.                (apply 'append (nreverse loop-for-steps)))
  908.              loop-steps))))
  909.  
  910.      ((eq word 'repeat)
  911.       (let ((temp (gensym)))
  912.     (cl-push (list (list temp (cl-pop args))) loop-bindings)
  913.     (cl-push (list '>= (list 'setq temp (list '1- temp)) 0) loop-body)))
  914.  
  915.      ((eq word 'collect)
  916.       (let ((what (cl-pop args))
  917.         (var (cl-loop-handle-accum nil 'nreverse)))
  918.     (if (eq var loop-accum-var)
  919.         (cl-push (list 'progn (list 'push what var) t) loop-body)
  920.       (cl-push (list 'progn
  921.              (list 'setq var (list 'nconc var (list 'list what)))
  922.              t) loop-body))))
  923.  
  924.      ((memq word '(nconc nconcing append appending))
  925.       (let ((what (cl-pop args))
  926.         (var (cl-loop-handle-accum nil 'nreverse)))
  927.     (cl-push (list 'progn
  928.                (list 'setq var
  929.                  (if (eq var loop-accum-var)
  930.                  (list 'nconc
  931.                        (list (if (memq word '(nconc nconcing))
  932.                          'nreverse 'reverse)
  933.                          what)
  934.                        var)
  935.                    (list (if (memq word '(nconc nconcing))
  936.                      'nconc 'append)
  937.                      var what))) t) loop-body)))
  938.  
  939.      ((memq word '(concat concating))
  940.       (let ((what (cl-pop args))
  941.         (var (cl-loop-handle-accum "")))
  942.     (cl-push (list 'progn (list 'callf 'concat var what) t) loop-body)))
  943.  
  944.      ((memq word '(vconcat vconcating))
  945.       (let ((what (cl-pop args))
  946.         (var (cl-loop-handle-accum [])))
  947.     (cl-push (list 'progn (list 'callf 'vconcat var what) t) loop-body)))
  948.  
  949.      ((memq word '(sum summing))
  950.       (let ((what (cl-pop args))
  951.         (var (cl-loop-handle-accum 0)))
  952.     (cl-push (list 'progn (list 'incf var what) t) loop-body)))
  953.  
  954.      ((memq word '(count counting))
  955.       (let ((what (cl-pop args))
  956.         (var (cl-loop-handle-accum 0)))
  957.     (cl-push (list 'progn (list 'if what (list 'incf var)) t) loop-body)))
  958.  
  959.      ((memq word '(minimize minimizing maximize maximizing))
  960.       (let* ((what (cl-pop args))
  961.          (temp (if (cl-simple-expr-p what) what (gensym)))
  962.          (var (cl-loop-handle-accum nil))
  963.          (func (intern (substring (symbol-name word) 0 3)))
  964.          (set (list 'setq var (list 'if var (list func var temp) temp))))
  965.     (cl-push (list 'progn (if (eq temp what) set
  966.                 (list 'let (list (list temp what)) set))
  967.                t) loop-body)))
  968.  
  969.      ((eq word 'with)
  970.       (let ((bindings nil))
  971.     (while (progn (cl-push (list (cl-pop args)
  972.                      (and (eq (car args) '=) (cl-pop2 args)))
  973.                    bindings)
  974.               (eq (car args) 'and))
  975.       (cl-pop args))
  976.     (cl-push (nreverse bindings) loop-bindings)))
  977.  
  978.      ((eq word 'while)
  979.       (cl-push (cl-pop args) loop-body))
  980.  
  981.      ((eq word 'until)
  982.       (cl-push (list 'not (cl-pop args)) loop-body))
  983.  
  984.      ((eq word 'always)
  985.       (or loop-finish-flag (setq loop-finish-flag (gensym)))
  986.       (cl-push (list 'setq loop-finish-flag (cl-pop args)) loop-body)
  987.       (setq loop-result t))
  988.  
  989.      ((eq word 'never)
  990.       (or loop-finish-flag (setq loop-finish-flag (gensym)))
  991.       (cl-push (list 'setq loop-finish-flag (list 'not (cl-pop args)))
  992.            loop-body)
  993.       (setq loop-result t))
  994.  
  995.      ((eq word 'thereis)
  996.       (or loop-finish-flag (setq loop-finish-flag (gensym)))
  997.       (or loop-result-var (setq loop-result-var (gensym)))
  998.       (cl-push (list 'setq loop-finish-flag
  999.              (list 'not (list 'setq loop-result-var (cl-pop args))))
  1000.            loop-body))
  1001.  
  1002.      ((memq word '(if when unless))
  1003.       (let* ((cond (cl-pop args))
  1004.          (then (let ((loop-body nil))
  1005.              (cl-parse-loop-clause)
  1006.              (cl-loop-build-ands (nreverse loop-body))))
  1007.          (else (let ((loop-body nil))
  1008.              (if (eq (car args) 'else)
  1009.              (progn (cl-pop args) (cl-parse-loop-clause)))
  1010.              (cl-loop-build-ands (nreverse loop-body))))
  1011.          (simple (and (eq (car then) t) (eq (car else) t))))
  1012.     (if (eq (car args) 'end) (cl-pop args))
  1013.     (if (eq word 'unless) (setq then (prog1 else (setq else then))))
  1014.     (let ((form (cons (if simple (cons 'progn (nth 1 then)) (nth 2 then))
  1015.               (if simple (nth 1 else) (list (nth 2 else))))))
  1016.       (if (cl-expr-contains form 'it)
  1017.           (let ((temp (gensym)))
  1018.         (cl-push (list temp) loop-bindings)
  1019.         (setq form (list* 'if (list 'setq temp cond)
  1020.                   (subst temp 'it form))))
  1021.         (setq form (list* 'if cond form)))
  1022.       (cl-push (if simple (list 'progn form t) form) loop-body))))
  1023.  
  1024.      ((memq word '(do doing))
  1025.       (let ((body nil))
  1026.     (or (consp (car args)) (error "Syntax error on `do' clause"))
  1027.     (while (consp (car args)) (cl-push (cl-pop args) body))
  1028.     (cl-push (cons 'progn (nreverse (cons t body))) loop-body)))
  1029.  
  1030.      ((eq word 'return)
  1031.       (or loop-finish-flag (setq loop-finish-flag (gensym)))
  1032.       (or loop-result-var (setq loop-result-var (gensym)))
  1033.       (cl-push (list 'setq loop-result-var (cl-pop args)
  1034.              loop-finish-flag nil) loop-body))
  1035.  
  1036.      (t
  1037.       (let ((handler (and (symbolp word) (get word 'cl-loop-handler))))
  1038.     (or handler (error "Expected a loop keyword, found %s" word))
  1039.     (funcall handler))))
  1040.     (if (eq (car args) 'and)
  1041.     (progn (cl-pop args) (cl-parse-loop-clause)))))
  1042.  
  1043. (defun cl-loop-let (specs body par)   ; uses loop-*
  1044.   (let ((p specs) (temps nil) (new nil))
  1045.     (while (and p (or (symbolp (car-safe (car p))) (null (cadar p))))
  1046.       (setq p (cdr p)))
  1047.     (and par p
  1048.      (progn
  1049.        (setq par nil p specs)
  1050.        (while p
  1051.          (or (cl-const-expr-p (cadar p))
  1052.          (let ((temp (gensym)))
  1053.            (cl-push (list temp (cadar p)) temps)
  1054.            (setcar (cdar p) temp)))
  1055.          (setq p (cdr p)))))
  1056.     (while specs
  1057.       (if (and (consp (car specs)) (listp (caar specs)))
  1058.       (let* ((spec (caar specs)) (nspecs nil)
  1059.          (expr (cadr (cl-pop specs)))
  1060.          (temp (cdr (or (assq spec loop-destr-temps)
  1061.                 (car (cl-push (cons spec (or (last spec 0)
  1062.                                  (gensym)))
  1063.                           loop-destr-temps))))))
  1064.         (cl-push (list temp expr) new)
  1065.         (while (consp spec)
  1066.           (cl-push (list (cl-pop spec)
  1067.                  (and expr (list (if spec 'pop 'car) temp)))
  1068.                nspecs))
  1069.         (setq specs (nconc (nreverse nspecs) specs)))
  1070.     (cl-push (cl-pop specs) new)))
  1071.     (if (eq body 'setq)
  1072.     (let ((set (cons (if par 'psetq 'setq) (apply 'nconc (nreverse new)))))
  1073.       (if temps (list 'let* (nreverse temps) set) set))
  1074.       (list* (if par 'let 'let*)
  1075.          (nconc (nreverse temps) (nreverse new)) body))))
  1076.  
  1077. (defun cl-loop-handle-accum (def &optional func)   ; uses args, loop-*
  1078.   (if (eq (car args) 'into)
  1079.       (let ((var (cl-pop2 args)))
  1080.     (or (memq var loop-accum-vars)
  1081.         (progn (cl-push (list (list var def)) loop-bindings)
  1082.            (cl-push var loop-accum-vars)))
  1083.     var)
  1084.     (or loop-accum-var
  1085.     (progn
  1086.       (cl-push (list (list (setq loop-accum-var (gensym)) def))
  1087.            loop-bindings)
  1088.       (setq loop-result (if func (list func loop-accum-var)
  1089.                   loop-accum-var))
  1090.       loop-accum-var))))
  1091.  
  1092. (defun cl-loop-build-ands (clauses)
  1093.   (let ((ands nil)
  1094.     (body nil))
  1095.     (while clauses
  1096.       (if (and (eq (car-safe (car clauses)) 'progn)
  1097.            (eq (car (last (car clauses))) t))
  1098.       (if (cdr clauses)
  1099.           (setq clauses (cons (nconc (butlast (car clauses))
  1100.                      (if (eq (car-safe (cadr clauses))
  1101.                          'progn)
  1102.                          (cdadr clauses)
  1103.                        (list (cadr clauses))))
  1104.                   (cddr clauses)))
  1105.         (setq body (cdr (butlast (cl-pop clauses)))))
  1106.     (cl-push (cl-pop clauses) ands)))
  1107.     (setq ands (or (nreverse ands) (list t)))
  1108.     (list (if (cdr ands) (cons 'and ands) (car ands))
  1109.       body
  1110.       (let ((full (if body
  1111.               (append ands (list (cons 'progn (append body '(t)))))
  1112.             ands)))
  1113.         (if (cdr full) (cons 'and full) (car full))))))
  1114.  
  1115.  
  1116. ;;; Other iteration control structures.
  1117.  
  1118. (defmacro do (steps endtest &rest body)
  1119.   "The Common Lisp `do' loop.
  1120. Format is: (do ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
  1121.   (cl-expand-do-loop steps endtest body nil))
  1122.  
  1123. (defmacro do* (steps endtest &rest body)
  1124.   "The Common Lisp `do*' loop.
  1125. Format is: (do* ((VAR INIT [STEP])...) (END-TEST [RESULT...]) BODY...)"
  1126.   (cl-expand-do-loop steps endtest body t))
  1127.  
  1128. (defun cl-expand-do-loop (steps endtest body star)
  1129.   (list 'block nil
  1130.     (list* (if star 'let* 'let)
  1131.            (mapcar (function (lambda (c)
  1132.                    (if (consp c) (list (car c) (nth 1 c)) c)))
  1133.                steps)
  1134.            (list* 'while (list 'not (car endtest))
  1135.               (append body
  1136.                   (let ((sets (mapcar
  1137.                        (function
  1138.                         (lambda (c)
  1139.                           (and (consp c) (cdr (cdr c))
  1140.                            (list (car c) (nth 2 c)))))
  1141.                        steps)))
  1142.                 (setq sets (delq nil sets))
  1143.                 (and sets
  1144.                      (list (cons (if (or star (not (cdr sets)))
  1145.                              'setq 'psetq)
  1146.                          (apply 'append sets)))))))
  1147.            (or (cdr endtest) '(nil)))))
  1148.  
  1149. (defmacro dolist (spec &rest body)
  1150.   "(dolist (VAR LIST [RESULT]) BODY...): loop over a list.
  1151. Evaluate BODY with VAR bound to each `car' from LIST, in turn.
  1152. Then evaluate RESULT to get return value, default nil."
  1153.   (let ((temp (gensym "--dolist-temp--")))
  1154.     (list 'block nil
  1155.       (list* 'let (list (list temp (nth 1 spec)) (car spec))
  1156.          (list* 'while temp (list 'setq (car spec) (list 'car temp))
  1157.             (append body (list (list 'setq temp
  1158.                          (list 'cdr temp)))))
  1159.          (if (cdr (cdr spec))
  1160.              (cons (list 'setq (car spec) nil) (cdr (cdr spec)))
  1161.            '(nil))))))
  1162.  
  1163. (defmacro dotimes (spec &rest body)
  1164.   "(dotimes (VAR COUNT [RESULT]) BODY...): loop a certain number of times.
  1165. Evaluate BODY with VAR bound to successive integers from 0, inclusive,
  1166. to COUNT, exclusive.  Then evaluate RESULT to get return value, default
  1167. nil."
  1168.   (let ((temp (gensym "--dotimes-temp--")))
  1169.     (list 'block nil
  1170.       (list* 'let (list (list temp (nth 1 spec)) (list (car spec) 0))
  1171.          (list* 'while (list '< (car spec) temp)
  1172.             (append body (list (list 'incf (car spec)))))
  1173.          (or (cdr (cdr spec)) '(nil))))))
  1174.  
  1175. (defmacro do-symbols (spec &rest body)
  1176.   "(dosymbols (VAR [OBARRAY [RESULT]]) BODY...): loop over all symbols.
  1177. Evaluate BODY with VAR bound to each interned symbol, or to each symbol
  1178. from OBARRAY."
  1179.   ;; Apparently this doesn't have an implicit block.
  1180.   (list 'block nil
  1181.     (list 'let (list (car spec))
  1182.           (list* 'mapatoms
  1183.              (list 'function (list* 'lambda (list (car spec)) body))
  1184.              (and (cadr spec) (list (cadr spec))))
  1185.           (caddr spec))))
  1186.  
  1187. (defmacro do-all-symbols (spec &rest body)
  1188.   (list* 'do-symbols (list (car spec) nil (cadr spec)) body))
  1189.  
  1190.  
  1191. ;;; Assignments.
  1192.  
  1193. (defmacro psetq (&rest args)
  1194.   "(psetq SYM VAL SYM VAL ...): set SYMs to the values VALs in parallel.
  1195. This is like `setq', except that all VAL forms are evaluated (in order)
  1196. before assigning any symbols SYM to the corresponding values."
  1197.   (cons 'psetf args))
  1198.  
  1199.  
  1200. ;;; Binding control structures.
  1201.  
  1202. (defmacro progv (symbols values &rest body)
  1203.   "(progv SYMBOLS VALUES BODY...): bind SYMBOLS to VALUES dynamically in BODY.
  1204. The forms SYMBOLS and VALUES are evaluated, and must evaluate to lists.
  1205. Each SYMBOL in the first list is bound to the corresponding VALUE in the
  1206. second list (or made unbound if VALUES is shorter than SYMBOLS); then the
  1207. BODY forms are executed and their result is returned.  This is much like
  1208. a `let' form, except that the list of symbols can be computed at run-time."
  1209.   (list 'let '((cl-progv-save nil))
  1210.     (list 'unwind-protect
  1211.           (list* 'progn (list 'cl-progv-before symbols values) body)
  1212.           '(cl-progv-after))))
  1213.  
  1214. ;;; This should really have some way to shadow 'byte-compile properties, etc.
  1215. (defmacro flet (bindings &rest body)
  1216.   "(flet ((FUNC ARGLIST BODY...) ...) FORM...): make temporary function defns.
  1217. This is an analogue of `let' that operates on the function cell of FUNC
  1218. rather than its value cell.  The FORMs are evaluated with the specified
  1219. function definitions in place, then the definitions are undone (the FUNCs
  1220. go back to their previous definitions, or lack thereof)."
  1221.   (list* 'letf*
  1222.      (mapcar
  1223.       (function
  1224.        (lambda (x)
  1225.          (let ((func (list 'function*
  1226.                    (list 'lambda (cadr x)
  1227.                      (list* 'block (car x) (cddr x))))))
  1228.            (if (and (cl-compiling-file)
  1229.             (boundp 'byte-compile-function-environment))
  1230.            (cl-push (cons (car x) (eval func))
  1231.                 byte-compile-function-environment))
  1232.            (list (list 'symbol-function (list 'quote (car x))) func))))
  1233.       bindings)
  1234.      body))
  1235.  
  1236. (defmacro labels (&rest args) (cons 'flet args))
  1237.  
  1238. ;; The following ought to have a better definition for use with newer
  1239. ;; byte compilers.
  1240. (defmacro macrolet (bindings &rest body)
  1241.   "(macrolet ((NAME ARGLIST BODY...) ...) FORM...): make temporary macro defns.
  1242. This is like `flet', but for macros instead of functions."
  1243.   (if (cdr bindings)
  1244.       (list 'macrolet
  1245.         (list (car bindings)) (list* 'macrolet (cdr bindings) body))
  1246.     (if (null bindings) (cons 'progn body)
  1247.       (let* ((name (caar bindings))
  1248.          (res (cl-transform-lambda (cdar bindings) name)))
  1249.     (eval (car res))
  1250.     (cl-macroexpand-all (cons 'progn body)
  1251.                 (cons (list* name 'lambda (cdr res))
  1252.                   cl-macro-environment))))))
  1253.  
  1254. (defmacro symbol-macrolet (bindings &rest body)
  1255.   "(symbol-macrolet ((NAME EXPANSION) ...) FORM...): make symbol macro defns.
  1256. Within the body FORMs, references to the variable NAME will be replaced
  1257. by EXPANSION, and (setq NAME ...) will act like (setf EXPANSION ...)."
  1258.   (if (cdr bindings)
  1259.       (list 'symbol-macrolet
  1260.         (list (car bindings)) (list* 'symbol-macrolet (cdr bindings) body))
  1261.     (if (null bindings) (cons 'progn body)
  1262.       (cl-macroexpand-all (cons 'progn body)
  1263.               (cons (list (symbol-name (caar bindings))
  1264.                       (cadar bindings))
  1265.                 cl-macro-environment)))))
  1266.  
  1267. (defvar cl-closure-vars nil)
  1268. (defmacro lexical-let (bindings &rest body)
  1269.   "(lexical-let BINDINGS BODY...): like `let', but lexically scoped.
  1270. The main visible difference is that lambdas inside BODY will create
  1271. lexical closures as in Common Lisp."
  1272.   (let* ((cl-closure-vars cl-closure-vars)
  1273.      (vars (mapcar (function
  1274.             (lambda (x)
  1275.               (or (consp x) (setq x (list x)))
  1276.               (cl-push (gensym (format "--%s--" (car x)))
  1277.                    cl-closure-vars)
  1278.               (list (car x) (cadr x) (car cl-closure-vars))))
  1279.                bindings))
  1280.      (ebody 
  1281.       (cl-macroexpand-all
  1282.        (cons 'progn body)
  1283.        (nconc (mapcar (function (lambda (x)
  1284.                       (list (symbol-name (car x))
  1285.                         (list 'symbol-value (caddr x))
  1286.                         t))) vars)
  1287.           (list '(defun . cl-defun-expander))
  1288.           cl-macro-environment))))
  1289.     (if (not (get (car (last cl-closure-vars)) 'used))
  1290.     (list 'let (mapcar (function (lambda (x)
  1291.                        (list (caddr x) (cadr x)))) vars)
  1292.           (sublis (mapcar (function (lambda (x)
  1293.                       (cons (caddr x)
  1294.                         (list 'quote (caddr x)))))
  1295.                   vars)
  1296.               ebody))
  1297.       (list 'let (mapcar (function (lambda (x)
  1298.                      (list (caddr x)
  1299.                        (list 'make-symbol
  1300.                          (format "--%s--" (car x))))))
  1301.              vars)
  1302.         (apply 'append '(setf)
  1303.            (mapcar (function
  1304.                 (lambda (x)
  1305.                   (list (list 'symbol-value (caddr x)) (cadr x))))
  1306.                vars))
  1307.         ebody))))
  1308.  
  1309. (defmacro lexical-let* (bindings &rest body)
  1310.   "(lexical-let* BINDINGS BODY...): like `let*', but lexically scoped.
  1311. The main visible difference is that lambdas inside BODY will create
  1312. lexical closures as in Common Lisp."
  1313.   (if (null bindings) (cons 'progn body)
  1314.     (setq bindings (reverse bindings))
  1315.     (while bindings
  1316.       (setq body (list (list* 'lexical-let (list (cl-pop bindings)) body))))
  1317.     (car body)))
  1318.  
  1319. (defun cl-defun-expander (func &rest rest)
  1320.   (list 'progn
  1321.     (list 'defalias (list 'quote func)
  1322.           (list 'function (cons 'lambda rest)))
  1323.     (list 'quote func)))
  1324.  
  1325.  
  1326. ;;; Multiple values.
  1327.  
  1328. (defmacro multiple-value-bind (vars form &rest body)
  1329.   "(multiple-value-bind (SYM SYM...) FORM BODY): collect multiple return values.
  1330. FORM must return a list; the BODY is then executed with the first N elements
  1331. of this list bound (`let'-style) to each of the symbols SYM in turn.  This
  1332. is analogous to the Common Lisp `multiple-value-bind' macro, using lists to
  1333. simulate true multiple return values.  For compatibility, (values A B C) is
  1334. a synonym for (list A B C)."
  1335.   (let ((temp (gensym)) (n -1))
  1336.     (list* 'let* (cons (list temp form)
  1337.                (mapcar (function
  1338.                 (lambda (v)
  1339.                   (list v (list 'nth (setq n (1+ n)) temp))))
  1340.                    vars))
  1341.        body)))
  1342.  
  1343. (defmacro multiple-value-setq (vars form)
  1344.   "(multiple-value-setq (SYM SYM...) FORM): collect multiple return values.
  1345. FORM must return a list; the first N elements of this list are stored in
  1346. each of the symbols SYM in turn.  This is analogous to the Common Lisp
  1347. `multiple-value-setq' macro, using lists to simulate true multiple return
  1348. values.  For compatibility, (values A B C) is a synonym for (list A B C)."
  1349.   (cond ((null vars) (list 'progn form nil))
  1350.     ((null (cdr vars)) (list 'setq (car vars) (list 'car form)))
  1351.     (t
  1352.      (let* ((temp (gensym)) (n 0))
  1353.        (list 'let (list (list temp form))
  1354.          (list 'prog1 (list 'setq (cl-pop vars) (list 'car temp))
  1355.                (cons 'setq (apply 'nconc
  1356.                       (mapcar (function
  1357.                            (lambda (v)
  1358.                              (list v (list
  1359.                                   'nth
  1360.                                   (setq n (1+ n))
  1361.                                   temp))))
  1362.                           vars)))))))))
  1363.  
  1364.  
  1365. ;;; Declarations.
  1366.  
  1367. (defmacro locally (&rest body) (cons 'progn body))
  1368. (defmacro the (type form) form)
  1369.  
  1370. (defvar cl-proclaim-history t)    ; for future compilers
  1371. (defvar cl-declare-stack t)       ; for future compilers
  1372.  
  1373. (defun cl-do-proclaim (spec hist)
  1374.   (and hist (listp cl-proclaim-history) (cl-push spec cl-proclaim-history))
  1375.   (cond ((eq (car-safe spec) 'special)
  1376.      (if (boundp 'byte-compile-bound-variables)
  1377.          (setq byte-compile-bound-variables
  1378.            (append (cdr spec) byte-compile-bound-variables))))
  1379.  
  1380.     ((eq (car-safe spec) 'inline)
  1381.      (while (setq spec (cdr spec))
  1382.        (or (memq (get (car spec) 'byte-optimizer)
  1383.              '(nil byte-compile-inline-expand))
  1384.            (error "%s already has a byte-optimizer, can't make it inline"
  1385.               (car spec)))
  1386.        (put (car spec) 'byte-optimizer 'byte-compile-inline-expand)))
  1387.  
  1388.     ((eq (car-safe spec) 'notinline)
  1389.      (while (setq spec (cdr spec))
  1390.        (if (eq (get (car spec) 'byte-optimizer)
  1391.            'byte-compile-inline-expand)
  1392.            (put (car spec) 'byte-optimizer nil))))
  1393.  
  1394.     ((eq (car-safe spec) 'optimize)
  1395.      (let ((speed (assq (nth 1 (assq 'speed (cdr spec)))
  1396.                 '((0 nil) (1 t) (2 t) (3 t))))
  1397.            (safety (assq (nth 1 (assq 'safety (cdr spec)))
  1398.                  '((0 t) (1 t) (2 t) (3 nil)))))
  1399.        (if speed (setq cl-optimize-speed (car speed)
  1400.                byte-optimize (nth 1 speed)))
  1401.        (if safety (setq cl-optimize-safety (car safety)
  1402.                 byte-compile-delete-errors (nth 1 safety)))))
  1403.  
  1404.     ((and (eq (car-safe spec) 'warn) (boundp 'byte-compile-warnings))
  1405.      (if (eq byte-compile-warnings t)
  1406.          (setq byte-compile-warnings byte-compile-warning-types))
  1407.      (while (setq spec (cdr spec))
  1408.        (if (consp (car spec))
  1409.            (if (eq (cadar spec) 0)
  1410.            (setq byte-compile-warnings
  1411.              (delq (caar spec) byte-compile-warnings))
  1412.          (setq byte-compile-warnings
  1413.                (adjoin (caar spec) byte-compile-warnings)))))))
  1414.   nil)
  1415.  
  1416. ;;; Process any proclamations made before cl-macs was loaded.
  1417. (defvar cl-proclaims-deferred)
  1418. (let ((p (reverse cl-proclaims-deferred)))
  1419.   (while p (cl-do-proclaim (cl-pop p) t))
  1420.   (setq cl-proclaims-deferred nil))
  1421.  
  1422. (defmacro declare (&rest specs)
  1423.   (if (cl-compiling-file)
  1424.       (while specs
  1425.     (if (listp cl-declare-stack) (cl-push (car specs) cl-declare-stack))
  1426.     (cl-do-proclaim (cl-pop specs) nil)))
  1427.   nil)
  1428.  
  1429.  
  1430.  
  1431. ;;; Generalized variables.
  1432.  
  1433. (defmacro define-setf-method (func args &rest body)
  1434.   "(define-setf-method NAME ARGLIST BODY...): define a `setf' method.
  1435. This method shows how to handle `setf's to places of the form (NAME ARGS...).
  1436. The argument forms ARGS are bound according to ARGLIST, as if NAME were
  1437. going to be expanded as a macro, then the BODY forms are executed and must
  1438. return a list of five elements: a temporary-variables list, a value-forms
  1439. list, a store-variables list (of length one), a store-form, and an access-
  1440. form.  See `defsetf' for a simpler way to define most setf-methods."
  1441.   (append '(eval-when (compile load eval))
  1442.       (if (stringp (car body))
  1443.           (list (list 'put (list 'quote func) '(quote setf-documentation)
  1444.               (cl-pop body))))
  1445.       (list (cl-transform-function-property
  1446.          func 'setf-method (cons args body)))))
  1447.  
  1448. (defmacro defsetf (func arg1 &rest args)
  1449.   "(defsetf NAME FUNC): define a `setf' method.
  1450. This macro is an easy-to-use substitute for `define-setf-method' that works
  1451. well for simple place forms.  In the simple `defsetf' form, `setf's of
  1452. the form (setf (NAME ARGS...) VAL) are transformed to function or macro
  1453. calls of the form (FUNC ARGS... VAL).  Example: (defsetf aref aset).
  1454. Alternate form: (defsetf NAME ARGLIST (STORE) BODY...).
  1455. Here, the above `setf' call is expanded by binding the argument forms ARGS
  1456. according to ARGLIST, binding the value form VAL to STORE, then executing
  1457. BODY, which must return a Lisp form that does the necessary `setf' operation.
  1458. Actually, ARGLIST and STORE may be bound to temporary variables which are
  1459. introduced automatically to preserve proper execution order of the arguments.
  1460. Example: (defsetf nth (n x) (v) (list 'setcar (list 'nthcdr n x) v))."
  1461.   (if (listp arg1)
  1462.       (let* ((largs nil) (largsr nil)
  1463.          (temps nil) (tempsr nil)
  1464.          (restarg nil) (rest-temps nil)
  1465.          (store-var (car (prog1 (car args) (setq args (cdr args)))))
  1466.          (store-temp (intern (format "--%s--temp--" store-var)))
  1467.          (lets1 nil) (lets2 nil)
  1468.          (docstr nil) (p arg1))
  1469.     (if (stringp (car args))
  1470.         (setq docstr (prog1 (car args) (setq args (cdr args)))))
  1471.     (while (and p (not (eq (car p) '&aux)))
  1472.       (if (eq (car p) '&rest)
  1473.           (setq p (cdr p) restarg (car p))
  1474.         (or (memq (car p) '(&optional &key &allow-other-keys))
  1475.         (setq largs (cons (if (consp (car p)) (car (car p)) (car p))
  1476.                   largs)
  1477.               temps (cons (intern (format "--%s--temp--" (car largs)))
  1478.                   temps))))
  1479.       (setq p (cdr p)))
  1480.     (setq largs (nreverse largs) temps (nreverse temps))
  1481.     (if restarg
  1482.         (setq largsr (append largs (list restarg))
  1483.           rest-temps (intern (format "--%s--temp--" restarg))
  1484.           tempsr (append temps (list rest-temps)))
  1485.       (setq largsr largs tempsr temps))
  1486.     (let ((p1 largs) (p2 temps))
  1487.       (while p1
  1488.         (setq lets1 (cons (list (car p2)
  1489.                     (list 'gensym (format "--%s--" (car p1))))
  1490.                   lets1)
  1491.           lets2 (cons (list (car p1) (car p2)) lets2)
  1492.           p1 (cdr p1) p2 (cdr p2))))
  1493.     (if restarg (setq lets2 (cons (list restarg rest-temps) lets2)))
  1494.     (append (list 'define-setf-method func arg1)
  1495.         (and docstr (list docstr))
  1496.         (list
  1497.          (list 'let*
  1498.                (nreverse
  1499.             (cons (list store-temp
  1500.                     (list 'gensym (format "--%s--" store-var)))
  1501.                   (if restarg
  1502.                   (append
  1503.                    (list
  1504.                     (list rest-temps
  1505.                       (list 'mapcar '(quote gensym)
  1506.                         restarg)))
  1507.                    lets1)
  1508.                 lets1)))
  1509.                (list 'list  ; 'values
  1510.                  (cons (if restarg 'list* 'list) tempsr)
  1511.                  (cons (if restarg 'list* 'list) largsr)
  1512.                  (list 'list store-temp)
  1513.                  (cons 'let*
  1514.                    (cons (nreverse
  1515.                       (cons (list store-var store-temp)
  1516.                         lets2))
  1517.                      args))
  1518.                  (cons (if restarg 'list* 'list)
  1519.                    (cons (list 'quote func) tempsr)))))))
  1520.     (list 'defsetf func '(&rest args) '(store)
  1521.       (let ((call (list 'cons (list 'quote arg1)
  1522.                 '(append args (list store)))))
  1523.         (if (car args)
  1524.         (list 'list '(quote progn) call 'store)
  1525.           call)))))
  1526.  
  1527. ;;; Some standard place types from Common Lisp.
  1528. (defsetf aref aset)
  1529. (defsetf car setcar)
  1530. (defsetf cdr setcdr)
  1531. (defsetf elt (seq n) (store)
  1532.   (list 'if (list 'listp seq) (list 'setcar (list 'nthcdr n seq) store)
  1533.     (list 'aset seq n store)))
  1534. (defsetf get put)
  1535. (defsetf get* (x y &optional d) (store) (list 'put x y store))
  1536. (defsetf gethash (x h &optional d) (store) (list 'cl-puthash x store h))
  1537. (defsetf nth (n x) (store) (list 'setcar (list 'nthcdr n x) store))
  1538. (defsetf subseq (seq start &optional end) (new)
  1539.   (list 'progn (list 'replace seq new ':start1 start ':end1 end) new))
  1540. (defsetf symbol-function fset)
  1541. (defsetf symbol-plist setplist)
  1542. (defsetf symbol-value set)
  1543.  
  1544. ;;; Various car/cdr aliases.  Note that `cadr' is handled specially.
  1545. (defsetf first setcar)
  1546. (defsetf second (x) (store) (list 'setcar (list 'cdr x) store))
  1547. (defsetf third (x) (store) (list 'setcar (list 'cddr x) store))
  1548. (defsetf fourth (x) (store) (list 'setcar (list 'cdddr x) store))
  1549. (defsetf fifth (x) (store) (list 'setcar (list 'nthcdr 4 x) store))
  1550. (defsetf sixth (x) (store) (list 'setcar (list 'nthcdr 5 x) store))
  1551. (defsetf seventh (x) (store) (list 'setcar (list 'nthcdr 6 x) store))
  1552. (defsetf eighth (x) (store) (list 'setcar (list 'nthcdr 7 x) store))
  1553. (defsetf ninth (x) (store) (list 'setcar (list 'nthcdr 8 x) store))
  1554. (defsetf tenth (x) (store) (list 'setcar (list 'nthcdr 9 x) store))
  1555. (defsetf rest setcdr)
  1556.  
  1557. ;;; Some more Emacs-related place types.
  1558. (defsetf buffer-file-name set-visited-file-name t)
  1559. (defsetf buffer-modified-p set-buffer-modified-p t)
  1560. (defsetf buffer-name rename-buffer t)
  1561. (defsetf buffer-string () (store)
  1562.   (list 'progn '(erase-buffer) (list 'insert store)))
  1563. (defsetf buffer-substring cl-set-buffer-substring)
  1564. (defsetf current-buffer set-buffer)
  1565. (defsetf current-case-table set-case-table)
  1566. (defsetf current-column move-to-column t)
  1567. (defsetf current-global-map use-global-map t)
  1568. (defsetf current-input-mode () (store)
  1569.   (list 'progn (list 'apply 'set-input-mode store) store))
  1570. (defsetf current-local-map use-local-map t)
  1571. (defsetf current-window-configuration set-window-configuration t)
  1572. (defsetf default-file-modes set-default-file-modes t)
  1573. (defsetf default-value set-default)
  1574. (defsetf documentation-property put)
  1575. (defsetf extent-data set-extent-data)
  1576. (defsetf extent-face set-extent-face)
  1577. (defsetf extent-priority set-extent-priority)
  1578. (defsetf extent-end-position (ext) (store)
  1579.   (list 'progn (list 'set-extent-endpoints (list 'extent-start-position ext)
  1580.              store) store))
  1581. (defsetf extent-start-position (ext) (store)
  1582.   (list 'progn (list 'set-extent-endpoints store
  1583.              (list 'extent-end-position ext)) store))
  1584. (defsetf face-background (f &optional s) (x) (list 'set-face-background f x s))
  1585. (defsetf face-background-pixmap (f &optional s) (x)
  1586.   (list 'set-face-background-pixmap f x s))
  1587. (defsetf face-font (f &optional s) (x) (list 'set-face-font f x s))
  1588. (defsetf face-foreground (f &optional s) (x) (list 'set-face-foreground f x s))
  1589. (defsetf face-underline-p (f &optional s) (x)
  1590.   (list 'set-face-underline-p f x s))
  1591. (defsetf file-modes set-file-modes t)
  1592. (defsetf frame-height set-screen-height t)
  1593. (defsetf frame-parameters modify-frame-parameters t)
  1594. (defsetf frame-visible-p cl-set-frame-visible-p)
  1595. (defsetf frame-width set-screen-width t)
  1596. (defsetf getenv setenv t)
  1597. (defsetf get-register set-register)
  1598. (defsetf global-key-binding global-set-key)
  1599. (defsetf keymap-parent set-keymap-parent)
  1600. (defsetf local-key-binding local-set-key)
  1601. (defsetf mark set-mark t)
  1602. (defsetf mark-marker set-mark t)
  1603. (defsetf marker-position set-marker t)
  1604. (defsetf match-data store-match-data t)
  1605. (defsetf mouse-position (scr) (store)
  1606.   (list 'set-mouse-position scr (list 'car store) (list 'cadr store)
  1607.     (list 'cddr store)))
  1608. (defsetf overlay-get overlay-put)
  1609. (defsetf overlay-start (ov) (store)
  1610.   (list 'progn (list 'move-overlay ov store (list 'overlay-end ov)) store))
  1611. (defsetf overlay-end (ov) (store)
  1612.   (list 'progn (list 'move-overlay ov (list 'overlay-start ov) store) store))
  1613. (defsetf point goto-char)
  1614. (defsetf point-marker goto-char t)
  1615. (defsetf point-max () (store)
  1616.   (list 'progn (list 'narrow-to-region '(point-min) store) store))
  1617. (defsetf point-min () (store)
  1618.   (list 'progn (list 'narrow-to-region store '(point-max)) store))
  1619. (defsetf process-buffer set-process-buffer)
  1620. (defsetf process-filter set-process-filter)
  1621. (defsetf process-sentinel set-process-sentinel)
  1622. (defsetf read-mouse-position (scr) (store)
  1623.   (list 'set-mouse-position scr (list 'car store) (list 'cdr store)))
  1624. (defsetf screen-height set-screen-height t)
  1625. (defsetf screen-width set-screen-width t)
  1626. (defsetf selected-window select-window)
  1627. (defsetf selected-screen select-screen)
  1628. (defsetf selected-frame select-frame)
  1629. (defsetf standard-case-table set-standard-case-table)
  1630. (defsetf syntax-table set-syntax-table)
  1631. (defsetf visited-file-modtime set-visited-file-modtime t)
  1632. (defsetf window-buffer set-window-buffer t)
  1633. (defsetf window-display-table set-window-display-table t)
  1634. (defsetf window-dedicated-p set-window-dedicated-p t)
  1635. (defsetf window-height () (store)
  1636.   (list 'progn (list 'enlarge-window (list '- store '(window-height))) store))
  1637. (defsetf window-hscroll set-window-hscroll)
  1638. (defsetf window-point set-window-point)
  1639. (defsetf window-start set-window-start)
  1640. (defsetf window-width () (store)
  1641.   (list 'progn (list 'enlarge-window (list '- store '(window-width)) t) store))
  1642. (defsetf x-get-cutbuffer x-store-cutbuffer t)
  1643. (defsetf x-get-cut-buffer x-store-cut-buffer t)   ; groan.
  1644. (defsetf x-get-secondary-selection x-own-secondary-selection t)
  1645. (defsetf x-get-selection x-own-selection t)
  1646.  
  1647. ;;; More complex setf-methods.
  1648. ;;; These should take &environment arguments, but since full arglists aren't
  1649. ;;; available while compiling cl-macs, we fake it by referring to the global
  1650. ;;; variable cl-macro-environment directly.
  1651.  
  1652. (define-setf-method apply (func arg1 &rest rest)
  1653.   (or (and (memq (car-safe func) '(quote function function*))
  1654.        (symbolp (car-safe (cdr-safe func))))
  1655.       (error "First arg to apply in setf is not (function SYM): %s" func))
  1656.   (let* ((form (cons (nth 1 func) (cons arg1 rest)))
  1657.      (method (get-setf-method form cl-macro-environment)))
  1658.     (list (car method) (nth 1 method) (nth 2 method)
  1659.       (cl-setf-make-apply (nth 3 method) (cadr func) (car method))
  1660.       (cl-setf-make-apply (nth 4 method) (cadr func) (car method)))))
  1661.  
  1662. (defun cl-setf-make-apply (form func temps)
  1663.   (if (eq (car form) 'progn)
  1664.       (list* 'progn (cl-setf-make-apply (cadr form) func temps) (cddr form))
  1665.     (or (equal (last form) (last temps))
  1666.     (error "%s is not suitable for use with setf-of-apply" func))
  1667.     (list* 'apply (list 'quote (car form)) (cdr form))))
  1668.  
  1669. (define-setf-method nthcdr (n place)
  1670.   (let ((method (get-setf-method place cl-macro-environment))
  1671.     (n-temp (gensym "--nthcdr-n--"))
  1672.     (store-temp (gensym "--nthcdr-store--")))
  1673.     (list (cons n-temp (car method))
  1674.       (cons n (nth 1 method))
  1675.       (list store-temp)
  1676.       (list 'let (list (list (car (nth 2 method))
  1677.                  (list 'cl-set-nthcdr n-temp (nth 4 method)
  1678.                        store-temp)))
  1679.         (nth 3 method) store-temp)
  1680.       (list 'nthcdr n-temp (nth 4 method)))))
  1681.  
  1682. (define-setf-method getf (place tag &optional def)
  1683.   (let ((method (get-setf-method place cl-macro-environment))
  1684.     (tag-temp (gensym "--getf-tag--"))
  1685.     (def-temp (gensym "--getf-def--"))
  1686.     (store-temp (gensym "--getf-store--")))
  1687.     (list (append (car method) (list tag-temp def-temp))
  1688.       (append (nth 1 method) (list tag def))
  1689.       (list store-temp)
  1690.       (list 'let (list (list (car (nth 2 method))
  1691.                  (list 'cl-set-getf (nth 4 method)
  1692.                        tag-temp store-temp)))
  1693.         (nth 3 method) store-temp)
  1694.       (list 'getf (nth 4 method) tag-temp def-temp))))
  1695.  
  1696. (define-setf-method substring (place from &optional to)
  1697.   (let ((method (get-setf-method place cl-macro-environment))
  1698.     (from-temp (gensym "--substring-from--"))
  1699.     (to-temp (gensym "--substring-to--"))
  1700.     (store-temp (gensym "--substring-store--")))
  1701.     (list (append (car method) (list from-temp to-temp))
  1702.       (append (nth 1 method) (list from to))
  1703.       (list store-temp)
  1704.       (list 'let (list (list (car (nth 2 method))
  1705.                  (list 'cl-set-substring (nth 4 method)
  1706.                        from-temp to-temp store-temp)))
  1707.         (nth 3 method) store-temp)
  1708.       (list 'substring (nth 4 method) from-temp to-temp))))
  1709.  
  1710. ;;; Getting and optimizing setf-methods.
  1711. (defun get-setf-method (place &optional env)
  1712.   "Return a list of five values describing the setf-method for PLACE.
  1713. PLACE may be any Lisp form which can appear as the PLACE argument to
  1714. a macro like `setf' or `incf'."
  1715.   (if (symbolp place)
  1716.       (let ((temp (gensym "--setf--")))
  1717.     (list nil nil (list temp) (list 'setq place temp) place))
  1718.     (or (and (symbolp (car place))
  1719.          (let* ((func (car place))
  1720.             (name (symbol-name func))
  1721.             (method (get func 'setf-method))
  1722.             (case-fold-search nil))
  1723.            (or (and method
  1724.             (let ((cl-macro-environment env))
  1725.               (setq method (apply method (cdr place))))
  1726.             (if (and (consp method) (= (length method) 5))
  1727.                 method
  1728.               (error "Setf-method for %s returns malformed method"
  1729.                  func)))
  1730.            (and (string-match "\\`c[ad][ad][ad]?[ad]?r\\'" name)
  1731.             (get-setf-method (compiler-macroexpand place)))
  1732.            (and (eq func 'edebug-after)
  1733.             (get-setf-method (nth (1- (length place)) place)
  1734.                      env)))))
  1735.     (if (eq place (setq place (macroexpand place env)))
  1736.         (if (and (symbolp (car place)) (fboundp (car place))
  1737.              (symbolp (symbol-function (car place))))
  1738.         (get-setf-method (cons (symbol-function (car place))
  1739.                        (cdr place)) env)
  1740.           (error "No setf-method known for %s" (car place)))
  1741.       (get-setf-method place env)))))
  1742.  
  1743. (defun cl-setf-do-modify (place opt-expr)
  1744.   (let* ((method (get-setf-method place cl-macro-environment))
  1745.      (temps (car method)) (values (nth 1 method))
  1746.      (lets nil) (subs nil)
  1747.      (optimize (and (not (eq opt-expr 'no-opt))
  1748.             (or (and (not (eq opt-expr 'unsafe))
  1749.                  (cl-safe-expr-p opt-expr))
  1750.                 (cl-setf-simple-store-p (car (nth 2 method))
  1751.                             (nth 3 method)))))
  1752.      (simple (and optimize (consp place) (cl-simple-exprs-p (cdr place)))))
  1753.     (while values
  1754.       (if (or simple (cl-const-expr-p (car values)))
  1755.       (cl-push (cons (cl-pop temps) (cl-pop values)) subs)
  1756.     (cl-push (list (cl-pop temps) (cl-pop values)) lets)))
  1757.     (list (nreverse lets)
  1758.       (cons (car (nth 2 method)) (sublis subs (nth 3 method)))
  1759.       (sublis subs (nth 4 method)))))
  1760.  
  1761. (defun cl-setf-do-store (spec val)
  1762.   (let ((sym (car spec))
  1763.     (form (cdr spec)))
  1764.     (if (or (cl-const-expr-p val)
  1765.         (and (cl-simple-expr-p val) (eq (cl-expr-contains form sym) 1))
  1766.         (cl-setf-simple-store-p sym form))
  1767.     (subst val sym form)
  1768.       (list 'let (list (list sym val)) form))))
  1769.  
  1770. (defun cl-setf-simple-store-p (sym form)
  1771.   (and (consp form) (eq (cl-expr-contains form sym) 1)
  1772.        (eq (nth (1- (length form)) form) sym)
  1773.        (symbolp (car form)) (fboundp (car form))
  1774.        (not (eq (car-safe (symbol-function (car form))) 'macro))))
  1775.  
  1776. ;;; The standard modify macros.
  1777. (defmacro setf (&rest args)
  1778.   "(setf PLACE VAL PLACE VAL ...): set each PLACE to the value of its VAL.
  1779. This is a generalized version of `setq'; the PLACEs may be symbolic
  1780. references such as (car x) or (aref x i), as well as plain symbols.
  1781. For example, (setf (cadar x) y) is equivalent to (setcar (cdar x) y).
  1782. The return value is the last VAL in the list."
  1783.   (if (cdr (cdr args))
  1784.       (let ((sets nil))
  1785.     (while args (cl-push (list 'setf (cl-pop args) (cl-pop args)) sets))
  1786.     (cons 'progn (nreverse sets)))
  1787.     (if (symbolp (car args))
  1788.     (and args (cons 'setq args))
  1789.       (let* ((method (cl-setf-do-modify (car args) (nth 1 args)))
  1790.          (store (cl-setf-do-store (nth 1 method) (nth 1 args))))
  1791.     (if (car method) (list 'let* (car method) store) store)))))
  1792.  
  1793. (defmacro psetf (&rest args)
  1794.   "(psetf PLACE VAL PLACE VAL ...): set PLACEs to the values VALs in parallel.
  1795. This is like `setf', except that all VAL forms are evaluated (in order)
  1796. before assigning any PLACEs to the corresponding values."
  1797.   (let ((p args) (simple t) (vars nil))
  1798.     (while p
  1799.       (if (or (not (symbolp (car p))) (cl-expr-depends-p (nth 1 p) vars))
  1800.       (setq simple nil))
  1801.       (if (memq (car p) vars)
  1802.       (error "Destination duplicated in psetf: %s" (car p)))
  1803.       (cl-push (cl-pop p) vars)
  1804.       (or p (error "Odd number of arguments to psetf"))
  1805.       (cl-pop p))
  1806.     (if simple
  1807.     (list 'progn (cons 'setf args) nil)
  1808.       (setq args (reverse args))
  1809.       (let ((expr (list 'setf (cadr args) (car args))))
  1810.     (while (setq args (cddr args))
  1811.       (setq expr (list 'setf (cadr args) (list 'prog1 (car args) expr))))
  1812.     (list 'progn expr nil)))))
  1813.  
  1814. (defun cl-do-pop (place)
  1815.   (if (cl-simple-expr-p place)
  1816.       (list 'prog1 (list 'car place) (list 'setf place (list 'cdr place)))
  1817.     (let* ((method (cl-setf-do-modify place t))
  1818.        (temp (gensym "--pop--")))
  1819.       (list 'let*
  1820.         (append (car method)
  1821.             (list (list temp (nth 2 method))))
  1822.         (list 'prog1
  1823.           (list 'car temp)
  1824.           (cl-setf-do-store (nth 1 method) (list 'cdr temp)))))))
  1825.  
  1826. (defmacro remf (place tag)
  1827.   "(remf PLACE TAG): remove TAG from property list PLACE.
  1828. PLACE may be a symbol, or any generalized variable allowed by `setf'.
  1829. The form returns true if TAG was found and removed, nil otherwise."
  1830.   (let* ((method (cl-setf-do-modify place t))
  1831.      (tag-temp (and (not (cl-const-expr-p tag)) (gensym "--remf-tag--")))
  1832.      (val-temp (and (not (cl-simple-expr-p place))
  1833.             (gensym "--remf-place--")))
  1834.      (ttag (or tag-temp tag))
  1835.      (tval (or val-temp (nth 2 method))))
  1836.     (list 'let*
  1837.       (append (car method)
  1838.           (and val-temp (list (list val-temp (nth 2 method))))
  1839.           (and tag-temp (list (list tag-temp tag))))
  1840.       (list 'if (list 'eq ttag (list 'car tval))
  1841.         (list 'progn
  1842.               (cl-setf-do-store (nth 1 method) (list 'cddr tval))
  1843.               t)
  1844.         (list 'cl-do-remf tval ttag)))))
  1845.  
  1846. (defmacro shiftf (place &rest args)
  1847.   "(shiftf PLACE PLACE... VAL): shift left among PLACEs.
  1848. Example: (shiftf A B C) sets A to B, B to C, and returns the old A.
  1849. Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
  1850.   (if (not (memq nil (mapcar 'symbolp (butlast (cons place args)))))
  1851.       (list* 'prog1 place
  1852.          (let ((sets nil))
  1853.            (while args
  1854.          (cl-push (list 'setq place (car args)) sets)
  1855.          (setq place (cl-pop args)))
  1856.            (nreverse sets)))
  1857.     (let* ((places (reverse (cons place args)))
  1858.        (form (cl-pop places)))
  1859.       (while places
  1860.     (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
  1861.       (setq form (list 'let* (car method)
  1862.                (list 'prog1 (nth 2 method)
  1863.                  (cl-setf-do-store (nth 1 method) form))))))
  1864.       form)))
  1865.  
  1866. (defmacro rotatef (&rest args)
  1867.   "(rotatef PLACE...): rotate left among PLACEs.
  1868. Example: (rotatef A B C) sets A to B, B to C, and C to A.  It returns nil.
  1869. Each PLACE may be a symbol, or any generalized variable allowed by `setf'."
  1870.   (if (not (memq nil (mapcar 'symbolp args)))
  1871.       (and (cdr args)
  1872.        (let ((sets nil)
  1873.          (first (car args)))
  1874.          (while (cdr args)
  1875.            (setq sets (nconc sets (list (cl-pop args) (car args)))))
  1876.          (nconc (list 'psetf) sets (list (car args) first))))
  1877.     (let* ((places (reverse args))
  1878.        (temp (gensym "--rotatef--"))
  1879.        (form temp))
  1880.       (while (cdr places)
  1881.     (let ((method (cl-setf-do-modify (cl-pop places) 'unsafe)))
  1882.       (setq form (list 'let* (car method)
  1883.                (list 'prog1 (nth 2 method)
  1884.                  (cl-setf-do-store (nth 1 method) form))))))
  1885.       (let ((method (cl-setf-do-modify (car places) 'unsafe)))
  1886.     (list 'let* (append (car method) (list (list temp (nth 2 method))))
  1887.           (cl-setf-do-store (nth 1 method) form) nil)))))
  1888.  
  1889. (defmacro letf (bindings &rest body)
  1890.   "(letf ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
  1891. This is the analogue of `let', but with generalized variables (in the
  1892. sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
  1893. VALUE, then the BODY forms are executed.  On exit, either normally or
  1894. because of a `throw' or error, the PLACEs are set back to their original
  1895. values.  Note that this macro is *not* available in Common Lisp.
  1896. As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
  1897. the PLACE is not modified before executing BODY."
  1898.   (if (and (not (cdr bindings)) (cdar bindings) (symbolp (caar bindings)))
  1899.       (list* 'let bindings body)
  1900.     (let ((lets nil) (sets nil)
  1901.       (unsets nil) (rev (reverse bindings)))
  1902.       (while rev
  1903.     (let* ((place (if (symbolp (caar rev))
  1904.               (list 'symbol-value (list 'quote (caar rev)))
  1905.             (caar rev)))
  1906.            (value (cadar rev))
  1907.            (method (cl-setf-do-modify place 'no-opt))
  1908.            (save (gensym "--letf-save--"))
  1909.            (bound (and (memq (car place) '(symbol-value symbol-function))
  1910.                (gensym "--letf-bound--")))
  1911.            (temp (and (not (cl-const-expr-p value)) (cdr bindings)
  1912.               (gensym "--letf-val--"))))
  1913.       (setq lets (nconc (car method)
  1914.                 (if bound
  1915.                 (list (list bound
  1916.                         (list (if (eq (car place)
  1917.                               'symbol-value)
  1918.                               'boundp 'fboundp)
  1919.                           (nth 1 (nth 2 method))))
  1920.                       (list save (list 'and bound
  1921.                                (nth 2 method))))
  1922.                   (list (list save (nth 2 method))))
  1923.                 (and temp (list (list temp value)))
  1924.                 lets)
  1925.         body (list
  1926.               (list 'unwind-protect
  1927.                 (cons 'progn
  1928.                   (if (cdr (car rev))
  1929.                       (cons (cl-setf-do-store (nth 1 method)
  1930.                                   (or temp value))
  1931.                         body)
  1932.                     body))
  1933.                 (if bound
  1934.                 (list 'if bound
  1935.                       (cl-setf-do-store (nth 1 method) save)
  1936.                       (list (if (eq (car place) 'symbol-value)
  1937.                         'makunbound 'fmakunbound)
  1938.                         (nth 1 (nth 2 method))))
  1939.                   (cl-setf-do-store (nth 1 method) save))))
  1940.         rev (cdr rev))))
  1941.       (list* 'let* lets body))))
  1942.  
  1943. (defmacro letf* (bindings &rest body)
  1944.   "(letf* ((PLACE VALUE) ...) BODY...): temporarily bind to PLACEs.
  1945. This is the analogue of `let*', but with generalized variables (in the
  1946. sense of `setf') for the PLACEs.  Each PLACE is set to the corresponding
  1947. VALUE, then the BODY forms are executed.  On exit, either normally or
  1948. because of a `throw' or error, the PLACEs are set back to their original
  1949. values.  Note that this macro is *not* available in Common Lisp.
  1950. As a special case, if `(PLACE)' is used instead of `(PLACE VALUE)',
  1951. the PLACE is not modified before executing BODY."
  1952.   (if (null bindings)
  1953.       (cons 'progn body)
  1954.     (setq bindings (reverse bindings))
  1955.     (while bindings
  1956.       (setq body (list (list* 'letf (list (cl-pop bindings)) body))))
  1957.     (car body)))
  1958.  
  1959. (defmacro callf (func place &rest args)
  1960.   "(callf FUNC PLACE ARGS...): set PLACE to (FUNC PLACE ARGS...).
  1961. FUNC should be an unquoted function name.  PLACE may be a symbol,
  1962. or any generalized variable allowed by `setf'."
  1963.   (let* ((method (cl-setf-do-modify place (cons 'list args)))
  1964.      (rargs (cons (nth 2 method) args)))
  1965.     (list 'let* (car method)
  1966.       (cl-setf-do-store (nth 1 method)
  1967.                 (if (symbolp func) (cons func rargs)
  1968.                   (list* 'funcall (list 'function func)
  1969.                      rargs))))))
  1970.  
  1971. (defmacro callf2 (func arg1 place &rest args)
  1972.   "(callf2 FUNC ARG1 PLACE ARGS...): set PLACE to (FUNC ARG1 PLACE ARGS...).
  1973. Like `callf', but PLACE is the second argument of FUNC, not the first."
  1974.   (if (and (cl-safe-expr-p arg1) (cl-simple-expr-p place) (symbolp func))
  1975.       (list 'setf place (list* func arg1 place args))
  1976.     (let* ((method (cl-setf-do-modify place (cons 'list args)))
  1977.        (temp (and (not (cl-const-expr-p arg1)) (gensym "--arg1--")))
  1978.        (rargs (list* (or temp arg1) (nth 2 method) args)))
  1979.       (list 'let* (append (and temp (list (list temp arg1))) (car method))
  1980.         (cl-setf-do-store (nth 1 method)
  1981.                   (if (symbolp func) (cons func rargs)
  1982.                 (list* 'funcall (list 'function func)
  1983.                        rargs)))))))
  1984.  
  1985. (defmacro define-modify-macro (name arglist func &optional doc)
  1986.   "(define-modify-macro NAME ARGLIST FUNC): define a `setf'-like modify macro.
  1987. If NAME is called, it combines its PLACE argument with the other arguments
  1988. from ARGLIST using FUNC: (define-modify-macro incf (&optional (n 1)) +)"
  1989.   (if (memq '&key arglist) (error "&key not allowed in define-modify-macro"))
  1990.   (let ((place (gensym "--place--")))
  1991.     (list 'defmacro* name (cons place arglist) doc
  1992.       (list* (if (memq '&rest arglist) 'list* 'list)
  1993.          '(quote callf) (list 'quote func) place
  1994.          (cl-arglist-args arglist)))))
  1995.  
  1996.  
  1997. ;;; Structures.
  1998.  
  1999. (defmacro defstruct (struct &rest descs)
  2000.   "(defstruct (NAME OPTIONS...) (SLOT SLOT-OPTS...)...): define a struct type.
  2001. This macro defines a new Lisp data type called NAME, which contains data
  2002. stored in SLOTs.  This defines a `make-NAME' constructor, a `copy-NAME'
  2003. copier, a `NAME-p' predicate, and setf-able `NAME-SLOT' accessors."
  2004.   (let* ((name (if (consp struct) (car struct) struct))
  2005.      (opts (cdr-safe struct))
  2006.      (slots nil)
  2007.      (defaults nil)
  2008.      (conc-name (concat (symbol-name name) "-"))
  2009.      (constructor (intern (format "make-%s" name)))
  2010.      (constrs nil)
  2011.      (copier (intern (format "copy-%s" name)))
  2012.      (predicate (intern (format "%s-p" name)))
  2013.      (print-func nil) (print-auto nil)
  2014.      (safety (if (cl-compiling-file) cl-optimize-safety 3))
  2015.      (include nil)
  2016.      (tag (intern (format "cl-struct-%s" name)))
  2017.      (tag-symbol (intern (format "cl-struct-%s-tags" name)))
  2018.      (include-descs nil)
  2019.      (include-tag-symbol nil)
  2020.      (side-eff nil)
  2021.      (type nil)
  2022.      (named nil)
  2023.      (forms nil)
  2024.      pred-form pred-check)
  2025.     (if (stringp (car descs))
  2026.     (cl-push (list 'put (list 'quote name) '(quote structure-documentation)
  2027.                (cl-pop descs)) forms))
  2028.     (setq descs (cons '(cl-tag-slot)
  2029.               (mapcar (function (lambda (x) (if (consp x) x (list x))))
  2030.                   descs)))
  2031.     (while opts
  2032.       (let ((opt (if (consp (car opts)) (caar opts) (car opts)))
  2033.         (args (cdr-safe (cl-pop opts))))
  2034.     (cond ((eq opt ':conc-name)
  2035.            (if args
  2036.            (setq conc-name (if (car args)
  2037.                        (symbol-name (car args)) ""))))
  2038.           ((eq opt ':constructor)
  2039.            (if (cdr args)
  2040.            (cl-push args constrs)
  2041.          (if args (setq constructor (car args)))))
  2042.           ((eq opt ':copier)
  2043.            (if args (setq copier (car args))))
  2044.           ((eq opt ':predicate)
  2045.            (if args (setq predicate (car args))))
  2046.           ((eq opt ':include)
  2047.            (setq include (car args)
  2048.              include-descs (mapcar (function
  2049.                         (lambda (x)
  2050.                           (if (consp x) x (list x))))
  2051.                        (cdr args))
  2052.              include-tag-symbol (intern (format "cl-struct-%s-tags"
  2053.                             include))))
  2054.           ((eq opt ':print-function)
  2055.            (setq print-func (car args)))
  2056.           ((eq opt ':type)
  2057.            (setq type (car args)))
  2058.           ((eq opt ':named)
  2059.            (setq named t))
  2060.           ((eq opt ':initial-offset)
  2061.            (setq descs (nconc (make-list (car args) '(cl-skip-slot))
  2062.                   descs)))
  2063.           (t
  2064.            (error "Slot option %s unrecognized" opt)))))
  2065.     (if print-func
  2066.     (setq print-func (list 'progn
  2067.                    (list 'funcall (list 'function print-func)
  2068.                      'cl-x 'cl-s 'cl-n) t))
  2069.       (or type (and include (not (get include 'cl-struct-print)))
  2070.       (setq print-auto t
  2071.         print-func (and (or (not (or include type)) (null print-func))
  2072.                 (list 'progn
  2073.                       (list 'princ (format "#S(%s" name)
  2074.                         'cl-s))))))
  2075.     (if include
  2076.     (let ((inc-type (get include 'cl-struct-type))
  2077.           (old-descs (get include 'cl-struct-slots)))
  2078.       (or inc-type (error "%s is not a struct name" include))
  2079.       (and type (not (eq (car inc-type) type))
  2080.            (error ":type disagrees with :include for %s" name))
  2081.       (while include-descs
  2082.         (setcar (memq (or (assq (caar include-descs) old-descs)
  2083.                   (error "No slot %s in included struct %s"
  2084.                      (caar include-descs) include))
  2085.               old-descs)
  2086.             (cl-pop include-descs)))
  2087.       (setq descs (append old-descs (delq (assq 'cl-tag-slot descs) descs))
  2088.         type (car inc-type)
  2089.         named (assq 'cl-tag-slot descs))
  2090.       (if (cadr inc-type) (setq tag name named t))
  2091.       (cl-push (list 'pushnew (list 'quote tag) include-tag-symbol)
  2092.            forms))
  2093.       (if type
  2094.       (progn
  2095.         (or (memq type '(vector list))
  2096.         (error "Illegal :type specifier: %s" type))
  2097.         (if named (setq tag name)))
  2098.     (setq type 'vector named 'true)))
  2099.     (or named (setq descs (delq (assq 'cl-tag-slot descs) descs)))
  2100.     (cl-push (list 'defvar tag-symbol) forms)
  2101.     (setq pred-form (and named
  2102.              (let ((pos (- (length descs)
  2103.                        (length (memq (assq 'cl-tag-slot descs)
  2104.                              descs)))))
  2105.                (if (eq type 'vector)
  2106.                    (list 'and '(vectorp cl-x)
  2107.                      (list '>= '(length cl-x) (length descs))
  2108.                      (list 'memq (list 'aref 'cl-x pos)
  2109.                        tag-symbol))
  2110.                  (if (= pos 0)
  2111.                  (list 'memq '(car-safe cl-x) tag-symbol)
  2112.                    (list 'and '(consp cl-x)
  2113.                      (list 'memq (list 'nth pos 'cl-x)
  2114.                        tag-symbol))))))
  2115.       pred-check (and pred-form (> safety 0)
  2116.               (if (and (eq (caadr pred-form) 'vectorp)
  2117.                    (= safety 1))
  2118.                   (cons 'and (cdddr pred-form)) pred-form)))
  2119.     (let ((pos 0) (descp descs))
  2120.       (while descp
  2121.     (let* ((desc (cl-pop descp))
  2122.            (slot (car desc)))
  2123.       (if (memq slot '(cl-tag-slot cl-skip-slot))
  2124.           (progn
  2125.         (cl-push nil slots)
  2126.         (cl-push (and (eq slot 'cl-tag-slot) (list 'quote tag))
  2127.              defaults))
  2128.         (if (assq slot descp)
  2129.         (error "Duplicate slots named %s in %s" slot name))
  2130.         (let ((accessor (intern (format "%s%s" conc-name slot))))
  2131.           (cl-push slot slots)
  2132.           (cl-push (nth 1 desc) defaults)
  2133.           (cl-push (list*
  2134.             'defsubst* accessor '(cl-x)
  2135.             (append
  2136.              (and pred-check
  2137.                   (list (list 'or pred-check
  2138.                       (list 'error
  2139.                         (format "%s accessing a non-%s"
  2140.                             accessor name)
  2141.                         'cl-x))))
  2142.              (list (if (eq type 'vector) (list 'aref 'cl-x pos)
  2143.                  (if (= pos 0) '(car cl-x)
  2144.                    (list 'nth pos 'cl-x)))))) forms)
  2145.           (cl-push (cons accessor t) side-eff)
  2146.           (cl-push (list 'define-setf-method accessor '(cl-x)
  2147.                  (if (cadr (memq ':read-only (cddr desc)))
  2148.                  (list 'error (format "%s is a read-only slot"
  2149.                               accessor))
  2150.                    (list 'cl-struct-setf-expander 'cl-x
  2151.                      (list 'quote name) (list 'quote accessor)
  2152.                      (and pred-check (list 'quote pred-check))
  2153.                      pos)))
  2154.                forms)
  2155.           (if print-auto
  2156.           (nconc print-func
  2157.              (list (list 'princ (format " %s" slot) 'cl-s)
  2158.                    (list 'prin1 (list accessor 'cl-x) 'cl-s)))))))
  2159.     (setq pos (1+ pos))))
  2160.     (setq slots (nreverse slots)
  2161.       defaults (nreverse defaults))
  2162.     (and predicate pred-form
  2163.      (progn (cl-push (list 'defsubst* predicate '(cl-x)
  2164.                    (if (eq (car pred-form) 'and)
  2165.                    (append pred-form '(t))
  2166.                  (list 'and pred-form t))) forms)
  2167.         (cl-push (cons predicate 'error-free) side-eff)))
  2168.     (and copier
  2169.      (progn (cl-push (list 'defun copier '(x) '(copy-sequence x)) forms)
  2170.         (cl-push (cons copier t) side-eff)))
  2171.     (if constructor
  2172.     (cl-push (list constructor
  2173.                (cons '&key (delq nil (copy-sequence slots))))
  2174.          constrs))
  2175.     (while constrs
  2176.       (let* ((name (caar constrs))
  2177.          (args (cadr (cl-pop constrs)))
  2178.          (anames (cl-arglist-args args))
  2179.          (make (mapcar* (function (lambda (s d) (if (memq s anames) s d)))
  2180.                 slots defaults)))
  2181.     (cl-push (list 'defsubst* name
  2182.                (list* '&cl-defs (list 'quote (cons nil descs)) args)
  2183.                (cons type make)) forms)
  2184.     (if (cl-safe-expr-p (cons 'progn (mapcar 'second descs)))
  2185.         (cl-push (cons name t) side-eff))))
  2186.     (if print-auto (nconc print-func (list '(princ ")" cl-s) t)))
  2187.     (if print-func
  2188.     (cl-push (list 'push
  2189.                (list 'function
  2190.                  (list 'lambda '(cl-x cl-s cl-n)
  2191.                    (list 'and pred-form print-func)))
  2192.                'custom-print-functions) forms))
  2193.     (cl-push (list 'setq tag-symbol (list 'list (list 'quote tag))) forms)
  2194.     (cl-push (list* 'eval-when '(compile load eval)
  2195.             (list 'put (list 'quote name) '(quote cl-struct-slots)
  2196.               (list 'quote descs))
  2197.             (list 'put (list 'quote name) '(quote cl-struct-type)
  2198.               (list 'quote (list type (eq named t))))
  2199.             (list 'put (list 'quote name) '(quote cl-struct-print)
  2200.               print-auto)
  2201.             (mapcar (function (lambda (x)
  2202.                     (list 'put (list 'quote (car x))
  2203.                           '(quote side-effect-free)
  2204.                           (list 'quote (cdr x)))))
  2205.                 side-eff))
  2206.          forms)
  2207.     (cons 'progn (nreverse (cons (list 'quote name) forms)))))
  2208.  
  2209. (defun cl-struct-setf-expander (x name accessor pred-form pos)
  2210.   (let* ((temp (gensym "--x--")) (store (gensym "--store--")))
  2211.     (list (list temp) (list x) (list store)
  2212.       (append '(progn)
  2213.           (and pred-form
  2214.                (list (list 'or (subst temp 'cl-x pred-form)
  2215.                    (list 'error
  2216.                      (format
  2217.                       "%s storing a non-%s" accessor name)
  2218.                      temp))))
  2219.           (list (if (eq (car (get name 'cl-struct-type)) 'vector)
  2220.                 (list 'aset temp pos store)
  2221.               (list 'setcar
  2222.                 (if (<= pos 5)
  2223.                     (let ((xx temp))
  2224.                       (while (>= (setq pos (1- pos)) 0)
  2225.                     (setq xx (list 'cdr xx)))
  2226.                       xx)
  2227.                   (list 'nthcdr pos temp))
  2228.                 store))))
  2229.       (list accessor temp))))
  2230.  
  2231.  
  2232. ;;; Types and assertions.
  2233.  
  2234. (defmacro deftype (name args &rest body)
  2235.   "(deftype NAME ARGLIST BODY...): define NAME as a new data type.
  2236. The type name can then be used in `typecase', `check-type', etc."
  2237.   (list 'eval-when '(compile load eval)
  2238.     (cl-transform-function-property
  2239.      name 'cl-deftype-handler (cons (list* '&cl-defs ''('*) args) body))))
  2240.  
  2241. (defun cl-make-type-test (val type)
  2242.   (if (memq type '(character string-char)) (setq type '(integer 0 255)))
  2243.   (if (symbolp type)
  2244.       (cond ((get type 'cl-deftype-handler)
  2245.          (cl-make-type-test val (funcall (get type 'cl-deftype-handler))))
  2246.         ((memq type '(nil t)) type)
  2247.         ((eq type 'null) (list 'null val))
  2248.         ((eq type 'float) (list 'floatp-safe val))
  2249.         ((eq type 'real) (list 'numberp val))
  2250.         ((eq type 'fixnum) (list 'integerp val))
  2251.         (t
  2252.          (let* ((name (symbol-name type))
  2253.             (namep (intern (concat name "p"))))
  2254.            (if (fboundp namep) (list namep val)
  2255.          (list (intern (concat name "-p")) val)))))
  2256.     (cond ((get (car type) 'cl-deftype-handler)
  2257.        (cl-make-type-test val (apply (get (car type) 'cl-deftype-handler)
  2258.                      (cdr type))))
  2259.       ((memq (car-safe type) '(integer float real number))
  2260.        (delq t (list 'and (cl-make-type-test val (car type))
  2261.              (if (memq (cadr type) '(* nil)) t
  2262.                (if (consp (cadr type)) (list '> val (caadr type))
  2263.                  (list '>= val (cadr type))))
  2264.              (if (memq (caddr type) '(* nil)) t
  2265.                (if (consp (caddr type)) (list '< val (caaddr type))
  2266.                  (list '<= val (caddr type)))))))
  2267.       ((memq (car-safe type) '(and or not))
  2268.        (cons (car type)
  2269.          (mapcar (function (lambda (x) (cl-make-type-test val x)))
  2270.              (cdr type))))
  2271.       ((memq (car-safe type) '(member member*))
  2272.        (list 'and (list 'member* val (list 'quote (cdr type))) t))
  2273.       ((eq (car-safe type) 'satisfies) (list (cadr type) val))
  2274.       (t (error "Bad type spec: %s" type)))))
  2275.  
  2276. (defun typep (val type)   ; See compiler macro below.
  2277.   "Check that OBJECT is of type TYPE.
  2278. TYPE is a Common Lisp-style type specifier."
  2279.   (eval (cl-make-type-test 'val type)))
  2280.  
  2281. (defmacro check-type (form type &optional string)
  2282.   "Verify that FORM is of type TYPE; signal an error if not.
  2283. STRING is an optional description of the desired type."
  2284.   (and (or (not (cl-compiling-file))
  2285.        (< cl-optimize-speed 3) (= cl-optimize-safety 3))
  2286.        (let* ((temp (if (cl-simple-expr-p form 3) form (gensym)))
  2287.           (body (list 'or (cl-make-type-test temp type)
  2288.               (list 'signal '(quote wrong-type-argument)
  2289.                 (list 'list (or string (list 'quote type))
  2290.                       temp (list 'quote form))))))
  2291.      (if (eq temp form) (list 'progn body nil)
  2292.        (list 'let (list (list temp form)) body nil)))))
  2293.  
  2294. (defmacro assert (form &optional show-args string &rest args)
  2295.   "Verify that FORM returns non-nil; signal an error if not.
  2296. Second arg SHOW-ARGS means to include arguments of FORM in message.
  2297. Other args STRING and ARGS... are arguments to be passed to `error'.
  2298. They are not evaluated unless the assertion fails.  If STRING is
  2299. omitted, a default message listing FORM itself is used."
  2300.   (and (or (not (cl-compiling-file))
  2301.        (< cl-optimize-speed 3) (= cl-optimize-safety 3))
  2302.        (let ((sargs (and show-args (delq nil (mapcar
  2303.                           (function
  2304.                            (lambda (x)
  2305.                          (and (not (cl-const-expr-p x))
  2306.                               x))) (cdr form))))))
  2307.      (list 'progn
  2308.            (list 'or form
  2309.              (if string
  2310.              (list* 'error string (append sargs args))
  2311.                (list 'signal '(quote cl-assertion-failed)
  2312.                  (list* 'list (list 'quote form) sargs))))
  2313.            nil))))
  2314.  
  2315. (defmacro ignore-errors (&rest body)
  2316.   "Execute FORMS; if an error occurs, return nil.
  2317. Otherwise, return result of last FORM."
  2318.   (let ((err (gensym)))
  2319.     (list 'condition-case err (cons 'progn body) '(error nil))))
  2320.  
  2321.  
  2322. ;;; Some predicates for analyzing Lisp forms.  These are used by various
  2323. ;;; macro expanders to optimize the results in certain common cases.
  2324.  
  2325. (defconst cl-simple-funcs '(car cdr nth aref elt if and or + - 1+ 1- min max
  2326.                 car-safe cdr-safe progn prog1 prog2))
  2327. (defconst cl-safe-funcs '(* / % length memq list vector vectorp
  2328.               < > <= >= = error))
  2329.  
  2330. ;;; Check if no side effects, and executes quickly.
  2331. (defun cl-simple-expr-p (x &optional size)
  2332.   (or size (setq size 10))
  2333.   (if (and (consp x) (not (memq (car x) '(quote function function*))))
  2334.       (and (symbolp (car x))
  2335.        (or (memq (car x) cl-simple-funcs)
  2336.            (get (car x) 'side-effect-free))
  2337.        (progn
  2338.          (setq size (1- size))
  2339.          (while (and (setq x (cdr x))
  2340.              (setq size (cl-simple-expr-p (car x) size))))
  2341.          (and (null x) (>= size 0) size)))
  2342.     (and (> size 0) (1- size))))
  2343.  
  2344. (defun cl-simple-exprs-p (xs)
  2345.   (while (and xs (cl-simple-expr-p (car xs)))
  2346.     (setq xs (cdr xs)))
  2347.   (not xs))
  2348.  
  2349. ;;; Check if no side effects.
  2350. (defun cl-safe-expr-p (x)
  2351.   (or (not (and (consp x) (not (memq (car x) '(quote function function*)))))
  2352.       (and (symbolp (car x))
  2353.        (or (memq (car x) cl-simple-funcs)
  2354.            (memq (car x) cl-safe-funcs)
  2355.            (get (car x) 'side-effect-free))
  2356.        (progn
  2357.          (while (and (setq x (cdr x)) (cl-safe-expr-p (car x))))
  2358.          (null x)))))
  2359.  
  2360. ;;; Check if constant (i.e., no side effects or dependencies).
  2361. (defun cl-const-expr-p (x)
  2362.   (cond ((consp x)
  2363.      (or (eq (car x) 'quote)
  2364.          (and (memq (car x) '(function function*))
  2365.           (or (symbolp (nth 1 x))
  2366.               (and (eq (car-safe (nth 1 x)) 'lambda) 'func)))))
  2367.     ((symbolp x) (and (memq x '(nil t)) t))
  2368.     (t t)))
  2369.  
  2370. (defun cl-const-exprs-p (xs)
  2371.   (while (and xs (cl-const-expr-p (car xs)))
  2372.     (setq xs (cdr xs)))
  2373.   (not xs))
  2374.  
  2375. (defun cl-const-expr-val (x)
  2376.   (and (eq (cl-const-expr-p x) t) (if (consp x) (nth 1 x) x)))
  2377.  
  2378. (defun cl-expr-access-order (x v)
  2379.   (if (cl-const-expr-p x) v
  2380.     (if (consp x)
  2381.     (progn
  2382.       (while (setq x (cdr x)) (setq v (cl-expr-access-order (car x) v)))
  2383.       v)
  2384.       (if (eq x (car v)) (cdr v) '(t)))))
  2385.  
  2386. ;;; Count number of times X refers to Y.  Return NIL for 0 times.
  2387. (defun cl-expr-contains (x y)
  2388.   (cond ((equal y x) 1)
  2389.     ((and (consp x) (not (memq (car-safe x) '(quote function function*))))
  2390.      (let ((sum 0))
  2391.        (while x
  2392.          (setq sum (+ sum (or (cl-expr-contains (cl-pop x) y) 0))))
  2393.        (and (> sum 0) sum)))
  2394.     (t nil)))
  2395.  
  2396. (defun cl-expr-contains-any (x y)
  2397.   (while (and y (not (cl-expr-contains x (car y)))) (cl-pop y))
  2398.   y)
  2399.  
  2400. ;;; Check whether X may depend on any of the symbols in Y.
  2401. (defun cl-expr-depends-p (x y)
  2402.   (and (not (cl-const-expr-p x))
  2403.        (or (not (cl-safe-expr-p x)) (cl-expr-contains-any x y))))
  2404.  
  2405.  
  2406. ;;; Compiler macros.
  2407.  
  2408. (defmacro define-compiler-macro (func args &rest body)
  2409.   "(define-compiler-macro FUNC ARGLIST BODY...): Define a compiler-only macro.
  2410. This is like `defmacro', but macro expansion occurs only if the call to
  2411. FUNC is compiled (i.e., not interpreted).  Compiler macros should be used
  2412. for optimizing the way calls to FUNC are compiled; the form returned by
  2413. BODY should do the same thing as a call to the normal function called
  2414. FUNC, though possibly more efficiently.  Note that, like regular macros,
  2415. compiler macros are expanded repeatedly until no further expansions are
  2416. possible.  Unlike regular macros, BODY can decide to \"punt\" and leave the
  2417. original function call alone by declaring an initial `&whole foo' parameter
  2418. and then returning foo."
  2419.   (let ((p (if (listp args) args (list '&rest args))) (res nil))
  2420.     (while (consp p) (cl-push (cl-pop p) res))
  2421.     (setq args (nreverse res)) (setcdr res (and p (list '&rest p))))
  2422.   (list 'eval-when '(compile load eval)
  2423.     (cl-transform-function-property
  2424.      func 'cl-compiler-macro
  2425.      (cons (if (memq '&whole args) (delq '&whole args)
  2426.          (cons '--cl-whole-arg-- args)) body))
  2427.     (list 'or (list 'get (list 'quote func) '(quote byte-compile))
  2428.           (list 'put (list 'quote func) '(quote byte-compile)
  2429.             '(quote cl-byte-compile-compiler-macro)))))
  2430.  
  2431. (defun compiler-macroexpand (form)
  2432.   (while
  2433.       (let ((func (car-safe form)) (handler nil))
  2434.     (while (and (symbolp func)
  2435.             (not (setq handler (get func 'cl-compiler-macro)))
  2436.             (fboundp func)
  2437.             (or (not (eq (car-safe (symbol-function func)) 'autoload))
  2438.             (load (nth 1 (symbol-function func)))))
  2439.       (setq func (symbol-function func)))
  2440.     (and handler
  2441.          (not (eq form (setq form (apply handler form (cdr form))))))))
  2442.   form)
  2443.  
  2444. (defun cl-byte-compile-compiler-macro (form)
  2445.   (if (eq form (setq form (compiler-macroexpand form)))
  2446.       (byte-compile-normal-call form)
  2447.     (byte-compile-form form)))
  2448.  
  2449. (defmacro defsubst* (name args &rest body)
  2450.   "(defsubst* NAME ARGLIST [DOCSTRING] BODY...): define NAME as a function.
  2451. Like `defun', except the function is automatically declared `inline',
  2452. ARGLIST allows full Common Lisp conventions, and BODY is implicitly
  2453. surrounded by (block NAME ...)."
  2454.   (let* ((argns (cl-arglist-args args)) (p argns)
  2455.      (pbody (cons 'progn body))
  2456.      (unsafe (not (cl-safe-expr-p pbody))))
  2457.     (while (and p (eq (cl-expr-contains args (car p)) 1)) (cl-pop p))
  2458.     (list 'progn
  2459.       (if p nil   ; give up if defaults refer to earlier args
  2460.         (list 'define-compiler-macro name
  2461.           (list* '&whole 'cl-whole '&cl-quote args)
  2462.           (list* 'cl-defsubst-expand (list 'quote argns)
  2463.              (list 'quote (list* 'block name body))
  2464.              (not (or unsafe (cl-expr-access-order pbody argns)))
  2465.              (and (memq '&key args) 'cl-whole) unsafe argns)))
  2466.       (list* 'defun* name args body))))
  2467.  
  2468. (defun cl-defsubst-expand (argns body simple whole unsafe &rest argvs)
  2469.   (if (and whole (not (cl-safe-expr-p (cons 'progn argvs)))) whole
  2470.     (if (cl-simple-exprs-p argvs) (setq simple t))
  2471.     (let ((lets (delq nil
  2472.               (mapcar* (function
  2473.                 (lambda (argn argv)
  2474.                   (if (or simple (cl-const-expr-p argv))
  2475.                       (progn (setq body (subst argv argn body))
  2476.                          (and unsafe (list argn argv)))
  2477.                     (list argn argv))))
  2478.                    argns argvs))))
  2479.       (if lets (list 'let lets body) body))))
  2480.  
  2481.  
  2482. ;;; Compile-time optimizations for some functions defined in this package.
  2483. ;;; Note that cl.el arranges to force cl-macs to be loaded at compile-time,
  2484. ;;; mainly to make sure these macros will be present.
  2485.  
  2486. (put 'eql 'byte-compile nil)
  2487. (define-compiler-macro eql (&whole form a b)
  2488.   (cond ((eq (cl-const-expr-p a) t)
  2489.      (let ((val (cl-const-expr-val a)))
  2490.        (if (and (numberp val) (not (integerp val)))
  2491.            (list 'equal a b)
  2492.          (list 'eq a b))))
  2493.     ((eq (cl-const-expr-p b) t)
  2494.      (let ((val (cl-const-expr-val b)))
  2495.        (if (and (numberp val) (not (integerp val)))
  2496.            (list 'equal a b)
  2497.          (list 'eq a b))))
  2498.     ((cl-simple-expr-p a 5)
  2499.      (list 'if (list 'numberp a)
  2500.            (list 'equal a b)
  2501.            (list 'eq a b)))
  2502.     ((and (cl-safe-expr-p a)
  2503.           (cl-simple-expr-p b 5))
  2504.      (list 'if (list 'numberp b)
  2505.            (list 'equal a b)
  2506.            (list 'eq a b)))
  2507.     (t form)))
  2508.  
  2509. (define-compiler-macro member* (&whole form a list &rest keys)
  2510.   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
  2511.            (cl-const-expr-val (nth 1 keys)))))
  2512.     (cond ((eq test 'eq) (list 'memq a list))
  2513.       ((eq test 'equal) (list 'member a list))
  2514.       ((or (null keys) (eq test 'eql))
  2515.        (if (eq (cl-const-expr-p a) t)
  2516.            (list (if (floatp-safe (cl-const-expr-val a)) 'member 'memq)
  2517.              a list)
  2518.          (if (eq (cl-const-expr-p list) t)
  2519.          (let ((p (cl-const-expr-val list)) (mb nil) (mq nil))
  2520.            (if (not (cdr p))
  2521.                (and p (list 'eql a (list 'quote (car p))))
  2522.              (while p
  2523.                (if (floatp-safe (car p)) (setq mb t)
  2524.              (or (integerp (car p)) (symbolp (car p)) (setq mq t)))
  2525.                (setq p (cdr p)))
  2526.              (if (not mb) (list 'memq a list)
  2527.                (if (not mq) (list 'member a list) form))))
  2528.            form)))
  2529.       (t form))))
  2530.  
  2531. (define-compiler-macro assoc* (&whole form a list &rest keys)
  2532.   (let ((test (and (= (length keys) 2) (eq (car keys) ':test)
  2533.            (cl-const-expr-val (nth 1 keys)))))
  2534.     (cond ((eq test 'eq) (list 'assq a list))
  2535.       ((eq test 'equal) (list 'assoc a list))
  2536.       ((and (eq (cl-const-expr-p a) t) (or (null keys) (eq test 'eql)))
  2537.        (if (floatp-safe (cl-const-expr-val a))
  2538.            (list 'assoc a list) (list 'assq a list)))
  2539.       (t form))))
  2540.  
  2541. (define-compiler-macro adjoin (&whole form a list &rest keys)
  2542.   (if (and (cl-simple-expr-p a) (cl-simple-expr-p list)
  2543.        (not (memq ':key keys)))
  2544.       (list 'if (list* 'member* a list keys) list (list 'cons a list))
  2545.     form))
  2546.  
  2547. (define-compiler-macro list* (arg &rest others)
  2548.   (let* ((args (reverse (cons arg others)))
  2549.      (form (car args)))
  2550.     (while (setq args (cdr args))
  2551.       (setq form (list 'cons (car args) form)))
  2552.     form))
  2553.  
  2554. (define-compiler-macro get* (sym prop &optional def)
  2555.   (if def
  2556.       (list 'getf (list 'symbol-plist sym) prop def)
  2557.     (list 'get sym prop)))
  2558.  
  2559. (define-compiler-macro typep (&whole form val type)
  2560.   (if (cl-const-expr-p type)
  2561.       (let ((res (cl-make-type-test val (cl-const-expr-val type))))
  2562.     (if (or (memq (cl-expr-contains res val) '(nil 1))
  2563.         (cl-simple-expr-p val)) res
  2564.       (let ((temp (gensym)))
  2565.         (list 'let (list (list temp val)) (subst temp val res)))))
  2566.     form))
  2567.  
  2568.  
  2569. (mapcar (function
  2570.      (lambda (y)
  2571.        (put (car y) 'side-effect-free t)
  2572.        (put (car y) 'byte-compile 'cl-byte-compile-compiler-macro)
  2573.        (put (car y) 'cl-compiler-macro
  2574.         (list 'lambda '(w x)
  2575.               (if (symbolp (cadr y))
  2576.               (list 'list (list 'quote (cadr y))
  2577.                 (list 'list (list 'quote (caddr y)) 'x))
  2578.             (cons 'list (cdr y)))))))
  2579.     '((first 'car x) (second 'cadr x) (third 'caddr x) (fourth 'cadddr x)
  2580.       (fifth 'nth 4 x) (sixth 'nth 5 x) (seventh 'nth 6 x)
  2581.       (eighth 'nth 7 x) (ninth 'nth 8 x) (tenth 'nth 9 x)
  2582.       (rest 'cdr x) (endp 'null x) (plusp '> x 0) (minusp '< x 0)
  2583.       (caar car car) (cadr car cdr) (cdar cdr car) (cddr cdr cdr)
  2584.       (caaar car caar) (caadr car cadr) (cadar car cdar)
  2585.       (caddr car cddr) (cdaar cdr caar) (cdadr cdr cadr)
  2586.       (cddar cdr cdar) (cdddr cdr cddr) (caaaar car caaar)
  2587.       (caaadr car caadr) (caadar car cadar) (caaddr car caddr)
  2588.       (cadaar car cdaar) (cadadr car cdadr) (caddar car cddar)
  2589.       (cadddr car cdddr) (cdaaar cdr caaar) (cdaadr cdr caadr)
  2590.       (cdadar cdr cadar) (cdaddr cdr caddr) (cddaar cdr cdaar)
  2591.       (cddadr cdr cdadr) (cdddar cdr cddar) (cddddr cdr cdddr) ))
  2592.  
  2593. ;;; Things that are inline.
  2594. (proclaim '(inline floatp-safe acons map concatenate notany notevery
  2595.            cl-set-elt revappend nreconc gethash))
  2596.  
  2597. ;;; Things that are side-effect-free.
  2598. (mapcar (function (lambda (x) (put x 'side-effect-free t)))
  2599.     '(oddp evenp abs expt signum last butlast ldiff pairlis gcd lcm
  2600.       isqrt floor* ceiling* truncate* round* mod* rem* subseq
  2601.       list-length get* getf gethash hash-table-count))
  2602.  
  2603. ;;; Things that are side-effect-and-error-free.
  2604. (mapcar (function (lambda (x) (put x 'side-effect-free 'error-free)))
  2605.     '(eql floatp-safe list* subst acons equalp random-state-p
  2606.       copy-tree sublis hash-table-p))
  2607.  
  2608.  
  2609. (run-hooks 'cl-macs-load-hook)
  2610.  
  2611. ;;; cl-macs.el ends here
  2612.