1.0.30.25: deftransform for ARRAY-IN-BOUNDS-P
[sbcl.git] / src / code / array.lisp
1 ;;;; functions to implement arrays
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
14 #!-sb-fluid
15 (declaim (inline fill-pointer array-has-fill-pointer-p adjustable-array-p
16                  array-displacement))
17 \f
18 ;;;; miscellaneous accessor functions
19
20 ;;; These functions are only needed by the interpreter, 'cause the
21 ;;; compiler inlines them.
22 (macrolet ((def (name)
23              `(progn
24                 (defun ,name (array)
25                   (,name array))
26                 (defun (setf ,name) (value array)
27                   (setf (,name array) value)))))
28   (def %array-fill-pointer)
29   (def %array-fill-pointer-p)
30   (def %array-available-elements)
31   (def %array-data-vector)
32   (def %array-displacement)
33   (def %array-displaced-p)
34   (def %array-diplaced-from))
35
36 (defun %array-rank (array)
37   (%array-rank array))
38
39 (defun %array-dimension (array axis)
40   (%array-dimension array axis))
41
42 (defun %set-array-dimension (array axis value)
43   (%set-array-dimension array axis value))
44
45 (defun %check-bound (array bound index)
46   (declare (type index bound)
47            (fixnum index))
48   (%check-bound array bound index))
49
50 (defun %with-array-data/fp (array start end)
51   (%with-array-data-macro array start end :check-bounds t :check-fill-pointer t))
52
53 (defun %with-array-data (array start end)
54   (%with-array-data-macro array start end :check-bounds t :check-fill-pointer nil))
55
56 (defun %data-vector-and-index (array index)
57   (if (array-header-p array)
58       (multiple-value-bind (vector index)
59           (%with-array-data array index nil)
60         (values vector index))
61       (values array index)))
62 \f
63 ;;;; MAKE-ARRAY
64 (eval-when (:compile-toplevel :execute)
65   (sb!xc:defmacro pick-vector-type (type &rest specs)
66     `(cond ,@(mapcar (lambda (spec)
67                        `(,(if (eq (car spec) t)
68                               t
69                               `(subtypep ,type ',(car spec)))
70                          ,@(cdr spec)))
71                      specs))))
72
73 ;;; These functions are used in the implementation of MAKE-ARRAY for
74 ;;; complex arrays. There are lots of transforms to simplify
75 ;;; MAKE-ARRAY for various easy cases, but not for all reasonable
76 ;;; cases, so e.g. as of sbcl-0.6.6 we still make full calls to
77 ;;; MAKE-ARRAY for any non-simple array. Thus, there's some value to
78 ;;; making this somewhat efficient, at least not doing full calls to
79 ;;; SUBTYPEP in the easy cases.
80 (defun %vector-widetag-and-n-bits (type)
81   (case type
82     ;; Pick off some easy common cases.
83     ;;
84     ;; (Perhaps we should make a much more exhaustive table of easy
85     ;; common cases here. Or perhaps the effort would be better spent
86     ;; on smarter compiler transforms which do the calculation once
87     ;; and for all in any reasonable user programs.)
88     ((t)
89      (values #.sb!vm:simple-vector-widetag #.sb!vm:n-word-bits))
90     ((base-char standard-char #!-sb-unicode character)
91      (values #.sb!vm:simple-base-string-widetag #.sb!vm:n-byte-bits))
92     #!+sb-unicode
93     ((character)
94      (values #.sb!vm:simple-character-string-widetag #.sb!vm:n-word-bits))
95     ((bit)
96      (values #.sb!vm:simple-bit-vector-widetag 1))
97     ;; OK, we have to wade into SUBTYPEPing after all.
98     (t
99      #.`(pick-vector-type type
100          ,@(map 'list
101                 (lambda (saetp)
102                   `(,(sb!vm:saetp-specifier saetp)
103                     (values ,(sb!vm:saetp-typecode saetp)
104                             ,(sb!vm:saetp-n-bits saetp))))
105                 sb!vm:*specialized-array-element-type-properties*)))))
106
107 (defun %complex-vector-widetag (type)
108   (case type
109     ;; Pick off some easy common cases.
110     ((t)
111      #.sb!vm:complex-vector-widetag)
112     ((base-char #!-sb-unicode character)
113      #.sb!vm:complex-base-string-widetag)
114     #!+sb-unicode
115     ((character)
116      #.sb!vm:complex-character-string-widetag)
117     ((nil)
118      #.sb!vm:complex-vector-nil-widetag)
119     ((bit)
120      #.sb!vm:complex-bit-vector-widetag)
121     ;; OK, we have to wade into SUBTYPEPing after all.
122     (t
123      (pick-vector-type type
124        (nil #.sb!vm:complex-vector-nil-widetag)
125        #!-sb-unicode
126        (character #.sb!vm:complex-base-string-widetag)
127        #!+sb-unicode
128        (base-char #.sb!vm:complex-base-string-widetag)
129        #!+sb-unicode
130        (character #.sb!vm:complex-character-string-widetag)
131        (bit #.sb!vm:complex-bit-vector-widetag)
132        (t #.sb!vm:complex-vector-widetag)))))
133
134 (defun make-array (dimensions &key
135                               (element-type t)
136                               (initial-element nil initial-element-p)
137                               (initial-contents nil initial-contents-p)
138                               adjustable fill-pointer
139                               displaced-to displaced-index-offset)
140   (let* ((dimensions (if (listp dimensions) dimensions (list dimensions)))
141          (array-rank (length (the list dimensions)))
142          (simple (and (null fill-pointer)
143                       (not adjustable)
144                       (null displaced-to))))
145     (declare (fixnum array-rank))
146     (when (and displaced-index-offset (null displaced-to))
147       (error "can't specify :DISPLACED-INDEX-OFFSET without :DISPLACED-TO"))
148     (when (and displaced-to
149                (arrayp displaced-to)
150                (not (equal (array-element-type displaced-to)
151                            (upgraded-array-element-type element-type))))
152       (error "Array element type of :DISPLACED-TO array does not match specified element type"))
153     (if (and simple (= array-rank 1))
154         ;; it's a (SIMPLE-ARRAY * (*))
155         (multiple-value-bind (type n-bits)
156             (%vector-widetag-and-n-bits element-type)
157           (declare (type (unsigned-byte 8) type)
158                    (type (integer 0 256) n-bits))
159           (let* ((length (car dimensions))
160                  (array (allocate-vector
161                          type
162                          length
163                          (ceiling
164                           (* (if (or (= type sb!vm:simple-base-string-widetag)
165                                      #!+sb-unicode
166                                      (= type
167                                         sb!vm:simple-character-string-widetag))
168                                  (1+ length)
169                                  length)
170                              n-bits)
171                           sb!vm:n-word-bits))))
172             (declare (type index length))
173             (when initial-element-p
174               (fill array initial-element))
175             (when initial-contents-p
176               (when initial-element-p
177                 (error "can't specify both :INITIAL-ELEMENT and ~
178                        :INITIAL-CONTENTS"))
179               (unless (= length (length initial-contents))
180                 (error "There are ~W elements in the :INITIAL-CONTENTS, but ~
181                        the vector length is ~W."
182                        (length initial-contents)
183                        length))
184               (replace array initial-contents))
185             array))
186         ;; it's either a complex array or a multidimensional array.
187         (let* ((total-size (reduce #'* dimensions))
188                (data (or displaced-to
189                          (data-vector-from-inits
190                           dimensions total-size element-type
191                           initial-contents initial-contents-p
192                           initial-element initial-element-p)))
193                (array (make-array-header
194                        (cond ((= array-rank 1)
195                               (%complex-vector-widetag element-type))
196                              (simple sb!vm:simple-array-widetag)
197                              (t sb!vm:complex-array-widetag))
198                        array-rank)))
199           (cond (fill-pointer
200                  (unless (= array-rank 1)
201                    (error "Only vectors can have fill pointers."))
202                  (let ((length (car dimensions)))
203                    (declare (fixnum length))
204                    (setf (%array-fill-pointer array)
205                      (cond ((eq fill-pointer t)
206                             length)
207                            (t
208                             (unless (and (fixnump fill-pointer)
209                                          (>= fill-pointer 0)
210                                          (<= fill-pointer length))
211                               ;; FIXME: should be TYPE-ERROR?
212                               (error "invalid fill-pointer ~W"
213                                      fill-pointer))
214                             fill-pointer))))
215                  (setf (%array-fill-pointer-p array) t))
216                 (t
217                  (setf (%array-fill-pointer array) total-size)
218                  (setf (%array-fill-pointer-p array) nil)))
219           (setf (%array-available-elements array) total-size)
220           (setf (%array-data-vector array) data)
221           (setf (%array-displaced-from array) nil)
222           (cond (displaced-to
223                  (when (or initial-element-p initial-contents-p)
224                    (error "Neither :INITIAL-ELEMENT nor :INITIAL-CONTENTS ~
225                    can be specified along with :DISPLACED-TO"))
226                  (let ((offset (or displaced-index-offset 0)))
227                    (when (> (+ offset total-size)
228                             (array-total-size displaced-to))
229                      (error "~S doesn't have enough elements." displaced-to))
230                    (setf (%array-displacement array) offset)
231                    (setf (%array-displaced-p array) t)
232                    (%save-displaced-array-backpointer array data)))
233                 (t
234                  (setf (%array-displaced-p array) nil)))
235           (let ((axis 0))
236             (dolist (dim dimensions)
237               (setf (%array-dimension array axis) dim)
238               (incf axis)))
239           array))))
240
241 (defun make-static-vector (length &key
242                            (element-type '(unsigned-byte 8))
243                            (initial-contents nil initial-contents-p)
244                            (initial-element nil initial-element-p))
245   "Allocate vector of LENGTH elements in static space. Only allocation
246 of specialized arrays is supported."
247   ;; STEP 1: check inputs fully
248   ;;
249   ;; This way of doing explicit checks before the vector is allocated
250   ;; is expensive, but probably worth the trouble as once we've allocated
251   ;; the vector we have no way to get rid of it anymore...
252   (when (eq t (upgraded-array-element-type element-type))
253     (error "Static arrays of type ~S not supported."
254            element-type))
255   (when initial-contents-p
256     (when initial-element-p
257       (error "can't specify both :INITIAL-ELEMENT and :INITIAL-CONTENTS"))
258     (unless (= length (length initial-contents))
259       (error "There are ~W elements in the :INITIAL-CONTENTS, but the ~
260               vector length is ~W."
261              (length initial-contents)
262              length))
263     (unless (every (lambda (x) (typep x element-type)) initial-contents)
264       (error ":INITIAL-CONTENTS contains elements not of type ~S."
265              element-type)))
266   (when initial-element-p
267     (unless (typep initial-element element-type)
268       (error ":INITIAL-ELEMENT ~S is not of type ~S."
269              initial-element element-type)))
270   ;; STEP 2
271   ;;
272   ;; Allocate and possibly initialize the vector.
273   (multiple-value-bind (type n-bits)
274       (sb!impl::%vector-widetag-and-n-bits element-type)
275     (let ((vector
276            (allocate-static-vector type length
277                                    (ceiling (* length n-bits)
278                                             sb!vm:n-word-bits))))
279       (cond (initial-element-p
280              (fill vector initial-element))
281             (initial-contents-p
282              (replace vector initial-contents))
283             (t
284              vector)))))
285
286 ;;; DATA-VECTOR-FROM-INITS returns a simple vector that has the
287 ;;; specified array characteristics. Dimensions is only used to pass
288 ;;; to FILL-DATA-VECTOR for error checking on the structure of
289 ;;; initial-contents.
290 (defun data-vector-from-inits (dimensions total-size element-type
291                                initial-contents initial-contents-p
292                                initial-element initial-element-p)
293   (when (and initial-contents-p initial-element-p)
294     (error "cannot supply both :INITIAL-CONTENTS and :INITIAL-ELEMENT to
295             either MAKE-ARRAY or ADJUST-ARRAY."))
296   (let ((data (if initial-element-p
297                   (make-array total-size
298                               :element-type element-type
299                               :initial-element initial-element)
300                   (make-array total-size
301                               :element-type element-type))))
302     (cond (initial-element-p
303            (unless (simple-vector-p data)
304              (unless (typep initial-element element-type)
305                (error "~S cannot be used to initialize an array of type ~S."
306                       initial-element element-type))
307              (fill (the vector data) initial-element)))
308           (initial-contents-p
309            (fill-data-vector data dimensions initial-contents)))
310     data))
311
312 (defun vector (&rest objects)
313   #!+sb-doc
314   "Construct a SIMPLE-VECTOR from the given objects."
315   (coerce (the list objects) 'simple-vector))
316 \f
317
318 ;;;; accessor/setter functions
319
320 ;;; Dispatch to an optimized routine the data vector accessors for
321 ;;; each different specialized vector type. Do dispatching by looking
322 ;;; up the widetag in the array rather than with the typecases, which
323 ;;; as of 1.0.5 compiles to a naive sequence of linear TYPEPs. Also
324 ;;; provide separate versions where bounds checking has been moved
325 ;;; from the callee to the caller, since it's much cheaper to do once
326 ;;; the type information is available. Finally, for each of these
327 ;;; routines also provide a slow path, taken for arrays that are not
328 ;;; vectors or not simple.
329 (macrolet ((def (name table-name)
330              `(progn
331                 (defglobal ,table-name (make-array ,(1+ sb!vm:widetag-mask)))
332                 (defmacro ,name (array-var)
333                   `(the function
334                      (let ((tag 0))
335                        (when (sb!vm::%other-pointer-p ,array-var)
336                          (setf tag (%other-pointer-widetag ,array-var)))
337                        (svref ,',table-name tag)))))))
338   (def !find-data-vector-setter %%data-vector-setters%%)
339   (def !find-data-vector-setter/check-bounds %%data-vector-setters/check-bounds%%)
340   (def !find-data-vector-reffer %%data-vector-reffers%%)
341   (def !find-data-vector-reffer/check-bounds %%data-vector-reffers/check-bounds%%))
342
343 (macrolet ((%ref (accessor-getter extra-params)
344              `(funcall (,accessor-getter array) array index ,@extra-params))
345            (define (accessor-name slow-accessor-name accessor-getter
346                                   extra-params check-bounds)
347              `(progn
348                 (defun ,accessor-name (array index ,@extra-params)
349                   (declare (optimize speed
350                                      ;; (SAFETY 0) is ok. All calls to
351                                      ;; these functions are generated by
352                                      ;; the compiler, so argument count
353                                      ;; checking isn't needed. Type checking
354                                      ;; is done implicitly via the widetag
355                                      ;; dispatch.
356                                      (safety 0)))
357                   (%ref ,accessor-getter ,extra-params))
358                 (defun ,slow-accessor-name (array index ,@extra-params)
359                   (declare (optimize speed (safety 0)))
360                   (if (not (%array-displaced-p array))
361                       ;; The reasonably quick path of non-displaced complex
362                       ;; arrays.
363                       (let ((array (%array-data-vector array)))
364                         (%ref ,accessor-getter ,extra-params))
365                       ;; The real slow path.
366                       (with-array-data
367                           ((vector array)
368                            (index (locally
369                                       (declare (optimize (speed 1) (safety 1)))
370                                     (,@check-bounds index)))
371                            (end)
372                            :force-inline t)
373                         (declare (ignore end))
374                         (,accessor-name vector index ,@extra-params)))))))
375   (define hairy-data-vector-ref slow-hairy-data-vector-ref
376     !find-data-vector-reffer
377     nil (progn))
378   (define hairy-data-vector-set slow-hairy-data-vector-set
379     !find-data-vector-setter
380     (new-value) (progn))
381   (define hairy-data-vector-ref/check-bounds
382       slow-hairy-data-vector-ref/check-bounds
383     !find-data-vector-reffer/check-bounds
384     nil (%check-bound array (array-dimension array 0)))
385   (define hairy-data-vector-set/check-bounds
386       slow-hairy-data-vector-set/check-bounds
387     !find-data-vector-setter/check-bounds
388     (new-value) (%check-bound array (array-dimension array 0))))
389
390 (defun hairy-ref-error (array index &optional new-value)
391   (declare (ignore index new-value))
392   (error 'type-error
393          :datum array
394          :expected-type 'vector))
395
396 ;;; Populate the dispatch tables.
397 (macrolet ((define-reffer (saetp check-form)
398              (let* ((type (sb!vm:saetp-specifier saetp))
399                     (atype `(simple-array ,type (*))))
400                `(named-lambda optimized-data-vector-ref (vector index)
401                   (declare (optimize speed (safety 0)))
402                   (data-vector-ref (the ,atype vector)
403                                    (locally
404                                        (declare (optimize (safety 1)))
405                                      (the index
406                                        (,@check-form index)))))))
407            (define-setter (saetp check-form)
408              (let* ((type (sb!vm:saetp-specifier saetp))
409                     (atype `(simple-array ,type (*))))
410                `(named-lambda optimized-data-vector-set (vector index new-value)
411                   (declare (optimize speed (safety 0)))
412                   (data-vector-set (the ,atype vector)
413                                    (locally
414                                        (declare (optimize (safety 1)))
415                                      (the index
416                                        (,@check-form index)))
417                                    (locally
418                                        ;; SPEED 1 needed to avoid the compiler
419                                        ;; from downgrading the type check to
420                                        ;; a cheaper one.
421                                        (declare (optimize (speed 1)
422                                                           (safety 1)))
423                                      (the ,type new-value)))
424                   ;; For specialized arrays, the return from
425                   ;; data-vector-set would have to be reboxed to be a
426                   ;; (Lisp) return value; instead, we use the
427                   ;; already-boxed value as the return.
428                   new-value)))
429            (define-reffers (symbol deffer check-form slow-path)
430              `(progn
431                 ;; FIXME/KLUDGE: can't just FILL here, because genesis doesn't
432                 ;; preserve the binding, so re-initiaize as NS doesn't have
433                 ;; the energy to figure out to change that right now.
434                 (setf ,symbol (make-array (1+ sb!vm::widetag-mask)
435                                           :initial-element #'hairy-ref-error))
436                 ,@(loop for widetag in '(sb!vm:complex-vector-widetag
437                                          sb!vm:complex-vector-nil-widetag
438                                          sb!vm:complex-bit-vector-widetag
439                                          #!+sb-unicode sb!vm:complex-character-string-widetag
440                                          sb!vm:complex-base-string-widetag
441                                          sb!vm:simple-array-widetag
442                                          sb!vm:complex-array-widetag)
443                         collect `(setf (svref ,symbol ,widetag) ,slow-path))
444                 ,@(loop for saetp across sb!vm:*specialized-array-element-type-properties*
445                         for widetag = (sb!vm:saetp-typecode saetp)
446                         collect `(setf (svref ,symbol ,widetag)
447                                        (,deffer ,saetp ,check-form))))))
448   (defun !hairy-data-vector-reffer-init ()
449     (define-reffers %%data-vector-reffers%% define-reffer
450       (progn)
451       #'slow-hairy-data-vector-ref)
452     (define-reffers %%data-vector-setters%% define-setter
453       (progn)
454       #'slow-hairy-data-vector-set)
455     (define-reffers %%data-vector-reffers/check-bounds%% define-reffer
456       (%check-bound vector (length vector))
457       #'slow-hairy-data-vector-ref/check-bounds)
458     (define-reffers %%data-vector-setters/check-bounds%% define-setter
459       (%check-bound vector (length vector))
460       #'slow-hairy-data-vector-set/check-bounds)))
461
462 ;;; (Ordinary DATA-VECTOR-REF usage compiles into a vop, but
463 ;;; DATA-VECTOR-REF is also FOLDABLE, and this ordinary function
464 ;;; definition is needed for the compiler to use in constant folding.)
465 (defun data-vector-ref (array index)
466   (hairy-data-vector-ref array index))
467
468 (defun data-vector-ref-with-offset (array index offset)
469   (hairy-data-vector-ref array (+ index offset)))
470
471 (defun invalid-array-p (array)
472   (and (array-header-p array)
473        (consp (%array-displaced-p array))))
474
475 (declaim (ftype (function (array) nil) invalid-array-error))
476 (defun invalid-array-error (array)
477   (aver (array-header-p array))
478   ;; Array invalidation stashes the original dimensions here...
479   (let ((dims (%array-displaced-p array))
480         (et (array-element-type array)))
481     (error 'invalid-array-error
482            :datum array
483            :expected-type
484            (if (cdr dims)
485                `(array ,et ,dims)
486                `(vector ,et ,@dims)))))
487
488 (declaim (ftype (function (array integer integer &optional t) nil)
489                 invalid-array-index-error))
490 (defun invalid-array-index-error (array index bound &optional axis)
491   (if (invalid-array-p array)
492       (invalid-array-error array)
493       (error 'invalid-array-index-error
494              :array array
495              :axis axis
496              :datum index
497              :expected-type `(integer 0 (,bound)))))
498
499 ;;; SUBSCRIPTS has a dynamic-extent list structure and is destroyed
500 (defun %array-row-major-index (array subscripts
501                                      &optional (invalid-index-error-p t))
502   (declare (array array)
503            (list subscripts))
504   (let ((rank (array-rank array)))
505     (unless (= rank (length subscripts))
506       (error "wrong number of subscripts, ~W, for array of rank ~W"
507              (length subscripts) rank))
508     (if (array-header-p array)
509         (do ((subs (nreverse subscripts) (cdr subs))
510              (axis (1- (array-rank array)) (1- axis))
511              (chunk-size 1)
512              (result 0))
513             ((null subs) result)
514           (declare (list subs) (fixnum axis chunk-size result))
515           (let ((index (car subs))
516                 (dim (%array-dimension array axis)))
517             (declare (fixnum dim))
518             (unless (and (fixnump index) (< -1 index dim))
519               (if invalid-index-error-p
520                   (invalid-array-index-error array index dim axis)
521                   (return-from %array-row-major-index nil)))
522             (incf result (* chunk-size (the fixnum index)))
523             (setf chunk-size (* chunk-size dim))))
524         (let ((index (first subscripts))
525               (length (length (the (simple-array * (*)) array))))
526           (unless (and (fixnump index) (< -1 index length))
527             (if invalid-index-error-p
528                 (invalid-array-index-error array index length)
529                 (return-from %array-row-major-index nil)))
530           index))))
531
532 (defun array-in-bounds-p (array &rest subscripts)
533   #!+sb-doc
534   "Return T if the SUBSCRIPTS are in bounds for the ARRAY, NIL otherwise."
535   (if (%array-row-major-index array subscripts nil)
536       t))
537
538 (defun array-row-major-index (array &rest subscripts)
539   (declare (truly-dynamic-extent subscripts))
540   (%array-row-major-index array subscripts))
541
542 (defun aref (array &rest subscripts)
543   #!+sb-doc
544   "Return the element of the ARRAY specified by the SUBSCRIPTS."
545   (declare (truly-dynamic-extent subscripts))
546   (row-major-aref array (%array-row-major-index array subscripts)))
547
548 (defun %aset (array &rest stuff)
549   (declare (truly-dynamic-extent stuff))
550   (let ((subscripts (butlast stuff))
551         (new-value (car (last stuff))))
552     (setf (row-major-aref array (%array-row-major-index array subscripts))
553           new-value)))
554
555 ;;; FIXME: What's supposed to happen with functions
556 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
557 ;;; DEFSETF FOO is also defined? It seems as though the logical
558 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
559 ;;; and replace it with the (SETF FOO) function, issuing a warning,
560 ;;; just as for ordinary functions
561 ;;;  * (LISP-IMPLEMENTATION-VERSION)
562 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
563 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
564 ;;;  ZOO
565 ;;;  * (DEFUN ZOO (X) (* 3 X))
566 ;;;  Warning: ZOO previously defined as a macro.
567 ;;;  ZOO
568 ;;; But that doesn't seem to be what happens in CMU CL.
569 ;;;
570 ;;; KLUDGE: this is probably because ANSI, in its wisdom (CLHS
571 ;;; 5.1.2.5) requires implementations to support
572 ;;;   (SETF (APPLY #'AREF ...) ...)
573 ;;; [and also #'BIT and #'SBIT].  Yes, this is terrifying, and it's
574 ;;; also terrifying that this sequence of definitions causes it to
575 ;;; work.
576 ;;;
577 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
578 ;;; has a setf expansion and/or a setf function defined.
579
580 #!-sb-fluid (declaim (inline (setf aref)))
581 (defun (setf aref) (new-value array &rest subscripts)
582   (declare (truly-dynamic-extent subscripts))
583   (declare (type array array))
584   (setf (row-major-aref array (%array-row-major-index array subscripts))
585         new-value))
586
587 (defun row-major-aref (array index)
588   #!+sb-doc
589   "Return the element of array corressponding to the row-major index. This is
590    SETF'able."
591   (declare (optimize (safety 1)))
592   (row-major-aref array index))
593
594 (defun %set-row-major-aref (array index new-value)
595   (declare (optimize (safety 1)))
596   (setf (row-major-aref array index) new-value))
597
598 (defun svref (simple-vector index)
599   #!+sb-doc
600   "Return the INDEX'th element of the given Simple-Vector."
601   (declare (optimize (safety 1)))
602   (aref simple-vector index))
603
604 (defun %svset (simple-vector index new)
605   (declare (optimize (safety 1)))
606   (setf (aref simple-vector index) new))
607
608 (defun bit (bit-array &rest subscripts)
609   #!+sb-doc
610   "Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
611   (declare (type (array bit) bit-array) (optimize (safety 1)))
612   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
613
614 (defun %bitset (bit-array &rest stuff)
615   (declare (type (array bit) bit-array) (optimize (safety 1)))
616   (let ((subscripts (butlast stuff))
617         (new-value (car (last stuff))))
618     (setf (row-major-aref bit-array
619                           (%array-row-major-index bit-array subscripts))
620           new-value)))
621
622 #!-sb-fluid (declaim (inline (setf bit)))
623 (defun (setf bit) (new-value bit-array &rest subscripts)
624   (declare (type (array bit) bit-array) (optimize (safety 1)))
625   (setf (row-major-aref bit-array
626                         (%array-row-major-index bit-array subscripts))
627         new-value))
628
629 (defun sbit (simple-bit-array &rest subscripts)
630   #!+sb-doc
631   "Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
632   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
633   (row-major-aref simple-bit-array
634                   (%array-row-major-index simple-bit-array subscripts)))
635
636 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
637 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
638 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
639 ;;; -- WHN 19990911
640 (defun %sbitset (simple-bit-array &rest stuff)
641   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
642   (let ((subscripts (butlast stuff))
643         (new-value (car (last stuff))))
644     (setf (row-major-aref simple-bit-array
645                           (%array-row-major-index simple-bit-array subscripts))
646           new-value)))
647
648 #!-sb-fluid (declaim (inline (setf sbit)))
649 (defun (setf sbit) (new-value bit-array &rest subscripts)
650   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
651   (setf (row-major-aref bit-array
652                         (%array-row-major-index bit-array subscripts))
653         new-value))
654 \f
655 ;;;; miscellaneous array properties
656
657 (defun array-element-type (array)
658   #!+sb-doc
659   "Return the type of the elements of the array"
660   (let ((widetag (widetag-of array)))
661     (macrolet ((pick-element-type (&rest stuff)
662                  `(cond ,@(mapcar (lambda (stuff)
663                                     (cons
664                                      (let ((item (car stuff)))
665                                        (cond ((eq item t)
666                                               t)
667                                              ((listp item)
668                                               (cons 'or
669                                                     (mapcar (lambda (x)
670                                                               `(= widetag ,x))
671                                                             item)))
672                                              (t
673                                               `(= widetag ,item))))
674                                      (cdr stuff)))
675                                   stuff))))
676       #.`(pick-element-type
677           ,@(map 'list
678                  (lambda (saetp)
679                    `(,(if (sb!vm:saetp-complex-typecode saetp)
680                           (list (sb!vm:saetp-typecode saetp)
681                                 (sb!vm:saetp-complex-typecode saetp))
682                           (sb!vm:saetp-typecode saetp))
683                      ',(sb!vm:saetp-specifier saetp)))
684                  sb!vm:*specialized-array-element-type-properties*)
685           ((sb!vm:simple-array-widetag
686             sb!vm:complex-vector-widetag
687             sb!vm:complex-array-widetag)
688            (with-array-data ((array array) (start) (end))
689              (declare (ignore start end))
690              (array-element-type array)))
691           (t
692            (error 'type-error :datum array :expected-type 'array))))))
693
694 (defun array-rank (array)
695   #!+sb-doc
696   "Return the number of dimensions of ARRAY."
697   (if (array-header-p array)
698       (%array-rank array)
699       1))
700
701 (defun array-dimension (array axis-number)
702   #!+sb-doc
703   "Return the length of dimension AXIS-NUMBER of ARRAY."
704   (declare (array array) (type index axis-number))
705   (cond ((not (array-header-p array))
706          (unless (= axis-number 0)
707            (error "Vector axis is not zero: ~S" axis-number))
708          (length (the (simple-array * (*)) array)))
709         ((>= axis-number (%array-rank array))
710          (error "Axis number ~W is too big; ~S only has ~D dimension~:P."
711                 axis-number array (%array-rank array)))
712         (t
713          (%array-dimension array axis-number))))
714
715 (defun array-dimensions (array)
716   #!+sb-doc
717   "Return a list whose elements are the dimensions of the array"
718   (declare (array array))
719   (if (array-header-p array)
720       (do ((results nil (cons (array-dimension array index) results))
721            (index (1- (array-rank array)) (1- index)))
722           ((minusp index) results))
723       (list (array-dimension array 0))))
724
725 (defun array-total-size (array)
726   #!+sb-doc
727   "Return the total number of elements in the Array."
728   (declare (array array))
729   (if (array-header-p array)
730       (%array-available-elements array)
731       (length (the vector array))))
732
733 (defun array-displacement (array)
734   #!+sb-doc
735   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
736    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
737   (declare (type array array))
738   (if (and (array-header-p array) ; if unsimple and
739            (%array-displaced-p array)) ; displaced
740       (values (%array-data-vector array) (%array-displacement array))
741       (values nil 0)))
742
743 (defun adjustable-array-p (array)
744   #!+sb-doc
745   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
746    to the argument, this happens for complex arrays."
747   (declare (array array))
748   ;; Note that this appears not to be a fundamental limitation.
749   ;; non-vector SIMPLE-ARRAYs are in fact capable of being adjusted,
750   ;; but in practice we test using ADJUSTABLE-ARRAY-P in ADJUST-ARRAY.
751   ;; -- CSR, 2004-03-01.
752   (not (typep array 'simple-array)))
753 \f
754 ;;;; fill pointer frobbing stuff
755
756 (defun array-has-fill-pointer-p (array)
757   #!+sb-doc
758   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
759   (declare (array array))
760   (and (array-header-p array) (%array-fill-pointer-p array)))
761
762 (defun fill-pointer-error (vector arg)
763   (cond (arg
764          (aver (array-has-fill-pointer-p vector))
765          (let ((max (%array-available-elements vector)))
766            (error 'simple-type-error
767                   :datum arg
768                   :expected-type (list 'integer 0 max)
769                   :format-control "The new fill pointer, ~S, is larger than the length of the vector (~S.)"
770                   :format-arguments (list arg max))))
771         (t
772          (error 'simple-type-error
773                 :datum vector
774                 :expected-type '(and vector (satisfies array-has-fill-pointer-p))
775                 :format-control "~S is not an array with a fill pointer."
776                 :format-arguments (list vector)))))
777
778 (defun fill-pointer (vector)
779   #!+sb-doc
780   "Return the FILL-POINTER of the given VECTOR."
781   (if (array-has-fill-pointer-p vector)
782       (%array-fill-pointer vector)
783       (fill-pointer-error vector nil)))
784
785 (defun %set-fill-pointer (vector new)
786   (flet ((oops (x)
787            (fill-pointer-error vector x)))
788     (if (array-has-fill-pointer-p vector)
789         (if (> new (%array-available-elements vector))
790             (oops new)
791             (setf (%array-fill-pointer vector) new))
792         (oops nil))))
793
794 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
795 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
796 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
797 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
798 ;;; back to CMU CL).
799 (defun vector-push (new-el array)
800   #!+sb-doc
801   "Attempt to set the element of ARRAY designated by its fill pointer
802    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
803    too large, NIL is returned, otherwise the index of the pushed element is
804    returned."
805   (declare (vector array))
806   (let ((fill-pointer (fill-pointer array)))
807     (declare (fixnum fill-pointer))
808     (cond ((= fill-pointer (%array-available-elements array))
809            nil)
810           (t
811            (locally (declare (optimize (safety 0)))
812              (setf (aref array fill-pointer) new-el))
813            (setf (%array-fill-pointer array) (1+ fill-pointer))
814            fill-pointer))))
815
816 (defun vector-push-extend (new-element
817                            vector
818                            &optional
819                            (min-extension
820                             (let ((length (length vector)))
821                               (min (1+ length)
822                                    (- array-dimension-limit length)))))
823   (declare (vector vector) (fixnum min-extension))
824   (let ((fill-pointer (fill-pointer vector)))
825     (declare (fixnum fill-pointer))
826     (when (= fill-pointer (%array-available-elements vector))
827       (adjust-array vector (+ fill-pointer (max 1 min-extension))))
828     ;; disable bounds checking
829     (locally (declare (optimize (safety 0)))
830       (setf (aref vector fill-pointer) new-element))
831     (setf (%array-fill-pointer vector) (1+ fill-pointer))
832     fill-pointer))
833
834 (defun vector-pop (array)
835   #!+sb-doc
836   "Decrease the fill pointer by 1 and return the element pointed to by the
837   new fill pointer."
838   (declare (vector array))
839   (let ((fill-pointer (fill-pointer array)))
840     (declare (fixnum fill-pointer))
841     (if (zerop fill-pointer)
842         (error "There is nothing left to pop.")
843         ;; disable bounds checking (and any fixnum test)
844         (locally (declare (optimize (safety 0)))
845           (aref array
846                 (setf (%array-fill-pointer array)
847                       (1- fill-pointer)))))))
848
849 \f
850 ;;;; ADJUST-ARRAY
851
852 (defun adjust-array (array dimensions &key
853                            (element-type (array-element-type array))
854                            (initial-element nil initial-element-p)
855                            (initial-contents nil initial-contents-p)
856                            fill-pointer
857                            displaced-to displaced-index-offset)
858   #!+sb-doc
859   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
860   (when (invalid-array-p array)
861     (invalid-array-error array))
862   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
863     (cond ((/= (the fixnum (length (the list dimensions)))
864                (the fixnum (array-rank array)))
865            (error "The number of dimensions not equal to rank of array."))
866           ((not (subtypep element-type (array-element-type array)))
867            (error "The new element type, ~S, is incompatible with old type."
868                   element-type))
869           ((and fill-pointer (not (array-has-fill-pointer-p array)))
870            (error 'type-error
871                   :datum array
872                   :expected-type '(satisfies array-has-fill-pointer-p))))
873     (let ((array-rank (length (the list dimensions))))
874       (declare (fixnum array-rank))
875       (unless (= array-rank 1)
876         (when fill-pointer
877           (error "Only vectors can have fill pointers.")))
878       (cond (initial-contents-p
879              ;; array former contents replaced by INITIAL-CONTENTS
880              (if (or initial-element-p displaced-to)
881                  (error "INITIAL-CONTENTS may not be specified with ~
882                          the :INITIAL-ELEMENT or :DISPLACED-TO option."))
883              (let* ((array-size (apply #'* dimensions))
884                     (array-data (data-vector-from-inits
885                                  dimensions array-size element-type
886                                  initial-contents initial-contents-p
887                                  initial-element initial-element-p)))
888                (if (adjustable-array-p array)
889                    (set-array-header array array-data array-size
890                                  (get-new-fill-pointer array array-size
891                                                        fill-pointer)
892                                  0 dimensions nil nil)
893                    (if (array-header-p array)
894                        ;; simple multidimensional or single dimensional array
895                        (make-array dimensions
896                                    :element-type element-type
897                                    :initial-contents initial-contents)
898                        array-data))))
899             (displaced-to
900              ;; We already established that no INITIAL-CONTENTS was supplied.
901              (when initial-element
902                (error "The :INITIAL-ELEMENT option may not be specified ~
903                        with :DISPLACED-TO."))
904              (unless (subtypep element-type (array-element-type displaced-to))
905                (error "can't displace an array of type ~S into another of ~
906                        type ~S"
907                       element-type (array-element-type displaced-to)))
908              (let ((displacement (or displaced-index-offset 0))
909                    (array-size (apply #'* dimensions)))
910                (declare (fixnum displacement array-size))
911                (if (< (the fixnum (array-total-size displaced-to))
912                       (the fixnum (+ displacement array-size)))
913                    (error "The :DISPLACED-TO array is too small."))
914                (if (adjustable-array-p array)
915                    ;; None of the original contents appear in adjusted array.
916                    (set-array-header array displaced-to array-size
917                                      (get-new-fill-pointer array array-size
918                                                            fill-pointer)
919                                      displacement dimensions t nil)
920                    ;; simple multidimensional or single dimensional array
921                    (make-array dimensions
922                                :element-type element-type
923                                :displaced-to displaced-to
924                                :displaced-index-offset
925                                displaced-index-offset))))
926             ((= array-rank 1)
927              (let ((old-length (array-total-size array))
928                    (new-length (car dimensions))
929                    new-data)
930                (declare (fixnum old-length new-length))
931                (with-array-data ((old-data array) (old-start)
932                                  (old-end old-length))
933                  (cond ((or (and (array-header-p array)
934                                  (%array-displaced-p array))
935                             (< old-length new-length))
936                         (setf new-data
937                               (data-vector-from-inits
938                                dimensions new-length element-type
939                                initial-contents initial-contents-p
940                                initial-element initial-element-p))
941                         (replace new-data old-data
942                                  :start2 old-start :end2 old-end))
943                        (t (setf new-data
944                                 (shrink-vector old-data new-length))))
945                  (if (adjustable-array-p array)
946                      (set-array-header array new-data new-length
947                                        (get-new-fill-pointer array new-length
948                                                              fill-pointer)
949                                        0 dimensions nil nil)
950                      new-data))))
951             (t
952              (let ((old-length (%array-available-elements array))
953                    (new-length (apply #'* dimensions)))
954                (declare (fixnum old-length new-length))
955                (with-array-data ((old-data array) (old-start)
956                                  (old-end old-length))
957                  (declare (ignore old-end))
958                  (let ((new-data (if (or (and (array-header-p array)
959                                               (%array-displaced-p array))
960                                          (> new-length old-length))
961                                      (data-vector-from-inits
962                                       dimensions new-length
963                                       element-type () nil
964                                       initial-element initial-element-p)
965                                      old-data)))
966                    (if (or (zerop old-length) (zerop new-length))
967                        (when initial-element-p (fill new-data initial-element))
968                        (zap-array-data old-data (array-dimensions array)
969                                        old-start
970                                        new-data dimensions new-length
971                                        element-type initial-element
972                                        initial-element-p))
973                    (if (adjustable-array-p array)
974                        (set-array-header array new-data new-length
975                                          nil 0 dimensions nil nil)
976                        (let ((new-array
977                               (make-array-header
978                                sb!vm:simple-array-widetag array-rank)))
979                          (set-array-header new-array new-data new-length
980                                            nil 0 dimensions nil t)))))))))))
981
982
983 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
984   (cond ((not fill-pointer)
985          (when (array-has-fill-pointer-p old-array)
986            (when (> (%array-fill-pointer old-array) new-array-size)
987              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
988                      smaller than its fill pointer (~S)"
989                     old-array new-array-size (fill-pointer old-array)))
990            (%array-fill-pointer old-array)))
991         ((not (array-has-fill-pointer-p old-array))
992          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
993                  in ADJUST-ARRAY unless the array (~S) was originally ~
994                  created with a fill pointer"
995                 fill-pointer
996                 old-array))
997         ((numberp fill-pointer)
998          (when (> fill-pointer new-array-size)
999            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
1000                    than the new length of the vector (~S)"
1001                   fill-pointer new-array-size))
1002          fill-pointer)
1003         ((eq fill-pointer t)
1004          new-array-size)
1005         (t
1006          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
1007                 fill-pointer))))
1008
1009 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
1010 ;;; which must be less than or equal to its current length. This can
1011 ;;; be called on vectors without a fill pointer but it is extremely
1012 ;;; dangerous to do so: shrinking the size of an object (as viewed by
1013 ;;; the gc) makes bounds checking unreliable in the face of interrupts
1014 ;;; or multi-threading. Call it only on provably local vectors.
1015 (defun %shrink-vector (vector new-length)
1016   (declare (vector vector))
1017   (unless (array-header-p vector)
1018     (macrolet ((frob (name &rest things)
1019                  `(etypecase ,name
1020                     ((simple-array nil (*)) (error 'nil-array-accessed-error))
1021                     ,@(mapcar (lambda (thing)
1022                                 (destructuring-bind (type-spec fill-value)
1023                                     thing
1024                                   `(,type-spec
1025                                     (fill (truly-the ,type-spec ,name)
1026                                           ,fill-value
1027                                           :start new-length))))
1028                               things))))
1029       ;; Set the 'tail' of the vector to the appropriate type of zero,
1030       ;; "because in some cases we'll scavenge larger areas in one go,
1031       ;; like groups of pages that had triggered the write barrier, or
1032       ;; the whole static space" according to jsnell.
1033       #.`(frob vector
1034           ,@(map 'list
1035                  (lambda (saetp)
1036                    `((simple-array ,(sb!vm:saetp-specifier saetp) (*))
1037                      ,(if (or (eq (sb!vm:saetp-specifier saetp) 'character)
1038                               #!+sb-unicode
1039                               (eq (sb!vm:saetp-specifier saetp) 'base-char))
1040                           *default-init-char-form*
1041                           (sb!vm:saetp-initial-element-default saetp))))
1042                  (remove-if-not
1043                   #'sb!vm:saetp-specifier
1044                   sb!vm:*specialized-array-element-type-properties*)))))
1045   ;; Only arrays have fill-pointers, but vectors have their length
1046   ;; parameter in the same place.
1047   (setf (%array-fill-pointer vector) new-length)
1048   vector)
1049
1050 (defun shrink-vector (vector new-length)
1051   (declare (vector vector))
1052   (cond
1053     ((eq (length vector) new-length)
1054      vector)
1055     ((array-has-fill-pointer-p vector)
1056      (setf (%array-fill-pointer vector) new-length)
1057      vector)
1058     (t (subseq vector 0 new-length))))
1059
1060 ;;; BIG THREAD SAFETY NOTE
1061 ;;;
1062 ;;; ADJUST-ARRAY/SET-ARRAY-HEADER, and its callees are very
1063 ;;; thread unsafe. They are nonatomic, and can mess with parallel
1064 ;;; code using the same arrays.
1065 ;;;
1066 ;;; A likely seeming fix is an additional level of indirection:
1067 ;;; ARRAY-HEADER -> ARRAY-INFO -> ... where ARRAY-HEADER would
1068 ;;; hold nothing but the pointer to ARRAY-INFO, and ARRAY-INFO
1069 ;;; would hold everything ARRAY-HEADER now holds. This allows
1070 ;;; consing up a new ARRAY-INFO and replacing it atomically in
1071 ;;; the ARRAY-HEADER.
1072 ;;;
1073 ;;; %WALK-DISPLACED-ARRAY-BACKPOINTERS is an especially nasty
1074 ;;; one: not only is it needed extremely rarely, which makes
1075 ;;; any thread safety bugs involving it look like rare random
1076 ;;; corruption, but because it walks the chain *upwards*, which
1077 ;;; may violate user expectations.
1078
1079 (defun %save-displaced-array-backpointer (array data)
1080   (flet ((purge (pointers)
1081            (remove-if (lambda (value)
1082                         (or (not value) (eq array value)))
1083                       pointers
1084                       :key #'weak-pointer-value)))
1085     ;; Add backpointer to the new data vector if it has a header.
1086     (when (array-header-p data)
1087       (setf (%array-displaced-from data)
1088             (cons (make-weak-pointer array)
1089                   (purge (%array-displaced-from data)))))
1090     ;; Remove old backpointer, if any.
1091     (let ((old-data (%array-data-vector array)))
1092       (when (and (neq data old-data) (array-header-p old-data))
1093         (setf (%array-displaced-from old-data)
1094               (purge (%array-displaced-from old-data)))))))
1095
1096 (defun %walk-displaced-array-backpointers (array new-length)
1097   (dolist (p (%array-displaced-from array))
1098     (let ((from (weak-pointer-value p)))
1099       (when (and from (eq array (%array-data-vector from)))
1100         (let ((requires (+ (%array-available-elements from)
1101                            (%array-displacement from))))
1102           (unless (>= new-length requires)
1103             ;; ANSI sayeth (ADJUST-ARRAY dictionary entry):
1104             ;;
1105             ;;   "If A is displaced to B, the consequences are unspecified if B is
1106             ;;   adjusted in such a way that it no longer has enough elements to
1107             ;;   satisfy A.
1108             ;;
1109             ;; since we're hanging on a weak pointer here, we can't signal an
1110             ;; error right now: the array that we're looking at might be
1111             ;; garbage. Instead, we set all dimensions to zero so that next
1112             ;; safe access to the displaced array will trap. Additionally, we
1113             ;; save the original dimensions, so we can signal a more
1114             ;; understandable error when the time comes.
1115             (%walk-displaced-array-backpointers from 0)
1116             (setf (%array-fill-pointer from) 0
1117                   (%array-available-elements from) 0
1118                   (%array-displaced-p from) (array-dimensions array))
1119             (dotimes (i (%array-rank from))
1120               (setf (%array-dimension from i) 0))))))))
1121
1122 ;;; Fill in array header with the provided information, and return the array.
1123 (defun set-array-header (array data length fill-pointer displacement dimensions
1124                          displacedp newp)
1125   (if newp
1126       (setf (%array-displaced-from array) nil)
1127       (%walk-displaced-array-backpointers array length))
1128   (when displacedp
1129     (%save-displaced-array-backpointer array data))
1130   (setf (%array-data-vector array) data)
1131   (setf (%array-available-elements array) length)
1132   (cond (fill-pointer
1133          (setf (%array-fill-pointer array) fill-pointer)
1134          (setf (%array-fill-pointer-p array) t))
1135         (t
1136          (setf (%array-fill-pointer array) length)
1137          (setf (%array-fill-pointer-p array) nil)))
1138   (setf (%array-displacement array) displacement)
1139   (if (listp dimensions)
1140       (dotimes (axis (array-rank array))
1141         (declare (type index axis))
1142         (setf (%array-dimension array axis) (pop dimensions)))
1143       (setf (%array-dimension array 0) dimensions))
1144   (setf (%array-displaced-p array) displacedp)
1145   array)
1146
1147 ;;; User visible extension
1148 (declaim (ftype (function (array) (values (simple-array * (*)) &optional))
1149                 array-storage-vector))
1150 (defun array-storage-vector (array)
1151   "Returns the underlying storage vector of ARRAY, which must be a non-displaced array.
1152
1153 In SBCL, if ARRAY is a of type \(SIMPLE-ARRAY * \(*)), it is its own storage
1154 vector. Multidimensional arrays, arrays with fill pointers, and adjustable
1155 arrays have an underlying storage vector with the same ARRAY-ELEMENT-TYPE as
1156 ARRAY, which this function returns.
1157
1158 Important note: the underlying vector is an implementation detail. Even though
1159 this function exposes it, changes in the implementation may cause this
1160 function to be removed without further warning."
1161   ;; KLUDGE: Without TRULY-THE the system is not smart enough to figure out that
1162   ;; the return value is always of the known type.
1163   (truly-the (simple-array * (*))
1164              (if (array-header-p array)
1165                  (if (%array-displaced-p array)
1166                      (error "~S cannot be used with displaced arrays. Use ~S instead."
1167                             'array-storage-vector 'array-displacement)
1168                      (%array-data-vector array))
1169                  array)))
1170 \f
1171 ;;;; used by SORT
1172
1173 ;;; temporary vector for stable sorting vectors, allocated for each new thread
1174 (defvar *merge-sort-temp-vector* (vector))
1175 (declaim (simple-vector *merge-sort-temp-vector*))
1176
1177 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
1178
1179 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
1180 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice. This is rebound
1181 ;;; to length zero array in each new thread.
1182 ;;;
1183 ;;; DX is probably a bad idea, because a with a big array it would
1184 ;;; be fairly easy to blow the stack.
1185 (defvar *zap-array-data-temp* (vector))
1186 (declaim (simple-vector *zap-array-data-temp*))
1187
1188 (defun zap-array-data-temp (length initial-element initial-element-p)
1189   (declare (fixnum length))
1190   (let ((tmp *zap-array-data-temp*))
1191     (declare (simple-vector tmp))
1192     (cond ((> length (length tmp))
1193            (setf *zap-array-data-temp*
1194                  (if initial-element-p
1195                      (make-array length :initial-element initial-element)
1196                      (make-array length))))
1197           (initial-element-p
1198            (fill tmp initial-element :end length))
1199           (t
1200            tmp))))
1201
1202 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
1203 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
1204 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
1205 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
1206 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
1207                        element-type initial-element initial-element-p)
1208   (declare (list old-dims new-dims))
1209   ;; OLD-DIMS comes from array-dimensions, which returns a fresh list
1210   ;; at least in SBCL.
1211   ;; NEW-DIMS comes from the user.
1212   (setf old-dims (nreverse old-dims)
1213         new-dims (reverse new-dims))
1214   (cond ((eq old-data new-data)
1215          ;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and
1216          ;; INITIAL-ELEMENT-P are used when OLD-DATA and NEW-DATA are
1217          ;; EQ; in this case, a temporary must be used and filled
1218          ;; appropriately. specified initial-element.
1219          (when initial-element-p
1220            ;; FIXME: transforming this TYPEP to someting a bit faster
1221            ;; would be a win...
1222            (unless (typep initial-element element-type)
1223              (error "~S can't be used to initialize an array of type ~S."
1224                     initial-element element-type)))
1225          (let ((temp (zap-array-data-temp new-length
1226                                           initial-element initial-element-p)))
1227            (declare (simple-vector temp))
1228            (zap-array-data-aux old-data old-dims offset temp new-dims)
1229            (dotimes (i new-length)
1230              (setf (aref new-data i) (aref temp i)
1231                    ;; zero out any garbage right away
1232                    (aref temp i) 0))))
1233         (t
1234          ;; When OLD-DATA and NEW-DATA are not EQ, NEW-DATA has
1235          ;; already been filled with any
1236          (zap-array-data-aux old-data old-dims offset new-data new-dims))))
1237
1238 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
1239   (declare (fixnum offset))
1240   (let ((limits (mapcar (lambda (x y)
1241                           (declare (fixnum x y))
1242                           (1- (the fixnum (min x y))))
1243                         old-dims new-dims)))
1244     (macrolet ((bump-index-list (index limits)
1245                  `(do ((subscripts ,index (cdr subscripts))
1246                        (limits ,limits (cdr limits)))
1247                       ((null subscripts) :eof)
1248                     (cond ((< (the fixnum (car subscripts))
1249                               (the fixnum (car limits)))
1250                            (rplaca subscripts
1251                                    (1+ (the fixnum (car subscripts))))
1252                            (return ,index))
1253                           (t (rplaca subscripts 0))))))
1254       (do ((index (make-list (length old-dims) :initial-element 0)
1255                   (bump-index-list index limits)))
1256           ((eq index :eof))
1257         (setf (aref new-data (row-major-index-from-dims index new-dims))
1258               (aref old-data
1259                     (+ (the fixnum (row-major-index-from-dims index old-dims))
1260                        offset)))))))
1261
1262 ;;; Figure out the row-major-order index of an array reference from a
1263 ;;; list of subscripts and a list of dimensions. This is for internal
1264 ;;; calls only, and the subscripts and dim-list variables are assumed
1265 ;;; to be reversed from what the user supplied.
1266 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
1267   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
1268        (rev-dim-list rev-dim-list (cdr rev-dim-list))
1269        (chunk-size 1)
1270        (result 0))
1271       ((null rev-dim-list) result)
1272     (declare (fixnum chunk-size result))
1273     (setq result (+ result
1274                     (the fixnum (* (the fixnum (car rev-subscripts))
1275                                    chunk-size))))
1276     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
1277 \f
1278 ;;;; some bit stuff
1279
1280 (defun bit-array-same-dimensions-p (array1 array2)
1281   (declare (type (array bit) array1 array2))
1282   (and (= (array-rank array1)
1283           (array-rank array2))
1284        (dotimes (index (array-rank array1) t)
1285          (when (/= (array-dimension array1 index)
1286                    (array-dimension array2 index))
1287            (return nil)))))
1288
1289 (defun pick-result-array (result-bit-array bit-array-1)
1290   (case result-bit-array
1291     ((t) bit-array-1)
1292     ((nil) (make-array (array-dimensions bit-array-1)
1293                        :element-type 'bit
1294                        :initial-element 0))
1295     (t
1296      (unless (bit-array-same-dimensions-p bit-array-1
1297                                           result-bit-array)
1298        (error "~S and ~S don't have the same dimensions."
1299               bit-array-1 result-bit-array))
1300      result-bit-array)))
1301
1302 (defmacro def-bit-array-op (name function)
1303   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
1304      #!+sb-doc
1305      ,(format nil
1306               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
1307                BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
1308                If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1309                RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1310                All the arrays must have the same rank and dimensions."
1311               (symbol-name function))
1312      (declare (type (array bit) bit-array-1 bit-array-2)
1313               (type (or (array bit) (member t nil)) result-bit-array))
1314      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1315        (error "~S and ~S don't have the same dimensions."
1316               bit-array-1 bit-array-2))
1317      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1318        (if (and (simple-bit-vector-p bit-array-1)
1319                 (simple-bit-vector-p bit-array-2)
1320                 (simple-bit-vector-p result-bit-array))
1321            (locally (declare (optimize (speed 3) (safety 0)))
1322              (,name bit-array-1 bit-array-2 result-bit-array))
1323            (with-array-data ((data1 bit-array-1) (start1) (end1))
1324              (declare (ignore end1))
1325              (with-array-data ((data2 bit-array-2) (start2) (end2))
1326                (declare (ignore end2))
1327                (with-array-data ((data3 result-bit-array) (start3) (end3))
1328                  (do ((index-1 start1 (1+ index-1))
1329                       (index-2 start2 (1+ index-2))
1330                       (index-3 start3 (1+ index-3)))
1331                      ((>= index-3 end3) result-bit-array)
1332                    (declare (type index index-1 index-2 index-3))
1333                    (setf (sbit data3 index-3)
1334                          (logand (,function (sbit data1 index-1)
1335                                             (sbit data2 index-2))
1336                                  1))))))))))
1337
1338 (def-bit-array-op bit-and logand)
1339 (def-bit-array-op bit-ior logior)
1340 (def-bit-array-op bit-xor logxor)
1341 (def-bit-array-op bit-eqv logeqv)
1342 (def-bit-array-op bit-nand lognand)
1343 (def-bit-array-op bit-nor lognor)
1344 (def-bit-array-op bit-andc1 logandc1)
1345 (def-bit-array-op bit-andc2 logandc2)
1346 (def-bit-array-op bit-orc1 logorc1)
1347 (def-bit-array-op bit-orc2 logorc2)
1348
1349 (defun bit-not (bit-array &optional result-bit-array)
1350   #!+sb-doc
1351   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1352   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1353   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1354   created. Both arrays must have the same rank and dimensions."
1355   (declare (type (array bit) bit-array)
1356            (type (or (array bit) (member t nil)) result-bit-array))
1357   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1358     (if (and (simple-bit-vector-p bit-array)
1359              (simple-bit-vector-p result-bit-array))
1360         (locally (declare (optimize (speed 3) (safety 0)))
1361           (bit-not bit-array result-bit-array))
1362         (with-array-data ((src bit-array) (src-start) (src-end))
1363           (declare (ignore src-end))
1364           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1365             (do ((src-index src-start (1+ src-index))
1366                  (dst-index dst-start (1+ dst-index)))
1367                 ((>= dst-index dst-end) result-bit-array)
1368               (declare (type index src-index dst-index))
1369               (setf (sbit dst dst-index)
1370                     (logxor (sbit src src-index) 1))))))))