ansi-aux.lsp 40.9 KB
Newer Older
1 2 3 4 5 6 7 8 9
;-*- Mode:     Lisp -*-
;;;; Author:   Paul Dietz
;;;; Created:  Sat Mar 28 17:10:18 1998
;;;; Contains: Aux. functions for CL-TEST

(in-package :cl-test)

(declaim (optimize (safety 3)))

10 11 12 13
;;; A function for coercing truth values to BOOLEAN

(defun notnot (x) (not (not x)))

14
(defmacro notnot-mv (form)
15
  `(notnot-mv-fn (multiple-value-list ,form)))
16

17 18 19 20
(defun notnot-mv-fn (results)
  (if (null results)
      (values)
    (apply #'values
sds's avatar
sds committed
21 22
           (not (not (first results)))
           (rest results))))
23 24 25 26 27 28 29 30

(defmacro not-mv (form)
  `(not-mv-fn (multiple-value-list ,form)))

(defun not-mv-fn (results)
  (if (null results)
      (values)
    (apply #'values
sds's avatar
sds committed
31 32
           (not (first results))
           (rest results))))
33

34 35 36 37 38 39
(declaim (ftype (function (t) function) to-function))

(defun to-function (fn)
  (etypecase fn
    (function fn)
    (symbol (symbol-function fn))
pfdietz's avatar
pfdietz committed
40
    ((cons (eql setf) (cons symbol null)) (fdefinition fn))))
41 42 43 44

