Skip to content
Snippets Groups Projects
macros.lisp 56.4 KiB
Newer Older
ram's avatar
ram committed
;;; -*- Log: code.log; Package: Lisp -*-
;;;
;;; **********************************************************************
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;; If you want to use this code or any part of CMU Common Lisp, please contact
;;; Scott Fahlman or slisp-group@cs.cmu.edu.
;;;
(ext:file-comment
  "$Header: /Volumes/share2/src/cmucl/cvs2git/cvsroot/src/code/macros.lisp,v 1.27 1992/02/21 21:59:58 wlott Exp $")
ram's avatar
ram committed
;;; **********************************************************************
;;;
;;; This file contains the macros that are part of the standard
;;; Spice Lisp environment.
;;;
;;; Written by Scott Fahlman and Rob MacLachlan.
;;; Modified by Bill Chiles to adhere to the wall.
ram's avatar
ram committed
;;;
(in-package "LISP")
(export '(defvar defparameter defconstant when unless setf
ram's avatar
ram committed
	  defsetf define-setf-method psetf shiftf rotatef push pushnew pop
	  incf decf remf case typecase with-open-file
	  with-open-stream with-input-from-string with-output-to-string
	  locally etypecase ctypecase ecase ccase
	  get-setf-method get-setf-method-multiple-value
ram's avatar
ram committed
          define-modify-macro destructuring-bind nth-value
ram's avatar
ram committed
          otherwise)) ; Sacred to CASE and related macros.

