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