;;; Macro to check that a function is returning a specified number of values
;;; (defaults to 1)
(defmacro check-values (form &optional (num 1))
45
  (let ((v (gensym))
sds's avatar
sds committed
46
        (n (gensym)))
47
   `(let ((,v (multiple-value-list ,form))
sds's avatar
sds committed
48
          (,n ,num))
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
      (check-values-length ,v ,n ',form)
      (car ,v))))

(defun check-values-length (results expected-number form)
  (declare (type fixnum expected-number))
  (let ((n expected-number))
    (declare (type fixnum n))
    (dolist (e results)
      (declare (ignore e))
      (decf n))
    (unless (= n 0)
      (error "Expected ~A results from ~A, got ~A results instead.~%~
Results: ~A~%" expected-number form n results))))

;;; Do multiple-value-bind, but check # of arguments
(defmacro multiple-value-bind* ((&rest vars) form &body body)
  (let ((len (length vars))
sds's avatar
sds committed
66
        (v (gensym)))
67 68 69
    `(let ((,v (multiple-value-list ,form)))
       (check-values-length ,v ,len ',form)
       (destructuring-bind ,vars ,v ,@body))))
sds's avatar
sds committed
70

71 72 73
;;; Comparison functions that are like various builtins,
;;; but are guaranteed to return T for true.

74
(defun eqt (x y)
75
  "Like EQ, but guaranteed to return T for true."
76
  (apply #'values (mapcar #'notnot (multiple-value-list (eq x y)))))
77

78 79
(defun eqlt (x y)
  "Like EQL, but guaranteed to return T for true."
80
  (apply #'values (mapcar #'notnot (multiple-value-list (eql x y)))))
81 82 83

(defun equalt (x y)
  "Like EQUAL, but guaranteed to return T for true."
84
  (apply #'values (mapcar #'notnot (multiple-value-list (equal x y)))))
85 86 87

(defun equalpt (x y)
  "Like EQUALP, but guaranteed to return T for true."
88
  (apply #'values (mapcar #'notnot (multiple-value-list (equalp x y)))))
89

90 91 92 93
(defun equalpt-or-report (x y)
  "Like EQUALPT, but return either T or a list of the arguments."
  (or (equalpt x y) (list x y)))

pfdietz's avatar
pfdietz committed
94 95 96
(defun string=t (x y)
  (notnot-mv (string= x y)))

97 98
(defun =t (x &rest args)
  "Like =, but guaranteed to return T for true."
99
  (apply #'values (mapcar #'notnot (multiple-value-list (apply #'=  x args)))))
100

pfdietz's avatar
pfdietz committed
101 102 103 104
(defun <=t (x &rest args)
  "Like <=, but guaranteed to return T for true."
  (apply #'values (mapcar #'notnot (multiple-value-list (apply #'<=  x args)))))

105
(defun make-int-list (n)
106
  (loop for i from 0 below n collect i))
107

108
(defun make-int-array (n &optional (fn #'make-array))
109 110 111 112 113
  (when (symbolp fn)
    (assert (fboundp fn))
    (setf fn (symbol-function (the symbol fn))))
  (let ((a (funcall (the function fn) n)))
    (declare (type (array * *) a))
114
    (loop for i from 0 below n do (setf (aref a i) i))
115 116
    a))

117 118 119
;;; Return true if A1 and A2 are arrays with the same rank
;;; and dimensions whose elements are EQUAL

120 121 122 123
(defun equal-array (a1 a2)
  (and (typep a1 'array)
       (typep a2 'array)
       (= (array-rank a1) (array-rank a2))
124
       (if (= (array-rank a1) 0)
sds's avatar
sds committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
           (equal (regression-test::my-aref a1) (regression-test::my-aref a2))
         (let ((ad (array-dimensions a1)))
           (and (equal ad (array-dimensions a2))
                (locally
                 (declare (type (array * *) a1 a2))
                 (if (= (array-rank a1) 1)
                     (let ((as (first ad)))
                       (loop
                        for i from 0 below as
                        always (equal (regression-test::my-aref a1 i)
                                      (regression-test::my-aref a2 i))))
                   (let ((as (array-total-size a1)))
                     (and (= as (array-total-size a2))
                          (loop
                           for i from 0 below as
                           always
                           (equal
                            (regression-test::my-row-major-aref a1 i)
                            (regression-test::my-row-major-aref a2 i))
                           ))))))))))
145

146 147
;;; *universe* is defined elsewhere -- it is a list of various
;;; lisp objects used when stimulating things in various tests.
148 149
(declaim (special *universe*))

pfdietz's avatar
pfdietz committed
150 151 152 153 154 155 156 157 158 159 160 161
;;; The function EMPIRICAL-SUBTYPEP checks two types
;;; for subtypeness, first using SUBTYPEP*, then (if that
;;; fails) empirically against all the elements of *universe*,
;;; checking if all that are in the first are also in the second.
;;; Return T if this is the case, NIL otherwise.  This will
;;; always return T if type1 is truly a subtype of type2,
;;; but may return T even if this is not the case.

(defun empirical-subtypep (type1 type2)
  (multiple-value-bind (sub good)
      (subtypep* type1 type2)
    (if good
sds's avatar
sds committed
162
        sub
pfdietz's avatar
pfdietz committed
163
      (loop for e in *universe*
sds's avatar
sds committed
164
            always (or (not (typep e type1)) (typep e type2))))))
pfdietz's avatar
pfdietz committed
165

166 167 168 169
(defun check-type-predicate (P TYPE)
  "Check that a predicate P is the same as #'(lambda (x) (typep x TYPE))
   by applying both to all elements of *UNIVERSE*.  Print message
   when a mismatch is found, and return number of mistakes."
170 171 172 173 174

  (when (symbolp p)
    (assert (fboundp p))
    (setf p (symbol-function p)))
  (assert (typep p 'function))
175

176
  (loop
177 178
      for x in *universe*
      when
sds's avatar
sds committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        (block failed
          (let ((p1 (handler-case
                        (normally (funcall (the function p) x))
                      (error () (format t "(FUNCALL ~S ~S) failed~%"
                                        P x)
                        (return-from failed t))))
                (p2 (handler-case
                        (normally (typep x TYPE))
                      (error () (format t "(TYPEP ~S '~S) failed~%"
                                        x TYPE)
                        (return-from failed t)))))
              (when (or (and p1 (not p2))
                        (and (not p1) p2))
                (format t "(FUNCALL ~S ~S) = ~S, (TYPEP ~S '~S) = ~S~%"
                        P x p1 x TYPE p2)
                t)))
        collect x))
196 197 198 199 200 201 202 203

;;; We have a common idiom where a guarded predicate should be
;;; true everywhere

(defun check-predicate (predicate &optional guard (universe *universe*))
  "Return all elements of UNIVERSE for which the guard (if present) is false
   and for which PREDICATE is false."
  (remove-if #'(lambda (e) (or (and guard (funcall guard e))
sds's avatar
sds committed
204 205
                               (funcall predicate e)))
             universe))
206 207 208 209 210 211 212 213 214 215

(declaim (special *catch-error-type*))

(defun catch-continue-debugger-hook (condition dbh)
  "Function that when used as *debugger-hook*, causes
   continuable errors to be continued without user intervention."
  (declare (ignore dbh))
  (let ((r (find-restart 'continue condition)))
    (cond
     ((and *catch-error-type*
sds's avatar
sds committed
216
           (not (typep condition *catch-error-type*)))
217 218
      (format t "Condition ~S is not a ~A~%" condition *catch-error-type*)
      (cond (r (format t "Its continue restart is ~S~%" r))
sds's avatar
sds committed
219
            (t (format t "It has no continue restart~%")))
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
      (throw 'continue-failed nil))
     (r (invoke-restart r))
     (t (throw 'continue-failed nil)))))

#|
(defun safe (fn &rest args)
  "Apply fn to args, trapping errors.  Convert type-errors to the
   symbol type-error."
  (declare (optimize (safety 3)))
  (handler-case
   (apply fn args)
   (type-error () 'type-error)
   (error (c) c)))
|#

pfdietz's avatar
pfdietz committed
235
;;; Use the next macro in place of SAFE
236 237 238 239 240 241

(defmacro catch-type-error (form)
"Evaluate form in safe mode, returning its value if there is no error.
If an error does occur, return type-error on TYPE-ERRORs, or the error
condition itself on other errors."
`(locally (declare (optimize (safety 3)))
242
  (handler-case (normally ,form)
243 244 245
     (type-error () 'type-error)
     (error (c) c))))

246
(defmacro classify-error* (form)
pfdietz's avatar
pfdietz committed
247 248 249 250
"Evaluate form in safe mode, returning its value if there is no error.
If an error does occur, return a symbol classify the error, or allow
the condition to go uncaught if it cannot be classified."
`(locally (declare (optimize (safety 3)))
251
  (handler-case (normally ,form)
252
     (undefined-function () 'undefined-function)
pfdietz's avatar
pfdietz committed
253
     (program-error () 'program-error)
254
     (package-error () 'package-error)
255 256
     (type-error    () 'type-error)
     (control-error () 'control-error)
257
     (parse-error   () 'parse-error)
pfdietz's avatar
pfdietz committed
258 259 260 261
     (stream-error  () 'stream-error)
     (reader-error  () 'reader-error)
     (file-error    () 'file-error)
     (cell-error    () 'cell-error)
262
     (division-by-zero () 'division-by-zero)
pfdietz's avatar
pfdietz committed
263 264
     (floating-point-overflow () 'floating-point-overflow)
     (floating-point-underflow () 'floating-point-underflow)
pfdietz's avatar
pfdietz committed
265
     (arithmetic-error () 'arithmetic-error)
266
     (error         () 'error)
267
  )))
pfdietz's avatar
pfdietz committed
268

269
(defun classify-error** (form)
270
  (handler-bind ((warning #'(lambda (c) (declare (ignore c))
sds's avatar
sds committed
271 272 273 274 275 276 277 278 279
                              (muffle-warning))))
                (proclaim '(optimize (safety 3)))
                (classify-error*
                 (if regression-test::*compile-tests*
                     (funcall (compile nil `(lambda ()
                                              (declare (optimize (safety 3)))
                                              ,form)))
                     (eval form))
                 )))
280

281
(defmacro classify-error (form)
282
  `(classify-error** ',form))
283

284 285 286
;;; The above is badly designed, since it fails when some signals
;;; may be in more than one class/

287
(defmacro signals-error (form error-name &key (safety 3) (name nil name-p) (inline nil))
288 289
  `(handler-bind
    ((warning #'(lambda (c) (declare (ignore c))
sds's avatar
sds committed
290
                              (muffle-warning))))
291 292
    (proclaim '(optimize (safety 3)))
    (handler-case
293
     (apply #'values
sds's avatar
sds committed
294 295 296 297 298 299 300 301 302
            nil
            (multiple-value-list
             ,(cond
               (inline form)
               (regression-test::*compile-tests*
                `(funcall (compile nil '(lambda ()
                                          (declare (optimize (safety ,safety)))
                                          ,form))))
               (t `(eval ',form)))))
303
     (,error-name (c)
sds's avatar
sds committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
                  (cond
                   ,@(case error-name
                       (type-error
                        `(((typep (type-error-datum c)
                                  (type-error-expected-type c))
                           (values
                            nil
                            (list (list 'typep (list 'quote
                                                     (type-error-datum c))
                                        (list 'quote
                                              (type-error-expected-type c)))
                                  "==> true")))))
                       ((undefined-function unbound-variable)
                        (and name-p
                             `(((not (eq (cell-error-name c) ',name))
                                (values
                                 nil
                                 (list 'cell-error-name "==>"
                                       (cell-error-name c)))))))
                       ((stream-error end-of-file reader-error)
                        `(((not (streamp (stream-error-stream c)))
                           (values
                            nil
                            (list 'stream-error-stream "==>"
                                  (stream-error-stream c))))))
                       (file-error
                        `(((not (pathnamep (pathname (file-error-pathname c))))
                           (values
                            nil
                            (list 'file-error-pathname "==>"
                                  (file-error-pathname c))))))
                       (t nil))
                   (t (printable-p c)))))))
337

338 339 340 341 342
(defmacro signals-error-always (form error-name)
  `(values
    (signals-error ,form ,error-name)
    (signals-error ,form ,error-name :safety 0)))

343
(defmacro signals-type-error (var datum-form form &key (safety 3) (inline nil))
344
  (let ((lambda-form
sds's avatar
sds committed
345 346 347
         `(lambda (,var)
            (declare (optimize (safety ,safety)))
            ,form)))
348
    `(let ((,var ,datum-form))
349
       (declare (optimize safety))
350
       (handler-bind
sds's avatar
sds committed
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        ((warning #'(lambda (c) (declare (ignore c))
                      (muffle-warning))))
                                        ; (proclaim '(optimize (safety 3)))
        (handler-case
         (apply #'values
                nil
                (multiple-value-list
                 (funcall
                 ,(cond
                   (inline `(function ,lambda-form))
                   (regression-test::*compile-tests*
                     `(compile nil ',lambda-form))
                   (t `(eval ',lambda-form)))
                  ,var)))
         (type-error
          (c)
          (let ((datum (type-error-datum c))
                (expected-type (type-error-expected-type c)))
            (cond
             ((not (eql ,var datum))
              (list :datum-mismatch ,var datum))
             ((typep datum expected-type)
              (list :is-typep datum expected-type))
             (t (printable-p c))))))))))
375

376 377 378 379 380 381 382
(declaim (special *mini-universe*))

(defun check-type-error* (pred-fn guard-fn &optional (universe *mini-universe*))
  "Check that for all elements in some set, either guard-fn is true or
   pred-fn signals a type error."
  (let (val)
    (loop for e in universe
sds's avatar
sds committed
383 384 385 386 387 388
          unless (or (funcall guard-fn e)
                     (equal
                      (setf val (multiple-value-list
                                 (signals-type-error x e (funcall pred-fn x) :inline t)))
                      '(t)))
        collect (list e val))))
389 390 391 392

(defmacro check-type-error (&body args)
  `(locally (declare (optimize safety)) (check-type-error* ,@args)))

393 394 395 396
(defun printable-p (obj)
  "Returns T iff obj can be printed to a string."
  (with-standard-io-syntax
   (let ((*print-readably* nil)
sds's avatar
sds committed
397
         (*print-escape* nil))
398 399
     (declare (optimize safety))
     (handler-case (and (stringp (write-to-string obj)) t)
sds's avatar
sds committed
400
                   (condition (c) (declare (ignore c)) nil)))))
401

pfdietz's avatar
pfdietz committed
402
;;;
403 404
;;; The function SUBTYPEP should return two generalized booleans.
;;; This auxiliary function returns booleans instead
pfdietz's avatar
pfdietz committed
405 406
;;; (which makes it easier to write tests).
;;;
407
(defun subtypep* (type1 type2)
408
  (apply #'values
sds's avatar
sds committed
409 410
         (mapcar #'notnot
                 (multiple-value-list (subtypep type1 type2)))))
411 412 413 414

(defun subtypep*-or-fail (type1 type2)
  (let ((results (multiple-value-list (subtypep type1 type2))))
    (and (= (length results) 2)
sds's avatar
sds committed
415 416
         (or (not (second results))
             (notnot (first results))))))
417 418 419 420

(defun subtypep*-not-or-fail (type1 type2)
  (let ((results (multiple-value-list (subtypep type1 type2))))
    (and (= (length results) 2)
sds's avatar
sds committed
421 422
         (or (not (second results))
             (not (first results))))))
423

424
;; (declaim (ftype (function (&rest function) (values function &optional))
sds's avatar
sds committed
425
;;              compose))
426

427 428
(defun compose (&rest fns)
  (let ((rfns (reverse fns)))
429
    #'(lambda (x) (loop for f
sds's avatar
sds committed
430
                        in rfns do (setf x (funcall (the function f) x))) x)))
431 432

(defun evendigitp (c)
433
  (notnot (find c "02468")))
434 435

(defun odddigitp (c)
436
  (notnot (find c "13579")))
437 438 439 440

(defun nextdigit (c)
  (cadr (member c '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))))

441 442
(defun is-eq-p (x) #'(lambda (y) (eqt x y)))
(defun is-not-eq-p (x) #'(lambda (y) (not (eqt x y))))
443

444 445 446 447 448
(defun is-eql-p (x) #'(lambda (y) (eqlt x y)))
(defun is-not-eql-p (x) #'(lambda (y) (not (eqlt x y))))

(defun onep (x) (eql x 1))

449 450 451 452 453 454
(defun char-invertcase (c)
  (if (upper-case-p c) (char-downcase c)
    (char-upcase c)))

(defun string-invertcase (s)
  (map 'string #'char-invertcase s))
455

456 457
(defun symbol< (x &rest args)
  (apply #'string< (symbol-name x) (mapcar #'symbol-name args)))
458 459


460 461 462 463 464
(defun make-list-expr (args)
  "Build an expression for computing (LIST . args), but that evades
   CALL-ARGUMENTS-LIMIT."
  (if (cddddr args)
      (list 'list*
sds's avatar
sds committed
465 466 467
            (first args) (second args) (third args) (fourth args)
            (make-list-expr (cddddr args)))
    (cons 'list args)))
468

469
(defparameter +standard-chars+
470
  (coerce
471
  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_+|\\=-`{}[]:\";'<>?,./
472
 " 'simple-base-string))
473

474
(defparameter
475
  +base-chars+ #.(coerce
sds's avatar
sds committed
476 477 478 479 480 481 482
                  (concatenate 'string
                               "abcdefghijklmnopqrstuvwxyz"
                               "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                               "0123456789"
                               "<,>.?/\"':;[{]}~`!@#$%^&*()_-+= \\|")
                  'simple-base-string))

483

484
(declaim (type simple-base-string +base-chars+))
485

486
(defparameter +num-base-chars+ (length +base-chars+))
487 488 489 490 491 492

(defparameter +alpha-chars+ (subseq +standard-chars+ 0 52))
(defparameter +lower-case-chars+ (subseq +alpha-chars+ 0 26))
(defparameter +upper-case-chars+ (subseq +alpha-chars+ 26 52))
(defparameter +alphanumeric-chars+ (subseq +standard-chars+ 0 62))
(defparameter +digit-chars+ "0123456789")
493
(defparameter +extended-digit-chars+ (coerce
sds's avatar
sds committed
494 495
                                      "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                      'simple-base-string))
496 497

(declaim (type simple-base-string +alpha-chars+ +lower-case-chars+
sds's avatar
sds committed
498 499
               +upper-case-chars+ +alphanumeric-chars+ +extended-digit-chars+
               +standard-chars+))
500

501
(defparameter +code-chars+
502
  (coerce (loop for i from 0 below 256
sds's avatar
sds committed
503 504 505
                for c = (code-char i)
                when c collect c)
          'simple-string))
506 507

(declaim (type simple-string +code-chars+))
508

509
(defparameter +rev-code-chars+ (reverse +code-chars+))
510 511 512 513 514

;;; Used in checking for continuable errors

(defun has-non-abort-restart (c)
  (throw 'handled
sds's avatar
sds committed
515 516 517 518
         (if (position 'abort (the list (compute-restarts c))
                       :key #'restart-name :test-not #'eq)
             'success
           'fail)))
519 520 521 522

(defmacro handle-non-abort-restart (&body body)
  `(catch 'handled
     (handler-bind ((error #'has-non-abort-restart))
sds's avatar
sds committed
523
                   ,@body)))
524

525 526 527 528 529
;;; used in elt.lsp
(defun elt-v-6-body ()
  (let ((x (make-int-list 1000)))
    (let ((a (make-array '(1000) :initial-contents x)))
      (loop
sds's avatar
sds committed
530 531 532
          for i from 0 to 999 do
            (unless (eql i (elt a i)) (return nil))
          finally (return t)))))
533 534 535 536 537 538 539 540 541 542 543

(defun make-adj-array (n &key initial-contents)
  (if initial-contents
      (make-array n :adjustable t :initial-contents initial-contents)
    (make-array n :adjustable t)))

;;; used in elt.lsp
(defun elt-adj-array-6-body ()
  (let ((x (make-int-list 1000)))
    (let ((a (make-adj-array '(1000) :initial-contents x)))
      (loop
sds's avatar
sds committed
544 545 546
          for i from 0 to 999 do
            (unless (eql i (elt a i)) (return nil))
          finally (return t)))))
547 548 549 550 551

(defparameter *displaced* (make-int-array 100000))

(defun make-displaced-array (n displacement)
  (make-array n :displaced-to *displaced*
552

sds's avatar
sds committed
553
              :displaced-index-offset displacement))
554 555 556 557

;;; used in fill.lsp
(defun array-unsigned-byte-fill-test-fn (byte-size &rest fill-args)
  (let* ((a (make-array '(5) :element-type (list 'unsigned-byte byte-size)
sds's avatar
sds committed
558 559
                        :initial-contents '(1 2 3 4 5)))
         (b (apply #'fill a fill-args)))
560
    (values (eqt a b)
sds's avatar
sds committed
561
            (map 'list #'identity a))))
562 563 564 565 566 567 568 569 570

;;; used in fill-strings.lsp
(defun array-string-fill-test-fn (a &rest fill-args)
  (setq a (copy-seq a))
  (let ((b (apply #'fill a fill-args)))
    (values (eqt a b) b)))

;;; From types-and-class.lsp

pfdietz's avatar
pfdietz committed
571 572 573 574 575 576
(defparameter +float-types+
  '(long-float double-float short-float single-float))

(defparameter *subtype-table*
(let ((table
       '(
sds's avatar
sds committed
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
         (null symbol)
         (symbol t)
         (boolean symbol)
         (standard-object t)
         (function t)
         (compiled-function function)
         (generic-function function)
         (standard-generic-function generic-function)
         (class standard-object)
         (built-in-class class)
         (structure-class class)
         (standard-class class)
         (method standard-object)
         (standard-method method)
         (structure-object t)
         (method-combination t)
         (condition t)
         (serious-condition condition)
         (error serious-condition)
         (type-error error)
         (simple-type-error type-error)
         (simple-condition condition)
         (simple-type-error simple-condition)
         (parse-error error)
         (hash-table t)
         (cell-error error)
         (unbound-slot cell-error)
         (warning condition)
         (style-warning warning)
         (storage-condition serious-condition)
         (simple-warning warning)
         (simple-warning simple-condition)
         (keyword symbol)
         (unbound-variable cell-error)
         (control-error error)
         (program-error error)
         (undefined-function cell-error)
         (package t)
         (package-error error)
         (random-state t)
         (number t)
         (real number)
         (complex number)
         (float real)
         (short-float float)
         (single-float float)
         (double-float float)
         (long-float float)
         (rational real)
         (integer rational)
         (ratio rational)
         (signed-byte integer)
         (integer signed-byte)
         (unsigned-byte signed-byte)
         (bit unsigned-byte)
         (fixnum integer)
         (bignum integer)
         (bit fixnum)
         (arithmetic-error error)
         (division-by-zero arithmetic-error)
         (floating-point-invalid-operation arithmetic-error)
         (floating-point-inexact arithmetic-error)
         (floating-point-overflow arithmetic-error)
         (floating-point-underflow arithmetic-error)
         (character t)
         (base-char character)
         (standard-char base-char)
         (extended-char character)
         (sequence t)
         (list sequence)
         (null list)
         (null boolean)
         (cons list)
         (array t)
         (simple-array array)
         (vector sequence)
         (vector array)
         (string vector)
         (bit-vector vector)
         (simple-vector vector)
         (simple-vector simple-array)
         (simple-bit-vector bit-vector)
         (simple-bit-vector simple-array)
         (base-string string)
         (simple-string string)
         (simple-string simple-array)
         (simple-base-string base-string)
         (simple-base-string simple-string)
         (pathname t)
         (logical-pathname pathname)
         (file-error error)
         (stream t)
         (broadcast-stream stream)
         (concatenated-stream stream)
         (echo-stream stream)
         (file-stream stream)
         (string-stream stream)
         (synonym-stream stream)
         (two-way-stream stream)
         (stream-error error)
         (end-of-file stream-error)
         (print-not-readable error)
         (readtable t)
         (reader-error parse-error)
         (reader-error stream-error)
         )))
pfdietz's avatar
pfdietz committed
683 684
  (when (subtypep* 'character 'base-char)
    (setq table
sds's avatar
sds committed
685 686 687 688 689 690 691
          (append
           '((character base-char)
             ;; (string base-string)
             ;; (simple-string simple-base-string)
             )
           table)))

pfdietz's avatar
pfdietz committed
692 693
  table))

694
(defparameter *disjoint-types-list*
695 696 697 698
    '(cons symbol array
      number character hash-table function readtable package
      pathname stream random-state condition restart))

699
(defparameter *disjoint-types-list2*
700 701
  `((cons (cons t t) (cons t (cons t t)) (eql (nil)))
    (symbol keyword boolean null (eql a) (eql nil) (eql t) (eql *))
702
    (array vector simple-array simple-vector string simple-string
sds's avatar
sds committed
703
           base-string simple-base-string (eql #()))
704
    (character base-char standard-char (eql #\a)
sds's avatar
sds committed
705 706
               ,@(if (subtypep 'character 'base-char) nil
                   (list 'extended-char)))
707
    (function compiled-function generic-function standard-generic-function
sds's avatar
sds committed
708
              (eql ,#'car))
709 710
    (package (eql ,(find-package "COMMON-LISP")))
    (pathname logical-pathname (eql #p""))
711
    (stream broadcast-stream concatenated-stream echo-stream
sds's avatar
sds committed
712
            file-stream string-stream synonym-stream two-way-stream)
pfdietz's avatar
pfdietz committed
713
    (number real complex float integer rational ratio fixnum
sds's avatar
sds committed
714 715 716 717 718
            bit (integer 0 100) (float 0.0 100.0) (integer 0 *)
            (rational 0 *) (mod 10)
            (eql 0)
            ,@(and (not (subtypep 'bignum nil))
                   (list 'bignum)))
719 720 721 722 723
    (random-state)
    ,*condition-types*
    (restart)
    (readtable)))

724 725 726 727 728 729 730
(defparameter *types-list3*
  (reduce #'append *disjoint-types-list2* :from-end t))

(defun trim-list (list n)
  (let ((len (length list)))
    (if (<= len n) list
      (append (subseq list 0 n)
sds's avatar
sds committed
731
              (format nil "And ~A more omitted." (- len n))))))
732

733 734 735
(defun is-t-or-nil (e)
  (or (eqt e t) (eqt e nil)))

736 737 738 739
(defun is-builtin-class (type)
  (when (symbolp type) (setq type (find-class type nil)))
  (typep type 'built-in-class))

740 741 742 743 744
(defun even-size-p (a)
  (some #'evenp (array-dimensions a)))


(defun safe-elt (x n)
745
  (classify-error* (elt x n)))
pfdietz's avatar
pfdietz committed
746 747

(defmacro defstruct* (&body args)
748
  `(eval-when (:load-toplevel :compile-toplevel :execute)
749
     (handler-case (eval '(defstruct ,@args))
sds's avatar
sds committed
750
                      (serious-condition () nil))))
751 752 753 754 755

(defun safely-delete-package (package-designator)
  (let ((package (find-package package-designator)))
    (when package
      (let ((used-by (package-used-by-list package)))
sds's avatar
sds committed
756 757
        (dolist (using-package used-by)
          (unuse-package package using-package)))
758 759
      (delete-package package))))

760
#-(or allegro openmcl lispworks)
pfdietz's avatar
pfdietz committed
761 762 763 764
(defun delete-all-versions (pathspec)
  "Replace the versions field of the pathname specified by pathspec with
   :wild, and delete all the files this refers to."
  (let* ((wild-pathname (make-pathname :version :wild :defaults (pathname pathspec)))
sds's avatar
sds committed
765 766
         (truenames (directory wild-pathname)))
    (mapc #'delete-file truenames)))
pfdietz's avatar
pfdietz committed
767

768 769
;;; This is a hack to get around an ACL bug; OpenMCL also apparently
;;; needs it
770
#+(or allegro openmcl lispworks)
771 772 773
(defun delete-all-versions (pathspec)
  (when (probe-file pathspec) (delete-file pathspec)))

774 775
(defconstant +fail-count-limit+ 20)

776 777 778 779 780 781 782
(defun frob-simple-condition (c expected-fmt &rest expected-args)
  "Try out the format control and format arguments of a simple-condition C,
   but make no assumptions about what they print as, only that they
   do print."
  (declare (ignore expected-fmt expected-args))
  (and (typep c 'simple-condition)
       (let ((fc (simple-condition-format-control c))
sds's avatar
sds committed
783 784 785 786
             (args (simple-condition-format-arguments c)))
         (and
          (stringp (apply #'format nil fc args))
          t))))
787 788 789 790 791

(defun frob-simple-error (c expected-fmt &rest expected-args)
  (and (typep c 'simple-error)
       (apply #'frob-simple-condition c expected-fmt expected-args)))

792 793 794
(defun frob-simple-warning (c expected-fmt &rest expected-args)
  (and (typep c 'simple-warning)
       (apply #'frob-simple-condition c expected-fmt expected-args)))
795 796 797 798 799 800 801

(defparameter *array-element-types*
  '(t (integer 0 0)
      bit (unsigned-byte 8) (unsigned-byte 16)
      (unsigned-byte 32) float short-float
      single-float double-float long-float
      nil character base-char symbol boolean null))
802 803 804 805

(defun collect-properties (plist prop)
  "Collect all the properties in plist for a property prop."
  (loop for e on plist by #'cddr
sds's avatar
sds committed
806 807
        when (eql (car e) prop)
        collect (cadr e)))
808 809 810 811 812 813

(defmacro def-macro-test (test-name macro-form)
  (let ((macro-name (car macro-form)))
    (assert (symbolp macro-name))
    `(deftest ,test-name
       (values
sds's avatar
sds committed
814 815 816 817 818 819 820 821
        (signals-error (funcall (macro-function ',macro-name))
                       program-error)
        (signals-error (funcall (macro-function ',macro-name)
                                ',macro-form)
                       program-error)
        (signals-error (funcall (macro-function ',macro-name)
                                ',macro-form nil nil)
                       program-error))
822 823 824 825 826 827
       t t t)))

(defun typep* (element type)
  (not (not (typep element type))))

(defun applyf (fn &rest args)
828 829 830 831 832
  (etypecase fn
    (symbol
     #'(lambda (&rest more-args) (apply (the symbol fn) (append args more-args))))
    (function
     #'(lambda (&rest more-args) (apply (the function fn) (append args more-args))))))
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

(defun slot-boundp* (object slot)
  (notnot (slot-boundp object slot)))

(defun slot-exists-p* (object slot)
  (notnot (slot-exists-p object slot)))

(defun map-slot-boundp* (c slots)
  (mapcar (applyf #'slot-boundp c) slots))

(defun map-slot-exists-p* (c slots)
  (mapcar (applyf #'slot-exists-p* c) slots))

(defun map-slot-value (c slots)
  (mapcar (applyf #'slot-value c) slots))

(defun map-typep* (object types)
  (mapcar (applyf #'typep* object) types))
851 852 853 854

(defun slot-value-or-nil (object slot-name)
  (and (slot-exists-p object slot-name)
       (slot-boundp object slot-name)
855
       (slot-value object slot-name)))
856 857 858 859 860 861 862 863

(defun is-noncontiguous-sublist-of (list1 list2)
  (loop
   for x in list1
   do (loop
       when (null list2) do (return-from is-noncontiguous-sublist-of nil)
       when (eql x (pop list2)) do (return))
   finally (return t)))
864 865 866 867 868 869 870 871

;;; This defines a new metaclass to allow us to get around
;;; the restriction in section 11.1.2.1.2, bullet 19 in some
;;; object system tests

;;; (when (typep (find-class 'standard-class) 'standard-class)
;;;  (defclass substandard-class (standard-class) ())
;;;  (defparameter *can-define-metaclasses* t))
872 873 874 875 876 877 878

;;; Macro for testing that something is undefined but 'harmless'

(defmacro defharmless (name form)
  `(deftest ,name
     (block done
       (let ((*debugger-hook* #'(lambda (&rest args)
sds's avatar
sds committed
879 880 881 882 883
                                  (declare (ignore args))
                                  (return-from done :good))))
         (handler-case
          (unwind-protect (eval ',form) (return-from done :good))
          (condition () :good))))
884
     :good))
885

886 887 888 889 890 891 892 893
(defun rational-safely (x)
  "Rational a floating point number, making sure the rational
   number isn't 'too big'.  This is important in implementations such
   as clisp where the floating bounds can be very large."
  (assert (floatp x))
  (multiple-value-bind (significand exponent sign)
      (integer-decode-float x)
    (let ((limit 1000)
sds's avatar
sds committed
894
          (radix (float-radix x)))
895 896
      (cond
       ((< exponent (- limit))
sds's avatar
sds committed
897
        (* significand (expt radix (- limit)) sign))
898
       ((> exponent limit)
sds's avatar
sds committed
899
        (* significand (expt radix limit) sign))
pfdietz's avatar
pfdietz committed
900 901
       (t (rational x))))))

902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
(declaim (special *similarity-list*))

(defun is-similar (x y)
  (let ((*similarity-list* nil))
    (is-similar* x y)))

(defgeneric is-similar* (x y))

(defmethod is-similar* ((x number) (y number))
  (and (eq (class-of x) (class-of y))
       (= x y)
       t))

(defmethod is-similar* ((x character) (y character))
  (and (char= x y) t))

(defmethod is-similar* ((x symbol) (y symbol))
  (if (null (symbol-package x))
      (and (null (symbol-package y))
sds's avatar
sds committed
921
           (is-similar* (symbol-name x) (symbol-name y)))
922 923 924 925 926 927 928
    ;; I think the requirements for interned symbols in
    ;; 3.2.4.2.2 boils down to EQ after the symbols are in the lisp
    (eq x y))
  t)

(defmethod is-similar* ((x random-state) (y random-state))
  (let ((copy-of-x (make-random-state x))
sds's avatar
sds committed
929 930
        (copy-of-y (make-random-state y))
        (bound (1- (ash 1 24))))
931 932 933 934 935
    (and
     ;; Try 50 values, and assume the random state are the same
     ;; if all the values are the same.  Assuming the RNG is not
     ;; very pathological, this should be acceptable.
     (loop repeat 50
sds's avatar
sds committed
936 937
           always (eql (random bound copy-of-x)
                       (random bound copy-of-y)))
938 939 940 941 942
     t)))

(defmethod is-similar* ((x cons) (y cons))
  (or (and (eq x y) t)
      (and (loop for (x2 . y2) in *similarity-list*
sds's avatar
sds committed
943 944
                 thereis (and (eq x x2) (eq y y2)))
           t)
945
      (let ((*similarity-list*
sds's avatar
sds committed
946 947 948 949 950
             (cons (cons x y) *similarity-list*)))
        (and (is-similar* (car x) (car y))
             ;; If this causes stack problems,
             ;; convert to a loop
             (is-similar* (cdr x) (cdr y))))))
951 952 953 954 955

(defmethod is-similar* ((x vector) (y vector))
  (or (and (eq x y) t)
      (and
       (or (not (typep x 'simple-array))
sds's avatar
sds committed
956
           (typep x 'simple-array))
957 958
       (= (length x) (length y))
       (is-similar* (array-element-type x)
sds's avatar
sds committed
959
                    (array-element-type y))
960
       (loop for i below (length x)
sds's avatar
sds committed
961
             always (is-similar* (aref x i) (aref y i)))
962 963 964 965 966 967
       t)))

(defmethod is-similar* ((x array) (y array))
  (or (and (eq x y) t)
      (and
       (or (not (typep x 'simple-array))
sds's avatar
sds committed
968
           (typep x 'simple-array))
969 970 971
       (= (array-rank x) (array-rank y))
       (equal (array-dimensions x) (array-dimensions y))
       (is-similar* (array-element-type x)
sds's avatar
sds committed
972
                    (array-element-type y))
973
       (let ((*similarity-list*
sds's avatar
sds committed
974 975 976 977
              (cons (cons x y) *similarity-list*)))
         (loop for i below (array-total-size x)
               always (is-similar* (row-major-aref x i)
                                   (row-major-aref y i))))
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
       t)))

(defmethod is-similar* ((x hash-table) (y hash-table))
  ;; FIXME  Add similarity check for hash tables
  (error "Sorry, we're not computing this yet."))

(defmethod is-similar* ((x pathname) (y pathname))
  (and
   (is-similar* (pathname-host x) (pathname-host y))
   (is-similar* (pathname-device x) (pathname-device y))
   (is-similar* (pathname-directory x) (pathname-directory y))
   (is-similar* (pathname-name x) (pathname-name y))
   (is-similar* (pathname-type x) (pathname-type y))
   (is-similar* (pathname-version x) (pathname-version y))
   t))

(defmethod is-similar* ((x t) (y t))
  (and (eql x y) t))
996 997

(defparameter *initial-print-pprint-dispatch* (if (boundp '*print-pprint-dispatch*)
sds's avatar
sds committed
998 999
                                                  *print-pprint-dispatch*
                                                nil))
1000 1001 1002

(defmacro my-with-standard-io-syntax (&body body)
  `(let ((*package* (find-package "COMMON-LISP-USER"))
sds's avatar
sds committed
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
         (*print-array* t)
         (*print-base* 10)
         (*print-case* :upcase)
         (*print-circle* nil)
         (*print-escape* t)
         (*print-gensym* t)
         (*print-length* nil)
         (*print-level* nil)
         (*print-lines* nil)
         (*print-miser-width* nil)
         (*print-pprint-dispatch* *initial-print-pprint-dispatch*)
         (*print-pretty* nil)
         (*print-radix* nil)
         (*print-readably* t)
         (*print-right-margin* nil)
         (*read-base* 10)
         (*read-default-float-format* 'single-float)
         (*read-eval* t)
         (*read-suppress* nil)
         (*readtable* (copy-readtable nil)))
1023
     ,@body))
1024 1025 1026 1027 1028

;;; Function to produce a non-simple string

(defun make-special-string (string &key fill adjust displace base)
  (let* ((len (length string))
sds's avatar
sds committed
1029 1030
         (len2 (if fill (+ len 4) len))
         (etype (if base 'base-char 'character)))
1031
    (if displace
sds's avatar
sds committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
        (let ((s0 (make-array (+ len2 5)
                              :initial-contents
                              (concatenate 'string
                                           (make-string 2 :initial-element #\X)
                                           string
                                           (make-string (if fill 7 3)
                                                        :initial-element #\Y))
                              :element-type etype)))
          (make-array len2 :element-type etype
                      :adjustable adjust
                      :fill-pointer (if fill len nil)
                      :displaced-to s0
                      :displaced-index-offset 2))
1045
      (make-array len2 :element-type etype
sds's avatar
sds committed
1046 1047 1048 1049
                  :initial-contents
                  (if fill (concatenate 'string string "ZZZZ") string)
                  :fill-pointer (if fill len nil)
                  :adjustable adjust))))
1050 1051 1052

(defmacro do-special-strings ((var string-form &optional ret-form) &body forms)
  (let ((string (gensym))
sds's avatar
sds committed
1053 1054 1055 1056
        (fill (gensym "FILL"))
        (adjust (gensym "ADJUST"))
        (base (gensym "BASE"))
        (displace (gensym "DISPLACE")))
1057 1058
    `(let ((,string ,string-form))
       (dolist (,fill '(nil t) ,ret-form)
sds's avatar
sds committed
1059 1060 1061 1062 1063 1064 1065 1066
         (dolist (,adjust '(nil t))
           (dolist (,base '(nil t))
             (dolist (,displace '(nil t))
               (let ((,var (make-special-string
                            ,string
                            :fill ,fill :adjust ,adjust
                            :base ,base :displace ,displace)))
                 ,@forms))))))))
1067 1068 1069

(defun make-special-integer-vector (contents &key fill adjust displace (etype 'integer))
  (let* ((len (length contents))
sds's avatar
sds committed
1070 1071 1072
         (min (reduce #'min contents))
         (max (reduce #'max contents))
         (len2 (if fill (+ len 4) len)))
1073
    (unless (and (typep min etype)
sds's avatar
sds committed
1074
                 (typep max etype))
1075 1076
      (setq etype `(integer ,min ,max)))
    (if displace
sds's avatar
sds committed
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
        (let ((s0 (make-array (+ len2 5)
                              :initial-contents
                              (concatenate 'list
                                           (make-list 2 :initial-element
                                                      (if (typep 0 etype) 0 min))
                                           contents
                                           (make-list (if fill 7 3)
                                                      :initial-element
                                                      (if (typep 1 etype) 1 max)))
                              :element-type etype)))
          (make-array len2 :element-type etype
                      :adjustable adjust
                      :fill-pointer (if fill len nil)
                      :displaced-to s0
                      :displaced-index-offset 2))
1092
      (make-array len2 :element-type etype
sds's avatar
sds committed
1093 1094 1095 1096 1097 1098 1099 1100
                  :initial-contents
                  (if fill (concatenate 'list
                                        contents
                                        (make-list 4 :initial-element
                                                   (if (typep 2 etype) 2 (floor (+ min max) 2))))
                    contents)
                  :fill-pointer (if fill len nil)
                  :adjustable adjust))))
1101 1102 1103

(defmacro do-special-integer-vectors ((var vec-form &optional ret-form) &body forms)
  (let ((vector (gensym))
sds's avatar
sds committed
1104 1105 1106 1107
        (fill (gensym "FILL"))
        (adjust (gensym "ADJUST"))
        (etype (gensym "ETYPE"))
        (displace (gensym "DISPLACE")))
1108 1109
    `(let ((,vector ,vec-form))
       (dolist (,fill '(nil t) ,ret-form)
sds's avatar
sds committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
         (dolist (,adjust '(nil t))
           (dolist (,etype ',(append (loop for i from 1 to 32 collect `(unsigned-byte ,i))
                                     (loop for i from 2 to 32 collect `(signed-byte ,i))
                                     '(integer)))
             (dolist (,displace '(nil t))
               (let ((,var (make-special-integer-vector
                            ,vector
                            :fill ,fill :adjust ,adjust
                            :etype ,etype :displace ,displace)))
                 ,@forms))))))))
pfdietz's avatar
pfdietz committed
1120 1121 1122 1123 1124 1125 1126

;;; Return T if arg X is a string designator in this implementation

(defun string-designator-p (x)
  (handler-case
   (progn (string x) t)
   (error nil)))
1127 1128

;;; Approximate comparison of numbers
1129
#|
1130 1131 1132 1133
(defun approx= (x y)
  (let ((eps 1.0d-4))
    (<= (abs (- x y))
       (* eps (max (abs x) (abs y))))))
pfdietz's avatar
pfdietz committed
1134 1135 1136 1137 1138
|#

;;; Approximate equality function
(defun approx= (x y &optional (eps (epsilon x)))
  (<= (abs (/ (- x y) (max (abs x) 1))) eps))
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156

(defun epsilon (number)
  (etypecase number
    (complex (* 2 (epsilon (realpart number)))) ;; crude
    (short-float short-float-epsilon)
    (single-float single-float-epsilon)
    (double-float double-float-epsilon)
    (long-float long-float-epsilon)
    (rational 0)))

(defun negative-epsilon (number)
  (etypecase number
    (complex (* 2 (negative-epsilon (realpart number)))) ;; crude
    (short-float short-float-negative-epsilon)
    (single-float single-float-negative-epsilon)
    (double-float double-float-negative-epsilon)
    (long-float long-float-negative-epsilon)
    (rational 0)))
1157 1158

(defun sequencep (x) (typep x 'sequence))
pfdietz's avatar
pfdietz committed
1159 1160 1161 1162 1163 1164 1165 1166

(defun typef (type) #'(lambda (x) (typep x type)))

(defun package-designator-p (x)
  "TRUE if x could be a package designator.  The package need not
   actually exist."
  (or (packagep x)
      (handler-case (and (locally (declare (optimize safety))
sds's avatar
sds committed
1167 1168 1169
                                  (string x))
                         t)
                    (type-error () nil))))
1170 1171 1172 1173 1174 1175

(defmacro def-fold-test (name form)
  "Create a test that FORM, which should produce a fresh value,
   does not improperly introduce sharing during constant folding."
  `(deftest ,name
     (flet ((%f () (declare (optimize (speed 3) (safety 0) (space 0)
sds's avatar
sds committed
1176 1177
                                      (compilation-speed 0) (debug 0)))
               ,form))
1178 1179
       (eq (%f) (%f)))
     nil))
1180 1181 1182 1183 1184 1185 1186 1187

;;; Macro used in tests of environments in system macros
;;; This was inspired by a bug in ACL 8.0 beta where CONSTANTP
;;; was being called in some system macros without the proper
;;; environment argument

(defmacro expand-in-current-env (macro-form &environment env)
  (macroexpand macro-form env))