(in-package "EXTENSIONS")
(export '(do-anonymous collect iterate))

(in-package "LISP")


;;; Parse-Body  --  Public
;;;
;;;    Parse out declarations and doc strings, *not* expanding macros.
;;; Eventually the environment arg should be flushed, since macros can't expand
;;; into declarations anymore.
;;;
(defun parse-body (body environment &optional (doc-string-allowed t))
  "This function is to parse the declarations and doc-string out of the body of
  a defun-like form.  Body is the list of stuff which is to be parsed.
  Environment is ignored.  If Doc-String-Allowed is true, then a doc string
  will be parsed out of the body and returned.  If it is false then a string
  will terminate the search for declarations.  Three values are returned: the
  tail of Body after the declarations and doc strings, a list of declare forms,
  and the doc-string, or NIL if none."
  (declare (ignore environment))
  (let ((decls ())
	(doc nil))
    (do ((tail body (cdr tail)))
	((endp tail)
	 (values tail (nreverse decls) doc))
      (let ((form (car tail)))
	(cond ((and (stringp form) (cdr tail))
	       (if doc-string-allowed
		   (setq doc form)
		   (return (values tail (nreverse decls) doc))))
	      ((not (and (consp form) (symbolp (car form))))
	       (return (values tail (nreverse decls) doc)))
	      ((eq (car form) 'declare)
	       (push form decls))
	      (t
	       (return (values tail (nreverse decls) doc))))))))


;;;; DEFMACRO:

;;; Defmacro  --  Public
;;;
;;;    Parse the definition and make an expander function.  The actual
;;; definition is done by %defmacro which we expand into.
;;;
(defmacro defmacro (name lambda-list &body body)
  (let ((whole (gensym "WHOLE-"))
	(environment (gensym "ENV-")))
ram's avatar
ram committed
    (multiple-value-bind
	(body local-decs doc)
	(parse-defmacro lambda-list whole body name 'defmacro
			:environment environment)
ram's avatar
ram committed
      (let ((def `(lambda (,whole ,environment)
		    ,@local-decs
		    (block ,name
		      ,body))))
	`(c::%defmacro ',name #',def ',lambda-list ,doc)))))
ram's avatar
ram committed


;;; %Defmacro, %%Defmacro  --  Internal
;;;
;;;    Defmacro expands into %Defmacro which is a function that is treated
;;; magically the compiler.  After the compiler has gotten the information it
;;; wants out of macro definition, it compiles a call to %%Defmacro which
;;; happens at load time.  We have a %Defmacro function which just calls
;;; %%Defmacro in order to keep the interpreter happy.
;;;
;;;    Eventually %%Defmacro should deal with clearing old compiler information
;;; for the functional value.
;;;
(defun c::%defmacro (name definition lambda-list doc)
  (assert (eval:interpreted-function-p definition))
  (setf (eval:interpreted-function-name definition)
	(format nil "DEFMACRO ~S" name))
  (setf (eval:interpreted-function-arglist definition) lambda-list)
ram's avatar
ram committed
  (c::%%defmacro name definition doc))
;;;
(defun c::%%defmacro (name definition doc)
  (clear-info function where-from name)
  (setf (macro-function name) definition)
ram's avatar
ram committed
  (setf (documentation name 'function) doc)
  name)


;;; DEFTYPE is a lot like DEFMACRO.

(defmacro deftype (name arglist &body body)
  "Syntax like DEFMACRO, but defines a new type."
  (unless (symbolp name)
    (error "~S -- Type name not a symbol." name))
  
  (let ((whole (gensym "WHOLE-")))
ram's avatar
ram committed
    (multiple-value-bind (body local-decs doc)
			 (parse-defmacro arglist whole body name 'deftype
					 :default-default ''*)
      `(eval-when (compile load eval)
	 (%deftype ',name
		   #'(lambda (,whole)
		       ,@local-decs
		       (block ,name ,body))
		   ,@(when doc `(,doc)))))))
;;;
(defun %deftype (name expander &optional doc)
  (ecase (info type kind name)
    (:primitive
     (error "Illegal to redefine standard type: ~S." name))
    (:structure
     (warn "Redefining structure type ~S with DEFTYPE." name)
     (c::undefine-structure (info type structure-info name)))
    ((nil :defined)))
  (setf (info type kind name) :defined)
  (setf (info type expander name) expander)
  (when doc
    (setf (documentation name 'type) doc))
  ;; ### Bootstrap hack -- we need to define types before %note-type-defined
  ;; is defined.
  (when (fboundp 'c::%note-type-defined)
    (c::%note-type-defined name))
ram's avatar
ram committed

;;; And so is DEFINE-SETF-METHOD.

(defparameter defsetf-error-string "Setf expander for ~S cannot be called with ~S args.")

(defmacro define-setf-method (access-fn lambda-list &body body)
  "Syntax like DEFMACRO, but creates a Setf-Method generator.  The body
  must be a form that returns the five magical values."
  (unless (symbolp access-fn)
    (error "~S -- Access-function name not a symbol in DEFINE-SETF-METHOD."
	   access-fn))

  (let ((whole (gensym "WHOLE-"))
	(environment (gensym "ENV-")))
ram's avatar
ram committed
    (multiple-value-bind (body local-decs doc)
			 (parse-defmacro lambda-list whole body access-fn
					 'define-setf-method
					 :environment environment)
ram's avatar
ram committed
      `(eval-when (load compile eval)
	 (%define-setf-macro
	  ',access-fn
	  #'(lambda (,whole ,environment)
	      ,@local-decs
	      (block ,access-fn ,body))
	  nil
	  ',doc)))))


;;; %DEFINE-SETF-MACRO  --  Internal
;;;
;;;    Do stuff for defining a setf macro.
;;;
(defun %define-setf-macro (name expander inverse doc)
  (cond ((not (fboundp `(setf ,name))))
	((info function accessor-for name)
	 (warn "Defining setf macro for destruct slot accessor; redefining as ~
	        a normal function:~%  ~S"
	       name)
	 (c::define-function-name name))
	((not (eq (symbol-package name) (symbol-package 'aref)))
	 (warn "Defining setf macro for ~S, but ~S is fbound."
	       name `(setf ,name))))
  (when (or inverse (info setf inverse name))
    (setf (info setf inverse name) inverse))
  (when (or expander (info setf expander name))
    (setf (info setf expander name) expander))
  (when doc
    (setf (documentation name 'setf) doc))
  name)
  

;;;; Destructuring-bind

(defmacro destructuring-bind (lambda-list arg-list &rest body)
  "Bind the variables in LAMBDA-LIST to the contents of ARG-LIST."
  (let* ((arg-list-name (gensym "ARG-LIST-")))
    (multiple-value-bind
	(body local-decls)
	(parse-defmacro lambda-list arg-list-name body nil 'destructuring-bind
			:annonymousp t :doc-string-allowed nil)
      `(let ((,arg-list-name ,arg-list))
	 ,@local-decls
ram's avatar
ram committed


;;;; Defun, Defvar, Defparameter, Defconstant:

;;; Defun  --  Public
;;;
;;;    Very similar to Defmacro, but simpler.  We don't have to parse the
;;; lambda-list.
;;;
(defmacro defun (&whole source name lambda-list &body (body decls doc))
ram's avatar
ram committed
  (let ((def `(lambda ,lambda-list
		,@decls
		(block ,(if (and (consp name) (eq (car name) 'setf))
			    (cadr name)
			    name)
		  ,@body))))
    `(c::%defun ',name #',def ,doc ',source)))


;;; %Defun, %%Defun  --  Internal
;;;
;;;    Similar to %Defmacro, ...
;;;
(defun c::%%defun (name def doc &optional inline-expansion)
  (setf (fdefinition name) def)
  (when doc
    (if (and (consp name) (eq (first name) 'setf))
	(setf (documentation (second name) 'setf) doc)
	(setf (documentation name 'function) doc)))
  (c::define-function-name name)
  (when (eq (info function where-from name) :assumed)
    (setf (info function where-from name) :defined)
    (when (info function assumed-type name)
      (setf (info function assumed-type name) nil)))
ram's avatar
ram committed
  (when (or inline-expansion
	    (info function inline-expansion name))
    (setf (info function inline-expansion name) inline-expansion))
  name)
;;;
(defun c::%defun (name def doc source)
  (declare (ignore source))
  (assert (eval:interpreted-function-p def))
  (setf (eval:interpreted-function-name def) name)
ram's avatar
ram committed
  (c::%%defun name def doc))


;;; DEFCONSTANT  --  Public
;;;
(defmacro defconstant (var val &optional doc)
  "For defining global constants at top level.  The DEFCONSTANT says that the
  value is constant and may be compiled into code.  If the variable already has
  a value, and this is not equal to the init, an error is signalled.  The third
  argument is an optional documentation string for the variable."
  `(c::%defconstant ',var ,val ',doc))

;;; %Defconstant, %%Defconstant  --  Internal
;;;
;;;    Like the other %mumbles except that we currently actually do something
;;; interesting at load time, namely checking if the constant is being
;;; redefined.
;;;
(defun c::%defconstant (name value doc)
  (c::%%defconstant name value doc))
;;;
(defun c::%%defconstant (name value doc)
  (when doc
    (setf (documentation name 'variable) doc))
  (when (boundp name)
    (unless (equalp (symbol-value name) value)
      (cerror "Go ahead and change the value."
	      "Constant ~S being redefined." name)))
  (setf (symbol-value name) value)
  (setf (info variable kind name) :constant)
  (clear-info variable constant-value name)
  name)


(defmacro defvar (var &optional (val nil valp) (doc nil docp))
  "For defining global variables at top level.  Declares the variable
  SPECIAL and, optionally, initializes it.  If the variable already has a
  value, the old value is not clobbered.  The third argument is an optional
  documentation string for the variable."
  `(progn
    (proclaim '(special ,var))
     ,@(when valp
	 `((unless (boundp ',var)
	     (setq ,var ,val))))
    ,@(when docp
	`((setf (documentation ',var 'variable) ',doc)))
    ',var))

(defmacro defparameter (var val &optional (doc nil docp))
  "Defines a parameter that is not normally changed by the program,
  but that may be changed without causing an error.  Declares the
  variable special and sets its value to VAL.  The third argument is
  an optional documentation string for the parameter."
  `(progn
    (proclaim '(special ,var))
    (setq ,var ,val)
    ,@(when docp
	`((setf (documentation ',var 'variable) ',doc)))
    ',var))


;;;; ASSORTED CONTROL STRUCTURES


(defmacro when (test &body forms)
  "First arg is a predicate.  If it is non-null, the rest of the forms are
  evaluated as a PROGN."
  `(cond (,test nil ,@forms)))

(defmacro unless (test &rest forms)
  "First arg is a predicate.  If it is null, the rest of the forms are
  evaluated as a PROGN."
  `(cond ((not ,test) nil ,@forms)))


(defmacro return (&optional (value nil))
  `(return-from nil ,value))

(defmacro prog (varlist &body (body decls))
  `(block nil
     (let ,varlist
       ,@decls
       (tagbody ,@body))))

(defmacro prog* (varlist &body (body decls))
  `(block nil
     (let* ,varlist
       ,@decls
       (tagbody ,@body))))


;;; Prog1, Prog2  --  Public
;;;
;;;    These just turn into a Let.
;;;
(defmacro prog1 (result &rest body)
  (let ((n-result (gensym)))
    `(let ((,n-result ,result))
       ,@body
       ,n-result)))
;;;
(defmacro prog2 (form1 result &rest body)
  `(prog1 (progn ,form1 ,result) ,@body))


;;; And, Or  --  Public
;;;
;;;    AND and OR are defined in terms of IF.
;;;
(defmacro and (&rest forms)
  (cond ((endp forms) t)
	((endp (rest forms)) (first forms))
	(t
	 `(if ,(first forms)
	      (and ,@(rest forms))
	      nil))))
;;;
(defmacro or (&rest forms)
  (cond ((endp forms) nil)
	((endp (rest forms)) (first forms))
	(t
	 (let ((n-result (gensym)))
	   `(let ((,n-result ,(first forms)))
	      (if ,n-result
		  ,n-result
		  (or ,@(rest forms))))))))


;;; Cond  --  Public
;;;
;;;    COND also turns into IF.
;;;
(defmacro cond (&rest clauses)
  (if (endp clauses)
      nil
      (let ((clause (first clauses)))
	(when (atom clause)
	  (error "Cond clause is not a list: ~S." clause))
	(let ((test (first clause))
	      (forms (rest clause)))
	  (if (endp forms)
	      (let ((n-result (gensym)))
		`(let ((,n-result ,test))
		   (if ,n-result
		       ,n-result
		       (cond ,@(rest clauses)))))
	      `(if ,test
		   (progn ,@forms)
		   (cond ,@(rest clauses))))))))


;;;; Multiple value macros:

;;; Multiple-Value-XXX  --  Public
;;;
;;;    All the multiple-value receiving forms are defined in terms of
;;; Multiple-Value-Call.
;;;
(defmacro multiple-value-setq (varlist value-form)
  (unless (and (listp varlist) (every #'symbolp varlist))
    (error "Varlist is not a list of symbols: ~S." varlist))
  (let ((temps (mapcar #'(lambda (x) (declare (ignore x)) (gensym)) varlist)))
    `(multiple-value-bind ,temps ,value-form
       ,@(mapcar #'(lambda (var temp)
		     `(setq ,var ,temp))
		 varlist temps)
       ,(car temps))))
;;;
(defmacro multiple-value-bind (varlist value-form &body body)
  (unless (and (listp varlist) (every #'symbolp varlist))
    (error "Varlist is not a list of symbols: ~S." varlist))
  (if (= (length varlist) 1)
      `(let ((,(car varlist) ,value-form))
	 ,@body)
      (let ((ignore (gensym)))
	`(multiple-value-call #'(lambda (&optional ,@varlist &rest ,ignore)
				  (declare (ignore ,ignore))
				  ,@body)
	   ,value-form))))
;;;
(defmacro multiple-value-list (value-form)
  `(multiple-value-call #'list ,value-form))

ram's avatar
ram committed

(defmacro nth-value (n form)
  "Evaluates FORM and returns the Nth value (zero based).  This involves no
  consing when N is a trivial constant integer."
  (if (integerp n)
      (let ((dummy-list nil)
            (wendy (gensym)))
        ;; We build DUMMY-LIST, a list of variables to bind to useless
        ;; values, then we explicitly IGNORE those bindings and return
        ;; WENDY, the only thing we're really interested in right now.
        (dotimes (i n)
          (push (gensym) dummy-list))
        `(multiple-value-bind (,@dummy-list ,wendy)
                              ,form
           (declare (ignore ,@dummy-list))
           ,wendy))
      `(once-only (,n)
         (case (the fixnum ,n)
           (0 (nth-value 0 ,form))
           (1 (nth-value 1 ,form))
           (2 (nth-value 2 ,form))
           (T (nth (the fixnum ,n) (multiple-value-list ,form)))))))
ram's avatar
ram committed

ram's avatar
ram committed

;;;; SETF and friends.

;;; Note: The expansions for SETF and friends sometimes create needless
;;; LET-bindings of argument values.  The compiler will remove most of
;;; these spurious bindings, so SETF doesn't worry too much about creating
;;; them. 

;;; The inverse for a generalized-variable reference function is stored in
;;; one of two ways:
;;;
;;; A SETF-INVERSE property corresponds to the short form of DEFSETF.  It is
;;; the name of a function takes the same args as the reference form, plus a
;;; new-value arg at the end.
;;;
;;; A SETF-METHOD-EXPANDER property is created by the long form of DEFSETF or
;;; by DEFINE-SETF-METHOD.  It is a function that is called on the reference
;;; form and that produces five values: a list of temporary variables, a list
;;; of value forms, a list of the single store-value form, a storing function,
;;; and an accessing function.

(eval-when (compile load eval)
ram's avatar
ram committed
;;;
(defun get-setf-method (form &optional environment)
ram's avatar
ram committed
  "Returns five values needed by the SETF machinery: a list of temporary
  variables, a list of values with which to fill them, the temporary for the
  new value in a list, the setting function, and the accessing function."
  (let (temp)
    (cond ((symbolp form)
	   (let ((new-var (gensym)))
	     (values nil nil (list new-var) `(setq ,form ,new-var) form)))
	  ;;
	  ;; Local functions inhibit global setf methods...
	  ((and environment
		(c::leaf-p (cdr (assoc (car form)
				       (c::lexenv-functions environment)))))
	   (get-setf-method-inverse form `(funcall #'(setf ,(car form))) t))
ram's avatar
ram committed
	  ((setq temp (info setf inverse (car form)))
	   (get-setf-method-inverse form `(,temp) nil))
ram's avatar
ram committed
	  ((setq temp (info setf expander (car form)))
	   (funcall temp form environment))
	  ;;
	  ;; If a macro, expand one level and try again.  If not, go for the
	  ;; SETF function.
ram's avatar
ram committed
	  (t
	   (multiple-value-bind (res win)
				(macroexpand-1 form environment)
	     (if win
		 (get-setf-method res environment)
		 (get-setf-method-inverse form
					  `(funcall #'(setf ,(car form)))
					  t)))))))
ram's avatar
ram committed

(defun get-setf-method-inverse (form inverse setf-function)
ram's avatar
ram committed
  (let ((new-var (gensym))
	(vars nil)
	(vals nil))
    (dolist (x (cdr form))
      (push (gensym) vars)
      (push x vals))
    (setq vals (nreverse vals))
    (values vars vals (list new-var)
	    (if setf-function
		`(,@inverse ,new-var ,@vars)
		`(,@inverse ,@vars ,new-var))
ram's avatar
ram committed
	    `(,(car form) ,@vars))))


(defun get-setf-method-multiple-value (form &optional environment)
  "Like Get-Setf-Method, but may return multiple new-value variables."
  (get-setf-method form environment))

(defun defsetter (fn rest)
  (let ((arglist (car rest))
	(arglist-var (gensym "ARGS-"))
	(new-var (car (cadr rest))))
    (multiple-value-bind
	(body local-decs doc)
	(parse-defmacro arglist arglist-var (cddr rest) fn 'defsetf)
ram's avatar
ram committed
      (values 
       `(lambda (,arglist-var ,new-var)
	  ,@local-decs
wlott's avatar
wlott committed
       doc))))
ram's avatar
ram committed

) ; End of Eval-When.


(defmacro defsetf (access-fn &rest rest)
ram's avatar
ram committed
  "Associates a SETF update function or macro with the specified access
  function or macro.  The format is complex.  See the manual for
  details."
  (cond ((not (listp (car rest)))
	 `(eval-when (load compile eval)
	    (%define-setf-macro ',access-fn nil ',(car rest)
				,(when (and (car rest) (stringp (cadr rest)))
				   `',(cadr rest)))))
ram's avatar
ram committed
	((and (listp (car rest)) (cdr rest) (listp (cadr rest)))
	 (if (not (= (length (cadr rest)) 1))
	     (cerror "Ignore the extra items in the list."
		     "Only one new-value variable allowed in DEFSETF."))
	 (multiple-value-bind (setting-form-generator doc)
			      (defsetter access-fn rest)
ram's avatar
ram committed
	   `(eval-when (load compile eval)
	      (%define-setf-macro
	       ',access-fn
	       #'(lambda (access-form environment)
		   (declare (ignore environment))
		   (do* ((args (cdr access-form) (cdr args))
			 (dummies nil (cons (gensym) dummies))
			 (newval-var (gensym))
			 (new-access-form nil))
			((atom args)
			 (setq new-access-form 
			       (cons (car access-form) dummies))
			 (values
			  dummies
			  (cdr access-form)
			  (list newval-var)
			  (funcall (function ,setting-form-generator)
				   new-access-form newval-var)
			  new-access-form))))
	       nil
	       ',doc))))
ram's avatar
ram committed
	(t (error "Ill-formed DEFSETF for ~S." access-fn))))

;;; SETF  --  Public
;;;
;;;    Except for atoms, we always call GET-SETF-METHOD, since it has some
;;; non-trivial semantics.  But when there is a setf inverse, and G-S-M uses
;;; it, then we return a call to the inverse, rather than returning a hairy let
;;; form.  This is probably important mainly as a convenince in allowing the
;;; use of setf inverses without the full interpreter.
;;;
ram's avatar
ram committed
(defmacro setf (&rest args &environment env)
  "Takes pairs of arguments like SETQ.  The first is a place and the second
  is the value that is supposed to go into that place.  Returns the last
  value.  The place argument may be any of the access forms for which SETF
  knows a corresponding setting form."
  (let ((nargs (length args)))
    (cond
     ((= nargs 2)
      (let ((place (first args))
	    (value-form (second args)))
	(if (atom place)
	    `(setq ,place ,value-form)
	    (multiple-value-bind (dummies vals newval setter getter)
				 (get-setf-method place env)
	      (declare (ignore getter))
	      (let ((inverse (info setf inverse (car place))))
		(if (and inverse (eq inverse (car setter)))
		    `(,inverse ,@(cdr place) ,value-form)
		    `(let* (,@(mapcar #'list dummies vals)
			    (,(first newval) ,value-form))
		       ,setter)))))))
     ((oddp nargs) 
      (error "Odd number of args to SETF."))
     (t
      (do ((a args (cddr a)) (l nil))
	  ((null a) `(progn ,@(nreverse l)))
	(setq l (cons (list 'setf (car a) (cadr a)) l)))))))
ram's avatar
ram committed


(defmacro psetf (&rest args &environment env)
  "This is to SETF as PSETQ is to SETQ.  Args are alternating place
  expressions and values to go into those places.  All of the subforms and
  values are determined, left to right, and only then are the locations
  updated.  Returns NIL."
  (do ((a args (cddr a))
       (let-list nil)
       (setf-list nil))
      ((atom a)
       `(let* ,(nreverse let-list) ,@(nreverse setf-list) nil))
    (if (atom (cdr a))
	(error "Odd number of args to PSETF."))
    (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
      (declare (ignore getter))
      (do* ((d dummies (cdr d))
	    (v vals (cdr v)))
	   ((null d))
	(push (list (car d) (car v)) let-list))
      (push (list (car newval) (cadr a)) let-list)
      (push setter setf-list))))



(defmacro shiftf (&rest args &environment env)
  "One or more SETF-style place expressions, followed by a single
  value expression.  Evaluates all of the expressions in turn, then
  assigns the value of each expression to the place on its left,
  returning the value of the leftmost."
  (if (< (length args) 2)
      (error "Too few argument forms to a SHIFTF."))
  (let ((leftmost (gensym)))
    (do ((a args (cdr a))
	 (let-list nil)
	 (setf-list nil)
	 (next-var leftmost))
	((atom (cdr a))
	 (push (list next-var (car a)) let-list)
	 `(let* ,(nreverse let-list) ,@(nreverse setf-list) ,leftmost))
      (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
	(do* ((d dummies (cdr d))
	      (v vals (cdr v)))
	     ((null d))
	  (push (list (car d) (car v)) let-list))
	(push (list next-var getter) let-list)
	(push setter setf-list)
	(setq next-var (car newval))))))


(defmacro rotatef (&rest args &environment env)
  "Takes any number of SETF-style place expressions.  Evaluates all of the
  expressions in turn, then assigns to each place the value of the form to
  its right.  The rightmost form gets the value of the leftmost.  Returns NIL."
  (cond ((null args) nil)
	((null (cdr args)) `(progn ,(car args) nil))
	(t (do ((a args (cdr a))
		(let-list nil)
		(setf-list nil)
		(next-var nil)
		(fix-me nil))
	       ((atom a)
		  (rplaca fix-me next-var)
		  `(let* ,(nreverse let-list) ,@(nreverse setf-list) nil))
	       (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
		 (do ((d dummies (cdr d))
		      (v vals (cdr v)))
		     ((null d))
		   (push (list (car d) (car v)) let-list))
		 (push (list next-var getter) let-list)
		 ;; We don't know the newval variable for the last form yet,
		 ;; so fake it for the first getter and fix it at the end.
		 (unless fix-me (setq fix-me (car let-list)))
		 (push setter setf-list)
		 (setq next-var (car newval)))))))


(defmacro define-modify-macro (name lambda-list function &optional doc-string)
  "Creates a new read-modify-write macro like PUSH or INCF."
  (let ((other-args nil)
	(rest-arg nil)
	(env (gensym))
	(reference (gensym)))
	     
    ;; Parse out the variable names and rest arg from the lambda list.
    (do ((ll lambda-list (cdr ll))
	 (arg nil))
	((null ll))
      (setq arg (car ll))
      (cond ((eq arg '&optional))
	    ((eq arg '&rest)
	     (if (symbolp (cadr ll))
		 (setq rest-arg (cadr ll))
		 (error "Non-symbol &rest arg in definition of ~S." name))
	     (if (null (cddr ll))
		 (return nil)
		 (error "Illegal stuff after &rest arg in Define-Modify-Macro.")))
	    ((memq arg '(&key &allow-other-keys &aux))
	     (error "~S not allowed in Define-Modify-Macro lambda list." arg))
	    ((symbolp arg)
	     (push arg other-args))
	    ((and (listp arg) (symbolp (car arg)))
	     (push (car arg) other-args))
	    (t (error "Illegal stuff in lambda list of Define-Modify-Macro."))))
    (setq other-args (nreverse other-args))
    `(defmacro ,name (,reference ,@lambda-list &environment ,env)
       ,doc-string
       (multiple-value-bind (dummies vals newval setter getter)
	 (get-setf-method ,reference ,env)
ram's avatar
ram committed
	 (do ((d dummies (cdr d))
	      (v vals (cdr v))
	      (let-list nil (cons (list (car d) (car v)) let-list)))
	     ((null d)
	      (push 
	       (list (car newval)
		     ,(if rest-arg
			  `(list* ',function getter ,@other-args ,rest-arg)
			  `(list ',function getter ,@other-args)))
	       let-list)
	      `(let* ,(nreverse let-list)
		 ,setter)))))))



(defmacro push (obj place &environment env)
  "Takes an object and a location holding a list.  Conses the object onto
  the list, returning the modified list."
  (if (symbolp place)
      `(setq ,place (cons ,obj ,place))
      (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
	(do* ((d dummies (cdr d))
	      (v vals (cdr v))
	      (let-list nil))
	     ((null d)
	      (push (list (car newval) `(cons ,obj ,getter))
		    let-list)
	      `(let* ,(nreverse let-list)
		 ,setter))
	  (push (list (car d) (car v)) let-list)))))


(defmacro pushnew (obj place &rest keys &environment env)
  "Takes an object and a location holding a list.  If the object is already
  in the list, does nothing.  Else, conses the object onto the list.  Returns
  NIL.  If there is a :TEST keyword, this is used for the comparison."
  (if (symbolp place)
      `(setq ,place (adjoin ,obj ,place ,@keys))
      (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
	(do* ((d dummies (cdr d))
	      (v vals (cdr v))
	      (let-list nil))
	     ((null d)
	      (push (list (car newval) `(adjoin ,obj ,getter ,@keys))
		    let-list)
	      `(let* ,(nreverse let-list)
		 ,setter))
	  (push (list (car d) (car v)) let-list)))))


(defmacro pop (place &environment env)
  "The argument is a location holding a list.  Pops one item off the front
  of the list and returns it."
  (if (symbolp place)
      `(prog1 (car ,place) (setq ,place (cdr ,place)))
      (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
	(do* ((d dummies (cdr d))
	      (v vals (cdr v))
	      (let-list nil))
	     ((null d)
	      (push (list (car newval) getter) let-list)
	      `(let* ,(nreverse let-list)
		 (prog1 (car ,(car newval))
			(setq ,(car newval) (cdr ,(car newval)))
			,setter)))
	  (push (list (car d) (car v)) let-list)))))


(define-modify-macro incf (&optional (delta 1)) +
  "The first argument is some location holding a number.  This number is
  incremented by the second argument, DELTA, which defaults to 1.")


(define-modify-macro decf (&optional (delta 1)) -
  "The first argument is some location holding a number.  This number is
  decremented by the second argument, DELTA, which defaults to 1.")


(defmacro remf (place indicator &environment env)
  "Place may be any place expression acceptable to SETF, and is expected
  to hold a property list or ().  This list is destructively altered to
  remove the property specified by the indicator.  Returns T if such a
  property was present, NIL if not."
  (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
    (do* ((d dummies (cdr d))
	  (v vals (cdr v))
	  (let-list nil)
	  (ind-temp (gensym))
	  (local1 (gensym))
	  (local2 (gensym)))
	 ((null d)
	  (push (list (car newval) getter) let-list)
	  (push (list ind-temp indicator) let-list)
	  `(let* ,(nreverse let-list)
	     (do ((,local1 ,(car newval) (cddr ,local1))
		  (,local2 nil ,local1))
		 ((atom ,local1) nil)
	       (cond ((atom (cdr ,local1))
		      (error "Odd-length property list in REMF."))
		     ((eq (car ,local1) ,ind-temp)
		      (cond (,local2
			     (rplacd (cdr ,local2) (cddr ,local1))
			     (return t))
			    (t (setq ,(car newval) (cddr ,(car newval)))
			       ,setter
			       (return t))))))))
      (push (list (car d) (car v)) let-list))))


;;; The built-in DEFSETFs.

(defsetf car %rplaca)
(defsetf cdr %rplacd)
(defsetf caar (x) (v) `(%rplaca (car ,x) ,v))
(defsetf cadr (x) (v) `(%rplaca (cdr ,x) ,v))
(defsetf cdar (x) (v) `(%rplacd (car ,x) ,v))
(defsetf cddr (x) (v) `(%rplacd (cdr ,x) ,v))
(defsetf caaar (x) (v) `(%rplaca (caar ,x) ,v))
(defsetf cadar (x) (v) `(%rplaca (cdar ,x) ,v))
(defsetf cdaar (x) (v) `(%rplacd (caar ,x) ,v))
(defsetf cddar (x) (v) `(%rplacd (cdar ,x) ,v))
(defsetf caadr (x) (v) `(%rplaca (cadr ,x) ,v))
(defsetf caddr (x) (v) `(%rplaca (cddr ,x) ,v))
(defsetf cdadr (x) (v) `(%rplacd (cadr ,x) ,v))
(defsetf cdddr (x) (v) `(%rplacd (cddr ,x) ,v))
(defsetf caaaar (x) (v) `(%rplaca (caaar ,x) ,v))
(defsetf cadaar (x) (v) `(%rplaca (cdaar ,x) ,v))
(defsetf cdaaar (x) (v) `(%rplacd (caaar ,x) ,v))
(defsetf cddaar (x) (v) `(%rplacd (cdaar ,x) ,v))
(defsetf caadar (x) (v) `(%rplaca (cadar ,x) ,v))
(defsetf caddar (x) (v) `(%rplaca (cddar ,x) ,v))
(defsetf cdadar (x) (v) `(%rplacd (cadar ,x) ,v))
(defsetf cdddar (x) (v) `(%rplacd (cddar ,x) ,v))
(defsetf caaadr (x) (v) `(%rplaca (caadr ,x) ,v))
(defsetf cadadr (x) (v) `(%rplaca (cdadr ,x) ,v))
(defsetf cdaadr (x) (v) `(%rplacd (caadr ,x) ,v))
(defsetf cddadr (x) (v) `(%rplacd (cdadr ,x) ,v))
(defsetf caaddr (x) (v) `(%rplaca (caddr ,x) ,v))
(defsetf cadddr (x) (v) `(%rplaca (cdddr ,x) ,v))
(defsetf cdaddr (x) (v) `(%rplacd (caddr ,x) ,v))
(defsetf cddddr (x) (v) `(%rplacd (cdddr ,x) ,v))

(defsetf first %rplaca)
(defsetf second (x) (v) `(%rplaca (cdr ,x) ,v))
(defsetf third (x) (v) `(%rplaca (cddr ,x) ,v))
(defsetf fourth (x) (v) `(%rplaca (cdddr ,x) ,v))
(defsetf fifth (x) (v) `(%rplaca (cddddr ,x) ,v))
(defsetf sixth (x) (v) `(%rplaca (cdr (cddddr ,x)) ,v))
(defsetf seventh (x) (v) `(%rplaca (cddr (cddddr ,x)) ,v))
(defsetf eighth (x) (v) `(%rplaca (cdddr (cddddr ,x)) ,v))
(defsetf ninth (x) (v) `(%rplaca (cddddr (cddddr ,x)) ,v))
(defsetf tenth (x) (v) `(%rplaca (cdr (cddddr (cddddr ,x))) ,v))
(defsetf rest %rplacd)

(defsetf elt %setelt)
(defsetf aref %aset)
(defsetf row-major-aref %set-row-major-aref)
ram's avatar
ram committed
(defsetf svref %svset)
(defsetf char %charset)
(defsetf bit %bitset)
(defsetf schar %scharset)
(defsetf sbit %sbitset)
(defsetf %array-dimension %set-array-dimension)
(defsetf %raw-bits %set-raw-bits)
ram's avatar
ram committed
(defsetf symbol-value set)
(defsetf symbol-function %sp-set-definition)
(defsetf symbol-plist %sp-set-plist)
(defsetf documentation %set-documentation)
(defsetf nth %setnth)
(defsetf fill-pointer %set-fill-pointer)
(defsetf search-list %set-search-list)

(defsetf sap-ref-8 %set-sap-ref-8)
(defsetf signed-sap-ref-8 %set-signed-sap-ref-8)
(defsetf sap-ref-16 %set-sap-ref-16)
(defsetf signed-sap-ref-16 %set-signed-sap-ref-16)
(defsetf sap-ref-32 %set-sap-ref-32)
(defsetf signed-sap-ref-32 %set-signed-sap-ref-32)
(defsetf sap-ref-sap %set-sap-ref-sap)
(defsetf sap-ref-single %set-sap-ref-single)
(defsetf sap-ref-double %set-sap-ref-double)
ram's avatar
ram committed

(define-setf-method getf (place prop &optional default &environment env)
  (multiple-value-bind (temps values stores set get)
ram's avatar
ram committed
    (let ((newval (gensym))
	  (ptemp (gensym))
	  (def-temp (gensym)))
      (values `(,@temps ,(car stores) ,ptemp ,@(if default `(,def-temp)))
	      `(,@values ,get ,prop ,@(if default `(,default)))
	      `(,newval)
	      `(progn (setq ,(car stores)
ram's avatar
ram committed
			    (%putf ,(car stores) ,ptemp ,newval))
ram's avatar
ram committed
		      ,set
		      ,newval)
	      `(getf ,(car stores) ,ptemp ,@(if default `(,def-temp)))))))

(define-setf-method get (symbol prop &optional default)
  "Get turns into %put. Don't put in the default unless it really is supplied and 
  non-nil, so that we can transform into the get instruction whenever possible."
  (let ((symbol-temp (gensym))
	(prop-temp (gensym))
	(def-temp (gensym))
	(newval (gensym)))
    (values `(,symbol-temp ,prop-temp ,@(if default `(,def-temp)))
	    `(,symbol ,prop ,@(if default `(,default)))
	    (list newval)
	    `(%put ,symbol-temp ,prop-temp ,newval)
	    `(get ,symbol-temp ,prop-temp ,@(if default `(,def-temp))))))

(define-setf-method gethash (key hashtable &optional default)
  (let ((key-temp (gensym))
	(hashtable-temp (gensym))
	(default-temp (gensym))
	(new-value-temp (gensym)))
    (values
     `(,key-temp ,hashtable-temp ,@(if default `(,default-temp)))
     `(,key ,hashtable ,@(if default `(,default)))
     `(,new-value-temp)
     `(%puthash ,key-temp ,hashtable-temp ,new-value-temp)
     `(gethash ,key-temp ,hashtable-temp ,@(if default `(,default-temp))))))

(defsetf subseq (sequence start &optional (end nil)) (v)
  `(progn (replace ,sequence ,v :start1 ,start :end1 ,end)
	  ,v))


;;; Evil hack invented by the gnomes of Vassar Street.  The function arg must
;;; be constant.  Get a setf method for this function, pretending that the
;;; final (list) arg to apply is just a normal arg.  If the setting and access
;;; forms produced in this way reference this arg at the end, then just splice
;;; the APPLY back onto the front and the right thing happens.
;;;
;;; We special-case uses functions in the Lisp package so that APPLY AREF works
;;; even though %ASET takes the new-value last.  (there is (SETF AREF) as well
;;; as a setf method, etc.)
;;;
ram's avatar
ram committed
(define-setf-method apply (function &rest args &environment env)
  (unless (and (listp function)
	       (= (list-length function) 2)
	       (eq (first function) 'function)
	       (symbolp (second function)))
    (error "Setf of Apply is only defined for function args like #'symbol."))
  (let ((function (second function)))
    (multiple-value-bind
	(dummies vals newval setter getter)
	(if (eq (symbol-package function) (symbol-package 'aref))
	    (get-setf-method-inverse (cons function args) `((setf ,function)) t)
	    (get-setf-method (cons function args) env))
      (unless (and (eq (car (last args)) (car (last vals)))
		   (eq (car (last getter)) (car (last dummies)))
		   (eq (car (last setter)) (car (last dummies))))
	(error "Apply of ~S not understood as a location for Setf." function))
      (values dummies vals newval
	      `(apply (function ,(car setter)) ,@(cdr setter))
	      `(apply (function ,(car getter)) ,@(cdr getter))))))
ram's avatar
ram committed


;;; Special-case a BYTE bytespec so that the compiler can recognize it.
;;;
ram's avatar
ram committed
(define-setf-method ldb (bytespec place &environment env)