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