Skip to content
Snippets Groups Projects
macros.lisp 51.8 KiB
Newer Older
ram's avatar
ram committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
      (setq function (second function))
      (error
       "Setf of Apply is only defined for function args of form #'symbol."))
  (multiple-value-bind (dummies vals newval setter getter)
		       (foo-get-setf-method (cons function args) env)
    ;; Special case aref and svref.
    (cond ((or (eq function 'aref) (eq function 'svref))
	   (let ((nargs (subseq setter 0 (1- (length setter))))
		 (fcn (if (eq function 'aref) 'lisp::%apply-aset 'lisp::%apply-svset)))
	     (values dummies vals newval
		     `(apply (function ,fcn) ,(car newval) ,@(cdr nargs))
		     `(apply (function ,function) ,@(cdr getter)))))
	  ;; Make sure the place is one that we can handle.
	  (T (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)))))))


(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)
		       (foo-get-setf-method place env)
    (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)))))


(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)
		       (foo-get-setf-method place env)
    (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 char-bit (place bit-name &environment env)
  "The first argument is any place form acceptable to SETF.  Replaces the
  specified bit of the character in this place with the new value."
  (multiple-value-bind (dummies vals newval setter getter)
		       (foo-get-setf-method place env)
    (let ((btemp (gensym))
	  (gnuval (gensym)))
      (values `(,@dummies ,btemp)
	      `(,@vals ,bit-name)
	      (list gnuval)
	      `(let ((,(car newval)
		      (set-char-bit ,getter ,btemp ,gnuval)))
		 ,setter
		 ,gnuval)
	      `(char-bit ,getter ,btemp)))))


(define-setf-method the (type place &environment env)
  (multiple-value-bind (dummies vals newval setter getter)
		       (foo-get-setf-method place env)
      (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))
	 (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)))

(defun assert-error (test-form places datum &rest arguments)
  (restart-case (if datum
		    (apply #'error datum arguments)
		    (simple-assertion-failure test-form))
    (continue ()
      :report (lambda (stream) (assert-report places stream))
      nil)))

(defun simple-assertion-failure (assertion)
  (error 'simple-type-error
	 :datum assertion
	 :expected-type nil ;this needs some work in next revision. -kmp
	 :format-string "The assertion ~S failed."
	 :format-arguments (list assertion)))

(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)
  (restart-case (if type-string
		    (error 'simple-type-error
			   :datum place :expected-type type
			   :format-string
			   "The value of ~S is ~S, which is not ~A."
			   :format-arguments
			   (list place place-value type-string))
		    (error 'simple-type-error
			   :datum place :expected-type type
			   :format-string
			   "The value of ~S is ~S, which is not of type ~S."
			   :format-arguments
			   (list place place-value type)))
    (store-value (value)
      :report (lambda (stream)
		(format stream "Supply a new value of ~S."
			place))
      :interactive read-evaluated-form
      value)))

;;; 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
   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
       (when ,var
	 (unwind-protect
	     (multiple-value-prog1
		 (progn ,@forms)
	       (setq ,abortp nil))
ram's avatar
ram committed
	   (close ,var :abort ,abortp))))))


ram's avatar
ram committed
(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
	  ,(if end
	       `(make-string-input-stream ,string ,(or start 0) ,end)
	       `(make-string-input-stream ,string ,(or start 0)))))
     ,@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 loop (&rest body)
  "Executes the body repeatedly until the form is exited by a Throw or
  Return.  The body is surrounded by an implicit block with name NIL."
  (let ((tag (gensym)))
    `(block nil (tagbody ,tag ,@body (go ,tag)))))


(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).
;;; ### Might not be legal...
;;;
(defmacro dolist ((var list &optional (result nil)) &body body)
  (let ((n-list (gensym)))
    `(do ((,n-list ,list (cdr ,n-list)))
	 ((endp ,n-list)
	  (let ((,var nil))
	    (declare (ignorable ,var))
	    ,result))
       (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))))

;;; ### Bootstrap hack...
;;; Restore defmacro processing to normal.
;;;
(eval-when (compile)
  (setq *bootstrap-defmacro* nil))


;;;; 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*)

(compiler-let ((*bootstrap-defmacro* :both))

;;; With-Compilation-Unit  --  Public
;;;
;;;
(defmacro with-compilation-unit (options &body body)
  (let ((force nil)
	(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)
	(:force
	 (setq force (second opt)))
	(t
	 (warn "Ignoring unknown option: ~S." (first opt)))))

    `(flet ((,n-fun () ,@body))
       (if (or ,force (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*))))))))
); Compiler-Let