Skip to content
Snippets Groups Projects
macros.lisp 58.7 KiB
Newer Older
(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 (if default (gensym))))
      (values `(,@temps ,ptemp ,@(if default `(,def-temp)))
	      `(,@values ,prop ,@(if default `(,default)))
ram's avatar
ram committed
	      `(,newval)
	      `(let ((,(car stores) (%putf ,get ,ptemp ,newval)))
		 ,set
		 ,newval)
	      `(getf ,get ,ptemp ,@(if default `(,def-temp)))))))
ram's avatar
ram committed

(define-setf-method get (symbol prop &optional default)
  (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 (though not as evil as
;;; it used to be.)  The function arg must be constant, and is converted to an
;;; APPLY of ther SETF function, which ought to exist.
(define-setf-method apply (function &rest args)
  (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))
	(new-var (gensym))
	(vars nil))
    (dolist (x args)
      (declare (ignore x))
      (push (gensym) vars))
    (values vars args (list new-var)
	    `(apply #'(setf ,function) ,new-var ,@vars)
	    `(apply #',function ,@vars))))
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)
  "The first argument is a byte specifier.  The second is any place form
  acceptable to SETF.  Replaces the specified byte of the number in this
  place with bits from the low-order end of the new value."
  (multiple-value-bind (dummies vals newval setter getter)
    (if (and (consp bytespec) (eq (car bytespec) 'byte))
	(let ((n-size (gensym))
	      (n-pos (gensym))
	      (n-new (gensym)))
	  (values (list* n-size n-pos dummies)
		  (list* (second bytespec) (third bytespec) vals)
		  (list n-new)
		  `(let ((,(car newval) (dpb ,n-new (byte ,n-size ,n-pos)
					     ,getter)))
		     ,setter
		     ,n-new)
		  `(ldb (byte ,n-size ,n-pos) ,getter)))
	(let ((btemp (gensym))
	      (gnuval (gensym)))
	  (values (cons btemp dummies)
		  (cons bytespec vals)
		  (list gnuval)
		  `(let ((,(car newval) (dpb ,gnuval ,btemp ,getter)))
		     ,setter
		     ,gnuval)
		  `(ldb ,btemp ,getter))))))
ram's avatar
ram committed


(define-setf-method mask-field (bytespec place &environment env)
  "The first argument is a byte specifier.  The second is any place form
  acceptable to SETF.  Replaces the specified byte of the number in this place
  with bits from the corresponding position in the new value."
  (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
    (let ((btemp (gensym))
	  (gnuval (gensym)))
      (values (cons btemp dummies)
	      (cons bytespec vals)
	      (list gnuval)
	      `(let ((,(car newval) (deposit-field ,gnuval ,btemp ,getter)))
		 ,setter
		 ,gnuval)
	      `(mask-field ,btemp ,getter)))))


(define-setf-method the (type place &environment env)
  (multiple-value-bind (dummies vals newval setter getter)
ram's avatar
ram committed
      (values dummies
	      vals
	      newval
	      (subst `(the ,type ,(car newval)) (car newval) setter)
	      `(the ,type ,getter))))


;;;; CASE, TYPECASE, & Friends.

(eval-when (compile load eval)

;;; CASE-BODY returns code for all the standard "case" macros.  Name is the
;;; macro name, and keyform is the thing to case on.  Multi-p indicates whether
;;; a branch may fire off a list of keys; otherwise, a key that is a list is
;;; interpreted in some way as a single key.  When multi-p, test is applied to
;;; the value of keyform and each key for a given branch; otherwise, test is
;;; applied to the value of keyform and the entire first element, instead of
;;; each part, of the case branch.  When errorp, no t or otherwise branch is
;;; permitted, and an ERROR form is generated.  When proceedp, it is an error
;;; to omit errorp, and the ERROR form generated is executed within a
;;; RESTART-CASE allowing keyform to be set and retested.
;;;
(defun case-body (name keyform cases multi-p test errorp proceedp)
  (let ((keyform-value (gensym))
	(clauses ())
	(keys ()))
    (dolist (case cases)
      (cond ((atom case)
	     (error "~S -- Bad clause in ~S." case name))
	    ((memq (car case) '(t otherwise))
	     (if errorp
		 (error "No default clause allowed in ~S: ~S" name case)
		 (push `(t nil ,@(rest case)) clauses)))
	    ((and multi-p (listp (first case)))
	     (setf keys (append (first case) keys))
	     (push `((or ,@(mapcar #'(lambda (key)
				       `(,test ,keyform-value ',key))
				   (first case)))
		     nil ,@(rest case))
		   clauses))
	    (t
	     (push (first case) keys)
	     (push `((,test ,keyform-value
			    ',(first case)) nil ,@(rest case)) clauses))))
    (case-body-aux name keyform keyform-value clauses keys errorp proceedp
		   `(,(if multi-p 'member 'or) ,@keys))))

;;; CASE-BODY-AUX provides the expansion once CASE-BODY has groveled all the
;;; cases.  Note: it is not necessary that the resulting code signal
;;; case-failure conditions, but that's what KMP's prototype code did.  We call
;;; CASE-BODY-ERROR, because of how closures are compiled.  RESTART-CASE has
;;; forms with closures that the compiler causes to be generated at the top of
;;; any function using the case macros, regardless of whether they are needed.
;;;
(defun case-body-aux (name keyform keyform-value clauses keys
		      errorp proceedp expected-type)
  (if proceedp
      (let ((block (gensym))
	    (again (gensym)))
	`(let ((,keyform-value ,keyform))
	   (block ,block
	     (tagbody
	      ,again
	      (return-from
	       ,block
	       (cond ,@(nreverse clauses)
		     (t
		      (setf ,keyform-value
			    (setf ,keyform
				  (case-body-error
				   ',name ',keyform ,keyform-value
				   ',expected-type ',keys)))
		      (go ,again))))))))
      `(let ((,keyform-value ,keyform))
	 ,keyform-value ; prevent warnings when key not used eg (case key (t))
ram's avatar
ram committed
	 (cond
	  ,@(nreverse clauses)
	  ,@(if errorp
		`((t (error 'conditions::case-failure
			    :name ',name
			    :datum ,keyform-value
			    :expected-type ',expected-type
			    :possibilities ',keys))))))))

); eval-when

(defun case-body-error (name keyform keyform-value expected-type keys)
  (restart-case
      (error 'conditions::case-failure
	     :name name
	     :datum keyform-value
	     :expected-type expected-type
	     :possibilities keys)
    (store-value (value)
      :report (lambda (stream)
		(format stream "Supply a new value for ~S." keyform))
      :interactive read-evaluated-form
      value)))


(defmacro case (keyform &body cases)
  "CASE Keyform {({(Key*) | Key} Form*)}*
  Evaluates the Forms in the first clause with a Key EQL to the value of
  Keyform.  If a singleton key is T then the clause is a default clause."
  (case-body 'case keyform cases t 'eql nil nil))

(defmacro ccase (keyform &body cases)
  "CCASE Keyform {({(Key*) | Key} Form*)}*
  Evaluates the Forms in the first clause with a Key EQL to the value of
  Keyform.  If none of the keys matches then a correctable error is
  signalled."
  (case-body 'ccase keyform cases t 'eql t t))

(defmacro ecase (keyform &body cases)
  "ECASE Keyform {({(Key*) | Key} Form*)}*
  Evaluates the Forms in the first clause with a Key EQL to the value of
  Keyform.  If none of the keys matches then an error is signalled."
  (case-body 'ecase keyform cases t 'eql t nil))

(defmacro typecase (keyform &body cases)
  "TYPECASE Keyform {(Type Form*)}*
  Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  is true."
  (case-body 'typecase keyform cases nil 'typep nil nil))

(defmacro ctypecase (keyform &body cases)
  "CTYPECASE Keyform {(Type Form*)}*
  Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  is true.  If no form is satisfied then a correctable error is signalled."
  (case-body 'ctypecase keyform cases nil 'typep t t))

(defmacro etypecase (keyform &body cases)
  "ETYPECASE Keyform {(Type Form*)}*
  Evaluates the Forms in the first clause for which TYPEP of Keyform and Type
  is true.  If no form is satisfied then an error is signalled."
  (case-body 'etypecase keyform cases nil 'typep t nil))


;;;; ASSERT and CHECK-TYPE.

;;; ASSERT is written this way, to call ASSERT-ERROR, because of how closures
;;; are compiled.  RESTART-CASE has forms with closures that the compiler
;;; causes to be generated at the top of any function using ASSERT, regardless
;;; of whether they are needed.
;;;
(defmacro assert (test-form &optional places datum &rest arguments)
  "Signals an error if the value of test-form is nil.  Continuing from this
   error using the CONTINUE restart will allow the user to alter the value of
   some locations known to SETF, starting over with test-form.  Returns nil."
  `(loop
     (when ,test-form (return nil))
     (assert-error ',test-form ',places ,datum ,@arguments)
     ,@(mapcar #'(lambda (place)
		   `(setf ,place (assert-prompt ',place ,place)))
	       places)))

ram's avatar
ram committed
(defun assert-error (assertion places datum &rest arguments)
  (let ((cond (if datum
		  (conditions::coerce-to-condition
		   datum arguments
		   'simple-error 'error)
		  (make-condition 'simple-error
				  :format-control "The assertion ~S failed."
				  :format-arguments (list assertion)))))
  (restart-case (error cond)
ram's avatar
ram committed
    (continue ()
      :report (lambda (stream) (assert-report places stream))
ram's avatar
ram committed


(defun assert-report (names stream)
  (format stream "Retry assertion")
  (if names
      (format stream " with new value~P for ~{~S~^, ~}."
	      (length names) names)
      (format stream ".")))

(defun assert-prompt (name value)
  (cond ((y-or-n-p "The old value of ~S is ~S.~
		  ~%Do you want to supply a new value? "
		   name value)
	 (format *query-io* "~&Type a form to be evaluated:~%")
	 (flet ((read-it () (eval (read *query-io*))))
	   (if (symbolp name) ;help user debug lexical variables
	       (progv (list name) (list value) (read-it))
	       (read-it))))
	(t value)))


;;; CHECK-TYPE is written this way, to call CHECK-TYPE-ERROR, because of how
;;; closures are compiled.  RESTART-CASE has forms with closures that the
;;; compiler causes to be generated at the top of any function using
;;; CHECK-TYPE, regardless of whether they are needed.  Because it would be
;;; nice if this were cheap to use, and some things can't afford this excessive
;;; consing (e.g., READ-CHAR), we bend backwards a little.
;;;

(defmacro check-type (place type &optional type-string)
  "Signals an error of type type-error if the contents of place are not of the
   specified type.  If an error is signaled, this can only return if
   STORE-VALUE is invoked.  It will store into place and start over."
  (let ((place-value (gensym)))
    `(loop
       (let ((,place-value ,place))
	 (when (typep ,place-value ',type) (return nil))
	 (setf ,place
	       (check-type-error ',place ,place-value ',type ,type-string))))))

(defun check-type-error (place place-value type type-string)
  (let ((cond (if type-string
		  (make-condition 'simple-type-error
				  :datum place :expected-type type
				  :format-control
				  "The value of ~S is ~S, which is not ~A."
				  :format-arguments
				  (list place place-value type-string))
		  (make-condition 'simple-type-error
				  :datum place :expected-type type
				  :format-control
			  "The value of ~S is ~S, which is not of type ~S."
				  :format-arguments
				  (list place place-value type)))))
    (restart-case (error cond)
      (store-value (value)
	:report (lambda (stream)
		  (format stream "Supply a new value of ~S."
			  place))
	:interactive read-evaluated-form
	value))))
ram's avatar
ram committed

;;; READ-EVALUATED-FORM is used as the interactive method for restart cases
;;; setup by the Common Lisp "casing" (e.g., CCASE and CTYPECASE) macros
;;; and by CHECK-TYPE.
;;;
(defun read-evaluated-form ()
  (format *query-io* "~&Type a form to be evaluated:~%")
  (list (eval (read *query-io*))))


;;;; With-XXX
(defmacro with-open-file ((var &rest open-args) &body (forms decls))
  "Bindspec is of the form (Stream File-Name . Options).  The file whose
   name is File-Name is opened using the Options and bound to the variable
pw's avatar
pw committed
   Stream. If the call to open is unsuccessful, the forms are not
   evaluated.  The Forms are executed, and when they 
   terminate, normally or otherwise, the file is closed."
ram's avatar
ram committed
  (let ((abortp (gensym)))
    `(let ((,var (open ,@open-args))
	   (,abortp t))
       ,@decls
pw's avatar
pw committed
       (unwind-protect
	   (multiple-value-prog1
	       (progn ,@forms)
	     (setq ,abortp nil))
	 (when ,var
ram's avatar
ram committed
	   (close ,var :abort ,abortp))))))


(defmacro with-open-stream ((var stream) &body (forms decls))
  "The form stream should evaluate to a stream.  VAR is bound
   to the stream and the forms are evaluated as an implicit
   progn.  The stream is closed upon exit."
  (let ((abortp (gensym)))
    `(let ((,var ,stream)
	   (,abortp t))
       ,@decls
       (unwind-protect
	 (multiple-value-prog1
	  (progn ,@forms)
	  (setq ,abortp nil))
	 (when ,var
	   (close ,var :abort ,abortp))))))


(defmacro with-input-from-string ((var string &key index start end) &body (forms decls))
  "Binds the Var to an input stream that returns characters from String and
  executes the body.  See manual for details."
  `(let ((,var
ram's avatar
ram committed
	  ,(cond ((null end)
		  `(make-string-input-stream ,string ,(or start 0)))
		 ((symbolp end)
		  `(if ,end
		       (make-string-input-stream ,string ,(or start 0) ,end)
		     (make-string-input-stream ,string ,(or start 0))))
		 (t
		  `(make-string-input-stream ,string ,(or start 0) ,end)))))
ram's avatar
ram committed
     ,@decls
     (unwind-protect
       (progn ,@forms)
       (close ,var)
       ,@(if index `((setf ,index (string-input-stream-current ,var)))))))


(defmacro with-output-to-string ((var &optional string) &body (forms decls))
  "If *string* is specified, it must be a string with a fill pointer; 
   the output is incrementally appended to the string (as if by use of
   VECTOR-PUSH-EXTEND)."
ram's avatar
ram committed
  (if string
      `(let ((,var (make-fill-pointer-output-stream ,string)))
	 ,@decls
	 (unwind-protect
	   (progn ,@forms)
	   (close ,var)))
      `(let ((,var (make-string-output-stream)))
	 ,@decls
	 (unwind-protect
	   (progn ,@forms)
	   (close ,var))
	 (get-output-stream-string ,var))))


;;;; Iteration macros:

(defmacro dotimes ((var count &optional (result nil)) &body body)
  (cond ((numberp count)
         `(do ((,var 0 (1+ ,var)))
              ((>= ,var ,count) ,result)
	    (declare (type unsigned-byte ,var))
ram's avatar
ram committed
            ,@body))
        (t (let ((v1 (gensym)))
             `(do ((,var 0 (1+ ,var)) (,v1 ,count))
                  ((>= ,var ,v1) ,result)
		(declare (type unsigned-byte ,var))
ram's avatar
ram committed
                ,@body)))))


;;; We repeatedly bind the var instead of setting it so that we never give the
;;; var a random value such as NIL (which might conflict with a declaration).
;;; If there is a result form, we introduce a gratitous binding of the variable
;;; to NIL w/o the declarations, then evaluate the result form in that
;;; environment.  We spuriously reference the gratuitous variable, since we
;;; don't want to use IGNORABLE on what might be a special var.
ram's avatar
ram committed
;;;
(defmacro dolist ((var list &optional (result nil)) &body body)
  (let ((n-list (gensym)))
    `(do ((,n-list ,list (cdr ,n-list)))
	 ((endp ,n-list)
	  ,@(if result
		`((let ((,var nil))
		    ,var
		    ,result))
		'(nil)))
ram's avatar
ram committed
       (let ((,var (car ,n-list)))
	 ,@body))))


(defmacro do (varlist endlist &body (body decls))
  "DO ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
  Iteration construct.  Each Var is initialized in parallel to the value of the
  specified Init form.  On subsequent iterations, the Vars are assigned the
  value of the Step form (if any) in paralell.  The Test is evaluated before
  each evaluation of the body Forms.  When the Test is true, the the Exit-Forms
  are evaluated as a PROGN, with the result being the value of the DO.  A block
  named NIL is established around the entire expansion, allowing RETURN to be
  used as an laternate exit mechanism."

  (do-do-body varlist endlist body decls 'let 'psetq 'do nil))


(defmacro do* (varlist endlist &body (body decls))
  "DO* ({(Var [Init] [Step])}*) (Test Exit-Form*) Declaration* Form*
  Iteration construct.  Each Var is initialized sequentially (like LET*) to the
  value of the specified Init form.  On subsequent iterations, the Vars are
  sequentially assigned the value of the Step form (if any).  The Test is
  evaluated before each evaluation of the body Forms.  When the Test is true,
  the the Exit-Forms are evaluated as a PROGN, with the result being the value
  of the DO.  A block named NIL is established around the entire expansion,
  allowing RETURN to be used as an laternate exit mechanism."
  (do-do-body varlist endlist body decls 'let* 'setq 'do* nil))


;;;; Miscellaneous macros:

(defmacro locally (&rest forms)
  "A form providing a container for locally-scoped variables."
  `(let () ,@forms))

(defmacro psetq (&rest pairs)
  (do ((lets nil)
       (setqs nil)
       (pairs pairs (cddr pairs)))
      ((atom (cdr pairs))
       `(let ,(nreverse lets) (setq ,@(nreverse setqs))))
    (let ((gen (gensym)))
      (push `(,gen ,(cadr pairs)) lets)
      (push (car pairs) setqs)
      (push gen setqs))))

pw's avatar
pw committed
;;; LAMBDA -- from the ANSI spec.
;;;
(defmacro lambda (&whole form &rest bvl-decls-and-body)
  (declare (ignore bvl-decls-and-body))
  `#',form) 


ram's avatar
ram committed

;;;; With-Compilation-Unit:

;;; True if we are within a With-Compilation-Unit form, which normally causes
;;; nested uses to be NOOPS.
;;;
(defvar *in-compilation-unit* nil)

;;; Count of the number of compilation units dynamically enclosed by the
;;; current active WITH-COMPILATION-UNIT that were unwound out of.
;;;
(defvar *aborted-compilation-units*)

(declaim (special c::*context-declarations*))


;;; EVALUATE-DECLARATION-CONTEXT  --  Internal
;;;
;;;    Recursively descend the context form, returning true if this subpart
;;; matches the specified context.
ram's avatar
ram committed
;;;
(defun evaluate-declaration-context (context name parent)
  (let* ((base (if (and (consp name) (consp (cdr name)))
		   (cadr name)
		   name))
	 (package (and (symbolp base) (symbol-package base))))
	(multiple-value-bind (ignore how)
			     (if package
				 (find-symbol (symbol-name base) package)
				 (values nil nil))
	  (declare (ignore ignore))
	  (case context
	    (:internal (eq how :internal))
	    (:external (eq how :external))
	    (:uninterned (and (symbolp base) (not package)))
	    (:anonymous (not name))
	    (:macro (eq parent 'defmacro))
	    (:function (member parent '(defun labels flet function)))
	    (:global (member parent '(defun defmacro function)))
	    (:local (member parent '(labels flet)))
	    (t
	     (error "Unknown declaration context: ~S." context))))
	(case (first context)
	  (:or
	   (loop for x in (rest context)
	     thereis (evaluate-declaration-context x name parent)))
	  (:and
	   (loop for x in (rest context)
	     always (evaluate-declaration-context x name parent)))
	  (:not
	   (evaluate-declaration-context (second context) name parent))
	  (:member
	   (member name (rest context) :test #'equal))
	  (:match
	   (let ((name (concatenate 'string "$" (string base) "$")))
	     (loop for x in (rest context)
	       thereis (search (string x) name))))
	  (:package
	   (and package
		(loop for x in (rest context)
		  thereis (eq (find-package (string x)) package))))
	  (t
	   (error "Unknown declaration context: ~S." context))))))

  
;;; PROCESS-CONTEXT-DECLARATIONS  --  Internal
;;;
;;;    Given a list of context declaration specs, return a new value for
;;; C::*CONTEXT-DECLARATIONS*.
;;;
(defun process-context-declarations (decls)
  (append
   (mapcar
    #'(lambda (decl)
	(unless (>= (length decl) 2)
	  (error "Context declaration spec should have context and at ~
	  least one DECLARE form:~%  ~S" decl))
	#'(lambda (name parent)
	    (when (evaluate-declaration-context (first decl) name parent)
	      (rest decl))))
    decls)
   c::*context-declarations*))


;;; With-Compilation-Unit  --  Public
ram's avatar
ram committed
;;;
(defmacro with-compilation-unit (options &body body)
  "WITH-COMPILATION-UNIT ({Key Value}*) Form*
  This form affects compilations that take place within its dynamic extent.  It
  is intended to be wrapped around the compilation of all files in the same
  system.  These keywords are defined:
    :OVERRIDE Boolean-Form
        One of the effects of this form is to delay undefined warnings 
        until the end of the form, instead of giving them at the end of each
        compilation.  If OVERRIDE is NIL (the default), then the outermost
        WITH-COMPILATION-UNIT form grabs the undefined warnings.  Specifying
        OVERRIDE true causes that form to grab any enclosed warnings, even if
        it is enclosed by another WITH-COMPILATION-UNIT.
    :OPTIMIZE Decl-Form
        Decl-Form should evaluate to an OPTIMIZE declaration specifier.  This
        declaration changes the `global' policy for compilations within the
        body.
    :OPTIMIZE-INTERFACE Decl-Form
        Like OPTIMIZE, except that it specifies the value of the CMU extension
        OPTIMIZE-INTERFACE policy (which controls argument type and syntax
        checking.)
    :CONTEXT-DECLARATIONS List-of-Context-Decls-Form
        This is a CMU extension which allows compilation to be controlled
        by pattern matching on the context in which a definition appears.  The
        argument should evaluate to a list of lists of the form:
            (Context-Spec Declare-Form+)
        In the indicated context, the specified declare forms are inserted at
        the head of each definition.  The declare forms for all contexts that
	match are appended together, with earlier declarations getting
	predecence over later ones.  A simple example:
            :context-declarations
            '((:external (declare (optimize (safety 2)))))
        This will cause all functions that are named by external symbols to be
        compiled with SAFETY 2.  The full syntax of context specs is:
	:INTERNAL, :EXTERNAL
	    True if the symbols is internal (external) in its home package.
	:UNINTERNED
	    True if the symbol has no home package.
	:ANONYMOUS
	    True if the function doesn't have any interesting name (not
	    DEFMACRO, DEFUN, LABELS or FLET).
	:MACRO, :FUNCTION
	    :MACRO is a global (DEFMACRO) macro.  :FUNCTION is anything else.
	:LOCAL, :GLOBAL
	    :LOCAL is a LABELS or FLET.  :GLOBAL is anything else.
	(:OR Context-Spec*)
	    True in any specified context.
	(:AND Context-Spec*)
	    True only when all specs are true.
	(:NOT Context-Spec)
	    True when the spec is false.
        (:MEMBER Name*)
	    True when the name is one of these names (EQUAL test.)
	(:MATCH Pattern*)
	    True when any of the patterns is a substring of the name.  The name
	    is wrapped with $'s, so $FOO matches names beginning with FOO,
	    etc."
  (let ((override nil)
	(optimize nil)
	(optimize-interface nil)
	(context-declarations nil)
ram's avatar
ram committed
	(n-fun (gensym))
	(n-abort-p (gensym)))
    (when (oddp (length options))
      (error "Odd number of key/value pairs: ~S." options))
    (do ((opt options (cddr opt)))
	((null opt))
      (case (first opt)
	(:override
	 (setq override (second opt)))
	(:optimize
	 (setq optimize (second opt)))
	(:optimize-interface
	 (setq optimize-interface (second opt)))
	(:context-declarations
	 (setq context-declarations (second opt)))
ram's avatar
ram committed
	(t
	 (warn "Ignoring unknown option: ~S." (first opt)))))

    `(flet ((,n-fun ()
	      (let (,@(when optimize
			`((c::*default-cookie*
			   (c::process-optimize-declaration
			    ,optimize c::*default-cookie*))))
		    ,@(when optimize-interface
			`((c::*default-interface-cookie*
			   (c::process-optimize-declaration
			    ,optimize-interface
			    c::*default-interface-cookie*))))
		    ,@(when context-declarations
			`((c::*context-declarations*
			   (process-context-declarations
			    ,context-declarations)))))
		,@body)))
       (if (or ,override (not *in-compilation-unit*))
ram's avatar
ram committed
	   (let ((c::*undefined-warnings* nil)
ram's avatar
ram committed
		 (c::*compiler-error-count* 0)
		 (c::*compiler-warning-count* 0)
		 (c::*compiler-note-count* 0)
		 (*in-compilation-unit* t)
		 (*aborted-compilation-units* 0)
		 (,n-abort-p t))
ram's avatar
ram committed
	     (handler-bind ((c::parse-unknown-type
			     #'(lambda (c)
				 (c::note-undefined-reference
				  (c::parse-unknown-type-specifier c)
				  :type))))
	       (unwind-protect
		   (multiple-value-prog1
		       (,n-fun)
		     (setq ,n-abort-p nil))
		 (c::print-summary ,n-abort-p *aborted-compilation-units*))))
ram's avatar
ram committed
	   (let ((,n-abort-p t))
	     (unwind-protect
		 (multiple-value-prog1
		     (,n-fun)
		   (setq ,n-abort-p nil))
	       (when ,n-abort-p
		 (incf *aborted-compilation-units*))))))))