Optimize some comparison functions for EQ cases.
[sbcl.git] / src / code / pred.lisp
1 ;;;; predicate functions (EQUAL and friends, and type predicates)
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!IMPL")
13 \f
14 ;;;; miscellaneous non-primitive predicates
15
16 #!-sb-fluid (declaim (inline streamp))
17 (defun streamp (stream)
18   (typep stream 'stream))
19
20 ;;; various (VECTOR FOO) type predicates, not implemented as simple
21 ;;; widetag tests
22 (macrolet
23     ((def ()
24        `(progn
25           ,@(loop for (name spec) in *vector-without-complex-typecode-infos*
26                   collect `(defun ,name (x)
27                              (or (typep x '(simple-array ,spec (*)))
28                                  (and (complex-vector-p x)
29                                       (do ((data (%array-data-vector x) (%array-data-vector data)))
30                                           ((not (array-header-p data)) (typep data '(simple-array ,spec (*))))))))))))
31   (def))
32
33 ;;; Is X an extended sequence?
34 (defun extended-sequence-p (x)
35   (and (not (listp x))
36        (not (vectorp x))
37        (let* ((slayout #.(info :type :compiler-layout 'sequence))
38              (depthoid #.(layout-depthoid (info :type :compiler-layout 'sequence)))
39              (layout (layout-of x)))
40         (when (layout-invalid layout)
41           (setq layout (update-object-layout-or-invalid x slayout)))
42         (if (eq layout slayout)
43             t
44             (let ((inherits (layout-inherits layout)))
45               (declare (optimize (safety 0)))
46               (and (> (length inherits) depthoid)
47                    (eq (svref inherits depthoid) slayout)))))))
48
49 ;;; Is X a SEQUENCE?  Harder than just (OR VECTOR LIST)
50 (defun sequencep (x)
51   (or (listp x)
52       (vectorp x)
53       (let* ((slayout #.(info :type :compiler-layout 'sequence))
54              (depthoid #.(layout-depthoid (info :type :compiler-layout 'sequence)))
55              (layout (layout-of x)))
56         (when (layout-invalid layout)
57           (setq layout (update-object-layout-or-invalid x slayout)))
58         (if (eq layout slayout)
59             t
60             (let ((inherits (layout-inherits layout)))
61               (declare (optimize (safety 0)))
62               (and (> (length inherits) depthoid)
63                    (eq (svref inherits depthoid) slayout)))))))
64 \f
65 ;;;; primitive predicates. These must be supported directly by the
66 ;;;; compiler.
67
68 (defun not (object)
69   #!+sb-doc
70   "Return T if X is NIL, otherwise return NIL."
71   (not object))
72
73 ;;; All the primitive type predicate wrappers share a parallel form..
74 (macrolet ((def-type-predicate-wrapper (pred)
75              (let* ((name (symbol-name pred))
76                     (stem (string-left-trim "%" (string-right-trim "P-" name)))
77                     (article (if (position (schar name 0) "AEIOU") "an" "a")))
78                `(defun ,pred (object)
79                   ,(format nil
80                            "Return true if OBJECT is ~A ~A, and NIL otherwise."
81                            article
82                            stem)
83                   ;; (falling through to low-level implementation)
84                   (,pred object)))))
85   (def-type-predicate-wrapper array-header-p)
86   (def-type-predicate-wrapper arrayp)
87   (def-type-predicate-wrapper atom)
88   (def-type-predicate-wrapper base-char-p)
89   (def-type-predicate-wrapper base-string-p)
90   #!+sb-unicode (def-type-predicate-wrapper character-string-p)
91   (def-type-predicate-wrapper bignump)
92   (def-type-predicate-wrapper bit-vector-p)
93   (def-type-predicate-wrapper characterp)
94   (def-type-predicate-wrapper code-component-p)
95   (def-type-predicate-wrapper consp)
96   (def-type-predicate-wrapper compiled-function-p)
97   (def-type-predicate-wrapper complexp)
98   (def-type-predicate-wrapper complex-double-float-p)
99   (def-type-predicate-wrapper complex-float-p)
100   #!+long-float (def-type-predicate-wrapper complex-long-float-p)
101   (def-type-predicate-wrapper complex-rational-p)
102   (def-type-predicate-wrapper complex-single-float-p)
103   ;; (COMPLEX-VECTOR-P is not included here since it's awkward to express
104   ;; the type it tests for in the Common Lisp type system, and since it's
105   ;; only used in the implementation of a few specialized things.)
106   (def-type-predicate-wrapper double-float-p)
107   (def-type-predicate-wrapper extended-char-p)
108   (def-type-predicate-wrapper fdefn-p)
109   (def-type-predicate-wrapper fixnump)
110   (def-type-predicate-wrapper floatp)
111   (def-type-predicate-wrapper functionp)
112   (def-type-predicate-wrapper integerp)
113   (def-type-predicate-wrapper listp)
114   (def-type-predicate-wrapper long-float-p)
115   (def-type-predicate-wrapper lra-p)
116   (def-type-predicate-wrapper null)
117   (def-type-predicate-wrapper numberp)
118   (def-type-predicate-wrapper rationalp)
119   (def-type-predicate-wrapper ratiop)
120   (def-type-predicate-wrapper realp)
121   (def-type-predicate-wrapper short-float-p)
122   (def-type-predicate-wrapper single-float-p)
123   #!+sb-simd-pack (def-type-predicate-wrapper simd-pack-p)
124   (def-type-predicate-wrapper %instancep)
125   (def-type-predicate-wrapper symbolp)
126   (def-type-predicate-wrapper %other-pointer-p)
127   (def-type-predicate-wrapper system-area-pointer-p)
128   (def-type-predicate-wrapper weak-pointer-p)
129   #!+#.(cl:if (cl:= 32 sb!vm:n-word-bits) '(and) '(or))
130   (progn
131     (def-type-predicate-wrapper unsigned-byte-32-p)
132     (def-type-predicate-wrapper signed-byte-32-p))
133   #!+#.(cl:if (cl:= 64 sb!vm:n-word-bits) '(and) '(or))
134   (progn
135     (def-type-predicate-wrapper unsigned-byte-64-p)
136     (def-type-predicate-wrapper signed-byte-64-p))
137   ;; Specialized array types
138   (macrolet ((saetp-defs ()
139                `(progn
140                   ,@(map 'list
141                          (lambda (saetp)
142                            `(def-type-predicate-wrapper
143                                 ,(symbolicate (sb!vm:saetp-primitive-type-name saetp) "-P")))
144                          sb!vm:*specialized-array-element-type-properties*))))
145     (saetp-defs))
146   ;; Other array types
147   (def-type-predicate-wrapper simple-array-p)
148   (def-type-predicate-wrapper simple-string-p)
149   (def-type-predicate-wrapper stringp)
150   (def-type-predicate-wrapper vectorp)
151   (def-type-predicate-wrapper vector-nil-p))
152
153 #!+(or x86 x86-64)
154 (defun fixnum-mod-p (x limit)
155   (and (fixnump x)
156        (<= 0 x limit)))
157
158 \f
159 ;;; Return the specifier for the type of object. This is not simply
160 ;;; (TYPE-SPECIFIER (CTYPE-OF OBJECT)) because CTYPE-OF has different
161 ;;; goals than TYPE-OF. In particular, speed is more important than
162 ;;; precision, and it is not permitted to return member types.
163 (defun type-of (object)
164   #!+sb-doc
165   "Return the type of OBJECT."
166   (typecase object
167     (fixnum
168      (cond
169        ((<= 0 object 1) 'bit)
170        ((< object 0) 'fixnum)
171        (t '(integer 0 #.sb!xc:most-positive-fixnum))))
172     (integer
173      (if (>= object 0)
174          '(integer #.(1+ sb!xc:most-positive-fixnum))
175          'bignum))
176     (standard-char 'standard-char)
177     (base-char 'base-char)
178     (extended-char 'extended-char)
179     ((member t) 'boolean)
180     (keyword 'keyword)
181     ((or array complex #!+sb-simd-pack sb!kernel:simd-pack)
182      (type-specifier (ctype-of object)))
183     (t
184      (let* ((classoid (layout-classoid (layout-of object)))
185             (name (classoid-name classoid)))
186        (if (%instancep object)
187            (case name
188              (sb!alien-internals:alien-value
189               `(sb!alien:alien
190                 ,(sb!alien-internals:unparse-alien-type
191                   (sb!alien-internals:alien-value-type object))))
192              (t
193               (let ((pname (classoid-proper-name classoid)))
194                 (if (classoid-p pname)
195                     (classoid-pcl-class pname)
196                     pname))))
197            name)))))
198 \f
199 ;;;; equality predicates
200
201 ;;; This is real simple, 'cause the compiler takes care of it.
202 (defun eq (obj1 obj2)
203   #!+sb-doc
204   "Return T if OBJ1 and OBJ2 are the same object, otherwise NIL."
205   (eq obj1 obj2))
206
207 (declaim (inline %eql))
208 (defun %eql (obj1 obj2)
209   #!+sb-doc
210   "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
211   (or (eq obj1 obj2)
212       (if (or (typep obj2 'fixnum)
213               (not (typep obj2 'number)))
214           nil
215           (macrolet ((foo (&rest stuff)
216                        `(typecase obj2
217                           ,@(mapcar (lambda (foo)
218                                       (let ((type (car foo))
219                                             (fn (cadr foo)))
220                                         `(,type
221                                           (and (typep obj1 ',type)
222                                                (,fn obj1 obj2)))))
223                                     stuff))))
224             (foo
225              (single-float eql)
226              (double-float eql)
227              #!+long-float
228              (long-float eql)
229              (bignum
230               (lambda (x y)
231                 (zerop (bignum-compare x y))))
232              (ratio
233               (lambda (x y)
234                 (and (eql (numerator x) (numerator y))
235                      (eql (denominator x) (denominator y)))))
236              (complex
237               (lambda (x y)
238                 (and (eql (realpart x) (realpart y))
239                      (eql (imagpart x) (imagpart y))))))))))
240
241 (defun eql (x y)
242   (%eql x y))
243
244 (defun bit-vector-= (x y)
245   (declare (type bit-vector x y))
246   (cond ((eq x y))
247         ((and (simple-bit-vector-p x)
248               (simple-bit-vector-p y))
249          (bit-vector-= x y))            ; DEFTRANSFORM
250         (t
251          (and (= (length x) (length y))
252               (do ((i 0 (1+ i))
253                    (length (length x)))
254                   ((= i length) t)
255                 (declare (fixnum i))
256                 (unless (= (bit x i) (bit y i))
257                   (return nil)))))))
258
259 (defun equal (x y)
260   #!+sb-doc
261   "Return T if X and Y are EQL or if they are structured components whose
262 elements are EQUAL. Strings and bit-vectors are EQUAL if they are the same
263 length and have identical components. Other arrays must be EQ to be EQUAL."
264   ;; Non-tail self-recursion implemented with a local auxiliary function
265   ;; is a lot faster than doing it the straightforward way (at least
266   ;; on x86oids) due to calling convention differences. -- JES, 2005-12-30
267   (labels ((equal-aux (x y)
268              (cond ((%eql x y)
269                     t)
270                    ((consp x)
271                     (and (consp y)
272                          (equal-aux (car x) (car y))
273                          (equal-aux (cdr x) (cdr y))))
274                    ((stringp x)
275                     (and (stringp y) (string= x y)))
276                    ((pathnamep x)
277                     (and (pathnamep y) (pathname= x y)))
278                    ((bit-vector-p x)
279                     (and (bit-vector-p y)
280                          (bit-vector-= x y)))
281                    (t nil))))
282     ;; Use MAYBE-INLINE to get the inline expansion only once (instead
283     ;; of 200 times with INLINE). -- JES, 2005-12-30
284     (declare (maybe-inline equal-aux))
285     (equal-aux x y)))
286
287 ;;; EQUALP comparison of HASH-TABLE values
288 (defun hash-table-equalp (x y)
289   (declare (type hash-table x y))
290   (or (eq x y)
291       (and (hash-table-p y)
292            (eql (hash-table-count x) (hash-table-count y))
293            (eql (hash-table-test x) (hash-table-test y))
294            (block comparison-of-entries
295              (maphash (lambda (key x-value)
296                         (multiple-value-bind (y-value y-value-p)
297                             (gethash key y)
298                           (unless (and y-value-p (equalp x-value y-value))
299                             (return-from comparison-of-entries nil))))
300                       x)
301              t))))
302
303 (defun equalp (x y)
304   #+nil ; KLUDGE: If doc string, should be accurate: Talk about structures
305   ; and HASH-TABLEs.
306   "This is like EQUAL, except more liberal in several respects.
307   Numbers may be of different types, as long as the values are identical
308   after coercion. Characters may differ in alphabetic case. Vectors and
309   arrays must have identical dimensions and EQUALP elements, but may differ
310   in their type restriction."
311   (cond ((eq x y) t)
312         ((characterp x) (and (characterp y) (char-equal x y)))
313         ((numberp x) (and (numberp y) (= x y)))
314         ((consp x)
315          (and (consp y)
316               (equalp (car x) (car y))
317               (equalp (cdr x) (cdr y))))
318         ((pathnamep x)
319          (and (pathnamep y) (pathname= x y)))
320         ((hash-table-p x)
321          (and (hash-table-p y)
322               (hash-table-equalp x y)))
323         ((%instancep x)
324          (let* ((layout-x (%instance-layout x))
325                 (raw-len (layout-n-untagged-slots layout-x))
326                 (total-len (layout-length layout-x))
327                 (normal-len (- total-len raw-len)))
328            (and (%instancep y)
329                 (eq layout-x (%instance-layout y))
330                 (structure-classoid-p (layout-classoid layout-x))
331                 (dotimes (i normal-len t)
332                   (let ((x-el (%instance-ref x i))
333                         (y-el (%instance-ref y i)))
334                     (unless (or (eq x-el y-el)
335                                 (equalp x-el y-el))
336                       (return nil))))
337                 (if (zerop raw-len)
338                     t
339                     (raw-instance-slots-equalp layout-x x y)))))
340         ((vectorp x)
341          (let ((length (length x)))
342            (and (vectorp y)
343                 (= length (length y))
344                 (dotimes (i length t)
345                   (let ((x-el (aref x i))
346                         (y-el (aref y i)))
347                     (unless (or (eq x-el y-el)
348                                 (equalp x-el y-el))
349                       (return nil)))))))
350         ((arrayp x)
351          (and (arrayp y)
352               (= (array-rank x) (array-rank y))
353               (dotimes (axis (array-rank x) t)
354                 (unless (= (array-dimension x axis)
355                            (array-dimension y axis))
356                   (return nil)))
357               (dotimes (index (array-total-size x) t)
358                 (let ((x-el (row-major-aref x index))
359                       (y-el (row-major-aref y index)))
360                   (unless (or (eq x-el y-el)
361                               (equalp x-el y-el))
362                     (return nil))))))
363         (t nil)))
364
365 (/show0 "about to do test cases in pred.lisp")
366 #!+sb-test
367 (let ((test-cases `((0.0 ,(load-time-value (make-unportable-float :single-float-negative-zero)) t)
368                     (0.0 1.0 nil)
369                     (#c(1 0) #c(1.0 0.0) t)
370                     (#c(0 1) #c(0.0 1.0) t)
371                     (#c(1.1 0.0) #c(11/10 0) nil) ; due to roundoff error
372                     ("Hello" "hello" t)
373                     ("Hello" #(#\h #\E #\l #\l #\o) t)
374                     ("Hello" "goodbye" nil))))
375   (/show0 "TEST-CASES bound in pred.lisp")
376   (dolist (test-case test-cases)
377     (/show0 "about to do a TEST-CASE in pred.lisp")
378     (destructuring-bind (x y expected-result) test-case
379       (let* ((result (equalp x y))
380              (bresult (if result 1 0))
381              (expected-bresult (if expected-result 1 0)))
382         (unless (= bresult expected-bresult)
383           (/show0 "failing test in pred.lisp")
384           (error "failed test (EQUALP ~S ~S)" x y))))))
385 (/show0 "done with test cases in pred.lisp")