0.8.16.9:
[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
35 (defun %array-rank (array)
36   (%array-rank array))
37
38 (defun %array-dimension (array axis)
39   (%array-dimension array axis))
40
41 (defun %set-array-dimension (array axis value)
42   (%set-array-dimension array axis value))
43
44 (defun %check-bound (array bound index)
45   (declare (type index bound)
46            (fixnum index))
47   (%check-bound array bound index))
48
49 (defun %with-array-data (array start end)
50   (%with-array-data-macro array start end :fail-inline? t))
51
52 (defun %data-vector-and-index (array index)
53   (if (array-header-p array)
54       (multiple-value-bind (vector index)
55           (%with-array-data array index nil)
56         (values vector index))
57       (values array index)))
58
59 ;;; It'd waste space to expand copies of error handling in every
60 ;;; inline %WITH-ARRAY-DATA, so we have them call this function
61 ;;; instead. This is just a wrapper which is known never to return.
62 (defun failed-%with-array-data (array start end)
63   (declare (notinline %with-array-data))
64   (%with-array-data array start end)
65   (bug "called FAILED-%WITH-ARRAY-DATA with valid array parameters?"))
66 \f
67 ;;;; MAKE-ARRAY
68 (eval-when (:compile-toplevel :execute)
69   (sb!xc:defmacro pick-vector-type (type &rest specs)
70     `(cond ,@(mapcar (lambda (spec)
71                        `(,(if (eq (car spec) t)
72                               t
73                               `(subtypep ,type ',(car spec)))
74                          ,@(cdr spec)))
75                      specs))))
76
77 ;;; These functions are used in the implementation of MAKE-ARRAY for
78 ;;; complex arrays. There are lots of transforms to simplify
79 ;;; MAKE-ARRAY for various easy cases, but not for all reasonable
80 ;;; cases, so e.g. as of sbcl-0.6.6 we still make full calls to
81 ;;; MAKE-ARRAY for any non-simple array. Thus, there's some value to
82 ;;; making this somewhat efficient, at least not doing full calls to
83 ;;; SUBTYPEP in the easy cases.
84 (defun %vector-widetag-and-n-bits (type)
85   (case type
86     ;; Pick off some easy common cases.
87     ;;
88     ;; (Perhaps we should make a much more exhaustive table of easy
89     ;; common cases here. Or perhaps the effort would be better spent
90     ;; on smarter compiler transforms which do the calculation once
91     ;; and for all in any reasonable user programs.)
92     ((t)
93      (values #.sb!vm:simple-vector-widetag #.sb!vm:n-word-bits))
94     ((base-char standard-char character)
95      (values #.sb!vm:simple-base-string-widetag #.sb!vm:n-byte-bits))
96     ((bit)
97      (values #.sb!vm:simple-bit-vector-widetag 1))
98     ;; OK, we have to wade into SUBTYPEPing after all.
99     (t
100      #.`(pick-vector-type type
101          ,@(map 'list
102                 (lambda (saetp)
103                   `(,(sb!vm:saetp-specifier saetp)
104                     (values ,(sb!vm:saetp-typecode saetp)
105                             ,(sb!vm:saetp-n-bits saetp))))
106                 sb!vm:*specialized-array-element-type-properties*)))))
107
108 (defun %complex-vector-widetag (type)
109   (case type
110     ;; Pick off some easy common cases.
111     ((t)
112      #.sb!vm:complex-vector-widetag)
113     ((base-char character)
114      #.sb!vm:complex-base-string-widetag)
115     ((nil)
116      #.sb!vm:complex-vector-nil-widetag)
117     ((bit)
118      #.sb!vm:complex-bit-vector-widetag)
119     ;; OK, we have to wade into SUBTYPEPing after all.
120     (t
121      (pick-vector-type type
122        (nil #.sb!vm:complex-vector-nil-widetag)
123        (character #.sb!vm:complex-base-string-widetag)
124        (bit #.sb!vm:complex-bit-vector-widetag)
125        (t #.sb!vm:complex-vector-widetag)))))
126
127 (defun make-array (dimensions &key
128                               (element-type t)
129                               (initial-element nil initial-element-p)
130                               (initial-contents nil initial-contents-p)
131                               adjustable fill-pointer
132                               displaced-to displaced-index-offset)
133   (let* ((dimensions (if (listp dimensions) dimensions (list dimensions)))
134          (array-rank (length (the list dimensions)))
135          (simple (and (null fill-pointer)
136                       (not adjustable)
137                       (null displaced-to))))
138     (declare (fixnum array-rank))
139     (when (and displaced-index-offset (null displaced-to))
140       (error "can't specify :DISPLACED-INDEX-OFFSET without :DISPLACED-TO"))
141     (if (and simple (= array-rank 1))
142         ;; it's a (SIMPLE-ARRAY * (*))
143         (multiple-value-bind (type n-bits)
144             (%vector-widetag-and-n-bits element-type)
145           (declare (type (unsigned-byte 8) type)
146                    (type (integer 0 256) n-bits))
147           (let* ((length (car dimensions))
148                  (array (allocate-vector
149                          type
150                          length
151                          (ceiling (* (if (= type sb!vm:simple-base-string-widetag)
152                                          (1+ length)
153                                          length)
154                                      n-bits)
155                                   sb!vm:n-word-bits))))
156             (declare (type index length))
157             (when initial-element-p
158               (fill array initial-element))
159             (when initial-contents-p
160               (when initial-element-p
161                 (error "can't specify both :INITIAL-ELEMENT and ~
162                        :INITIAL-CONTENTS"))
163               (unless (= length (length initial-contents))
164                 (error "There are ~W elements in the :INITIAL-CONTENTS, but ~
165                        the vector length is ~W."
166                        (length initial-contents)
167                        length))
168               (replace array initial-contents))
169             array))
170         ;; it's either a complex array or a multidimensional array.
171         (let* ((total-size (reduce #'* dimensions))
172                (data (or displaced-to
173                          (data-vector-from-inits
174                           dimensions total-size element-type
175                           initial-contents initial-contents-p
176                           initial-element initial-element-p)))
177                (array (make-array-header
178                        (cond ((= array-rank 1)
179                               (%complex-vector-widetag element-type))
180                              (simple sb!vm:simple-array-widetag)
181                              (t sb!vm:complex-array-widetag))
182                        array-rank)))
183           (cond (fill-pointer
184                  (unless (= array-rank 1)
185                    (error "Only vectors can have fill pointers."))
186                  (let ((length (car dimensions)))
187                    (declare (fixnum length))
188                    (setf (%array-fill-pointer array)
189                      (cond ((eq fill-pointer t)
190                             length)
191                            (t
192                             (unless (and (fixnump fill-pointer)
193                                          (>= fill-pointer 0)
194                                          (<= fill-pointer length))
195                               ;; FIXME: should be TYPE-ERROR?
196                               (error "invalid fill-pointer ~W"
197                                      fill-pointer))
198                             fill-pointer))))
199                  (setf (%array-fill-pointer-p array) t))
200                 (t
201                  (setf (%array-fill-pointer array) total-size)
202                  (setf (%array-fill-pointer-p array) nil)))
203           (setf (%array-available-elements array) total-size)
204           (setf (%array-data-vector array) data)
205           (cond (displaced-to
206                  (when (or initial-element-p initial-contents-p)
207                    (error "Neither :INITIAL-ELEMENT nor :INITIAL-CONTENTS ~
208                    can be specified along with :DISPLACED-TO"))
209                  (let ((offset (or displaced-index-offset 0)))
210                    (when (> (+ offset total-size)
211                             (array-total-size displaced-to))
212                      (error "~S doesn't have enough elements." displaced-to))
213                    (setf (%array-displacement array) offset)
214                    (setf (%array-displaced-p array) t)))
215                 (t
216                  (setf (%array-displaced-p array) nil)))
217           (let ((axis 0))
218             (dolist (dim dimensions)
219               (setf (%array-dimension array axis) dim)
220               (incf axis)))
221           array))))
222
223 ;;; DATA-VECTOR-FROM-INITS returns a simple vector that has the
224 ;;; specified array characteristics. Dimensions is only used to pass
225 ;;; to FILL-DATA-VECTOR for error checking on the structure of
226 ;;; initial-contents.
227 (defun data-vector-from-inits (dimensions total-size element-type
228                                initial-contents initial-contents-p
229                                initial-element initial-element-p)
230   (when (and initial-contents-p initial-element-p)
231     (error "cannot supply both :INITIAL-CONTENTS and :INITIAL-ELEMENT to
232             either MAKE-ARRAY or ADJUST-ARRAY."))
233   (let ((data (if initial-element-p
234                   (make-array total-size
235                               :element-type element-type
236                               :initial-element initial-element)
237                   (make-array total-size
238                               :element-type element-type))))
239     (cond (initial-element-p
240            (unless (simple-vector-p data)
241              (unless (typep initial-element element-type)
242                (error "~S cannot be used to initialize an array of type ~S."
243                       initial-element element-type))
244              (fill (the vector data) initial-element)))
245           (initial-contents-p
246            (fill-data-vector data dimensions initial-contents)))
247     data))
248
249 (defun fill-data-vector (vector dimensions initial-contents)
250   (let ((index 0))
251     (labels ((frob (axis dims contents)
252                (cond ((null dims)
253                       (setf (aref vector index) contents)
254                       (incf index))
255                      (t
256                       (unless (typep contents 'sequence)
257                         (error "malformed :INITIAL-CONTENTS: ~S is not a ~
258                                 sequence, but ~W more layer~:P needed."
259                                contents
260                                (- (length dimensions) axis)))
261                       (unless (= (length contents) (car dims))
262                         (error "malformed :INITIAL-CONTENTS: Dimension of ~
263                                 axis ~W is ~W, but ~S is ~W long."
264                                axis (car dims) contents (length contents)))
265                       (if (listp contents)
266                           (dolist (content contents)
267                             (frob (1+ axis) (cdr dims) content))
268                           (dotimes (i (length contents))
269                             (frob (1+ axis) (cdr dims) (aref contents i))))))))
270       (frob 0 dimensions initial-contents))))
271
272 (defun vector (&rest objects)
273   #!+sb-doc
274   "Construct a SIMPLE-VECTOR from the given objects."
275   (coerce (the list objects) 'simple-vector))
276 \f
277 ;;;; accessor/setter functions
278 (defun hairy-data-vector-ref (array index)
279   (with-array-data ((vector array) (index index) (end))
280     (declare (ignore end))
281     (etypecase vector .
282                #.(map 'list
283                       (lambda (saetp)
284                         (let* ((type (sb!vm:saetp-specifier saetp))
285                                (atype `(simple-array ,type (*))))
286                           `(,atype
287                             (data-vector-ref (the ,atype vector) index))))
288                       (sort
289                        (copy-seq
290                         sb!vm:*specialized-array-element-type-properties*)
291                        #'> :key #'sb!vm:saetp-importance)))))
292
293 ;;; (Ordinary DATA-VECTOR-REF usage compiles into a vop, but
294 ;;; DATA-VECTOR-REF is also FOLDABLE, and this ordinary function
295 ;;; definition is needed for the compiler to use in constant folding.)
296 (defun data-vector-ref (array index)
297   (hairy-data-vector-ref array index))
298
299 (defun hairy-data-vector-set (array index new-value)
300   (with-array-data ((vector array) (index index) (end))
301     (declare (ignore end))
302     (etypecase vector .
303                #.(map 'list
304                       (lambda (saetp)
305                         (let* ((type (sb!vm:saetp-specifier saetp))
306                                (atype `(simple-array ,type (*))))
307                           `(,atype
308                             (data-vector-set (the ,atype vector) index
309                                              (the ,type new-value))
310                             ;; For specialized arrays, the return from
311                             ;; data-vector-set would have to be
312                             ;; reboxed to be a (Lisp) return value;
313                             ;; instead, we use the already-boxed value
314                             ;; as the return.
315                             new-value)))
316                       (sort
317                        (copy-seq
318                         sb!vm:*specialized-array-element-type-properties*)
319                        #'> :key #'sb!vm:saetp-importance)))))
320
321 (defun %array-row-major-index (array subscripts
322                                      &optional (invalid-index-error-p t))
323   (declare (array array)
324            (list subscripts))
325   (let ((rank (array-rank array)))
326     (unless (= rank (length subscripts))
327       (error "wrong number of subscripts, ~W, for array of rank ~W"
328              (length subscripts) rank))
329     (if (array-header-p array)
330         (do ((subs (nreverse subscripts) (cdr subs))
331              (axis (1- (array-rank array)) (1- axis))
332              (chunk-size 1)
333              (result 0))
334             ((null subs) result)
335           (declare (list subs) (fixnum axis chunk-size result))
336           (let ((index (car subs))
337                 (dim (%array-dimension array axis)))
338             (declare (fixnum dim))
339             (unless (and (fixnump index) (< -1 index dim))
340               (if invalid-index-error-p
341                   (error 'simple-type-error
342                          :format-control "invalid index ~W~[~;~:; on axis ~:*~W~] in ~S"
343                          :format-arguments (list index axis array)
344                          :datum index
345                          :expected-type `(integer 0 (,dim)))
346                   (return-from %array-row-major-index nil)))
347             (incf result (* chunk-size (the fixnum index)))
348             (setf chunk-size (* chunk-size dim))))
349         (let ((index (first subscripts))
350               (length (length (the (simple-array * (*)) array))))
351           (unless (and (fixnump index) (< -1 index length))
352             (if invalid-index-error-p
353                 ;; FIXME: perhaps this should share a format-string
354                 ;; with INVALID-ARRAY-INDEX-ERROR or
355                 ;; INDEX-TOO-LARGE-ERROR?
356                 (error 'simple-type-error
357                        :format-control "invalid index ~W in ~S"
358                        :format-arguments (list index array)
359                        :datum index
360                        :expected-type `(integer 0 (,length)))
361                 (return-from %array-row-major-index nil)))
362           index))))
363
364 (defun array-in-bounds-p (array &rest subscripts)
365   #!+sb-doc
366   "Return T if the SUBSCIPTS are in bounds for the ARRAY, NIL otherwise."
367   (if (%array-row-major-index array subscripts nil)
368       t))
369
370 (defun array-row-major-index (array &rest subscripts)
371   (%array-row-major-index array subscripts))
372
373 (defun aref (array &rest subscripts)
374   #!+sb-doc
375   "Return the element of the ARRAY specified by the SUBSCRIPTS."
376   (row-major-aref array (%array-row-major-index array subscripts)))
377
378 (defun %aset (array &rest stuff)
379   (let ((subscripts (butlast stuff))
380         (new-value (car (last stuff))))
381     (setf (row-major-aref array (%array-row-major-index array subscripts))
382           new-value)))
383
384 ;;; FIXME: What's supposed to happen with functions
385 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
386 ;;; DEFSETF FOO is also defined? It seems as though the logical
387 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
388 ;;; and replace it with the (SETF FOO) function, issuing a warning,
389 ;;; just as for ordinary functions
390 ;;;  * (LISP-IMPLEMENTATION-VERSION)
391 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
392 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
393 ;;;  ZOO
394 ;;;  * (DEFUN ZOO (X) (* 3 X))
395 ;;;  Warning: ZOO previously defined as a macro.
396 ;;;  ZOO
397 ;;; But that doesn't seem to be what happens in CMU CL.
398 ;;;
399 ;;; KLUDGE: this is probably because ANSI, in its wisdom (CLHS
400 ;;; 5.1.2.5) requires implementations to support
401 ;;;   (SETF (APPLY #'AREF ...) ...)
402 ;;; [and also #'BIT and #'SBIT].  Yes, this is terrifying, and it's
403 ;;; also terrifying that this sequence of definitions causes it to
404 ;;; work.
405 ;;;
406 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
407 ;;; has a setf expansion and/or a setf function defined.
408
409 #!-sb-fluid (declaim (inline (setf aref)))
410 (defun (setf aref) (new-value array &rest subscripts)
411   (declare (type array array))
412   (setf (row-major-aref array (%array-row-major-index array subscripts))
413         new-value))
414
415 (defun row-major-aref (array index)
416   #!+sb-doc
417   "Return the element of array corressponding to the row-major index. This is
418    SETF'able."
419   (declare (optimize (safety 1)))
420   (row-major-aref array index))
421
422 (defun %set-row-major-aref (array index new-value)
423   (declare (optimize (safety 1)))
424   (setf (row-major-aref array index) new-value))
425
426 (defun svref (simple-vector index)
427   #!+sb-doc
428   "Return the INDEX'th element of the given Simple-Vector."
429   (declare (optimize (safety 1)))
430   (aref simple-vector index))
431
432 (defun %svset (simple-vector index new)
433   (declare (optimize (safety 1)))
434   (setf (aref simple-vector index) new))
435
436 (defun bit (bit-array &rest subscripts)
437   #!+sb-doc
438   "Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
439   (declare (type (array bit) bit-array) (optimize (safety 1)))
440   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
441
442 (defun %bitset (bit-array &rest stuff)
443   (declare (type (array bit) bit-array) (optimize (safety 1)))
444   (let ((subscripts (butlast stuff))
445         (new-value (car (last stuff))))
446     (setf (row-major-aref bit-array
447                           (%array-row-major-index bit-array subscripts))
448           new-value)))
449
450 #!-sb-fluid (declaim (inline (setf bit)))
451 (defun (setf bit) (new-value bit-array &rest subscripts)
452   (declare (type (array bit) bit-array) (optimize (safety 1)))
453   (setf (row-major-aref bit-array
454                         (%array-row-major-index bit-array subscripts))
455         new-value))
456
457 (defun sbit (simple-bit-array &rest subscripts)
458   #!+sb-doc
459   "Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
460   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
461   (row-major-aref simple-bit-array
462                   (%array-row-major-index simple-bit-array subscripts)))
463
464 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
465 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
466 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
467 ;;; -- WHN 19990911
468 (defun %sbitset (simple-bit-array &rest stuff)
469   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
470   (let ((subscripts (butlast stuff))
471         (new-value (car (last stuff))))
472     (setf (row-major-aref simple-bit-array
473                           (%array-row-major-index simple-bit-array subscripts))
474           new-value)))
475
476 #!-sb-fluid (declaim (inline (setf sbit)))
477 (defun (setf sbit) (new-value bit-array &rest subscripts)
478   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
479   (setf (row-major-aref bit-array
480                         (%array-row-major-index bit-array subscripts))
481         new-value))
482 \f
483 ;;;; miscellaneous array properties
484
485 (defun array-element-type (array)
486   #!+sb-doc
487   "Return the type of the elements of the array"
488   (let ((widetag (widetag-of array)))
489     (macrolet ((pick-element-type (&rest stuff)
490                  `(cond ,@(mapcar (lambda (stuff)
491                                     (cons
492                                      (let ((item (car stuff)))
493                                        (cond ((eq item t)
494                                               t)
495                                              ((listp item)
496                                               (cons 'or
497                                                     (mapcar (lambda (x)
498                                                               `(= widetag ,x))
499                                                             item)))
500                                              (t
501                                               `(= widetag ,item))))
502                                      (cdr stuff)))
503                                   stuff))))
504       #.`(pick-element-type
505           ,@(map 'list
506                  (lambda (saetp)
507                    `(,(if (sb!vm:saetp-complex-typecode saetp)
508                           (list (sb!vm:saetp-typecode saetp)
509                                 (sb!vm:saetp-complex-typecode saetp))
510                           (sb!vm:saetp-typecode saetp))
511                      ',(sb!vm:saetp-specifier saetp)))
512                  sb!vm:*specialized-array-element-type-properties*)
513           ((sb!vm:simple-array-widetag
514             sb!vm:complex-vector-widetag
515             sb!vm:complex-array-widetag)
516            (with-array-data ((array array) (start) (end))
517              (declare (ignore start end))
518              (array-element-type array)))
519           (t
520            (error 'type-error :datum array :expected-type 'array))))))
521
522 (defun array-rank (array)
523   #!+sb-doc
524   "Return the number of dimensions of ARRAY."
525   (if (array-header-p array)
526       (%array-rank array)
527       1))
528
529 (defun array-dimension (array axis-number)
530   #!+sb-doc
531   "Return the length of dimension AXIS-NUMBER of ARRAY."
532   (declare (array array) (type index axis-number))
533   (cond ((not (array-header-p array))
534          (unless (= axis-number 0)
535            (error "Vector axis is not zero: ~S" axis-number))
536          (length (the (simple-array * (*)) array)))
537         ((>= axis-number (%array-rank array))
538          (error "Axis number ~W is too big; ~S only has ~D dimension~:P."
539                 axis-number array (%array-rank array)))
540         (t
541          ;; ANSI sayeth (ADJUST-ARRAY dictionary entry): 
542          ;; 
543          ;;   "If A is displaced to B, the consequences are
544          ;;   unspecified if B is adjusted in such a way that it no
545          ;;   longer has enough elements to satisfy A.
546          ;;
547          ;; In situations where this matters we should be doing a
548          ;; bounds-check, which in turn uses ARRAY-DIMENSION -- so
549          ;; this seems like a good place to signal an error.
550          (multiple-value-bind (target offset) (array-displacement array)
551            (when (and target 
552                       (> (array-total-size array)
553                          (- (array-total-size target) offset)))
554                (error 'displaced-to-array-too-small-error
555                       :format-control "~@<The displaced-to array is too small. ~S ~
556                                       elements after offset required, ~S available.~:@>"
557                       :format-arguments (list (array-total-size array) 
558                                               (- (array-total-size target) offset))))
559            (%array-dimension array axis-number)))))
560
561 (defun array-dimensions (array)
562   #!+sb-doc
563   "Return a list whose elements are the dimensions of the array"
564   (declare (array array))
565   (if (array-header-p array)
566       (do ((results nil (cons (array-dimension array index) results))
567            (index (1- (array-rank array)) (1- index)))
568           ((minusp index) results))
569       (list (array-dimension array 0))))
570
571 (defun array-total-size (array)
572   #!+sb-doc
573   "Return the total number of elements in the Array."
574   (declare (array array))
575   (if (array-header-p array)
576       (%array-available-elements array)
577       (length (the vector array))))
578
579 (defun array-displacement (array)
580   #!+sb-doc
581   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
582    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
583   (declare (type array array))
584   (if (and (array-header-p array) ; if unsimple and
585            (%array-displaced-p array)) ; displaced
586       (values (%array-data-vector array) (%array-displacement array))
587       (values nil 0)))
588
589 (defun adjustable-array-p (array)
590   #!+sb-doc
591   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
592    to the argument, this happens for complex arrays."
593   (declare (array array))
594   ;; Note that this appears not to be a fundamental limitation.
595   ;; non-vector SIMPLE-ARRAYs are in fact capable of being adjusted,
596   ;; but in practice we test using ADJUSTABLE-ARRAY-P in ADJUST-ARRAY.
597   ;; -- CSR, 2004-03-01.
598   (not (typep array 'simple-array)))
599 \f
600 ;;;; fill pointer frobbing stuff
601
602 (defun array-has-fill-pointer-p (array)
603   #!+sb-doc
604   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
605   (declare (array array))
606   (and (array-header-p array) (%array-fill-pointer-p array)))
607
608 (defun fill-pointer (vector)
609   #!+sb-doc
610   "Return the FILL-POINTER of the given VECTOR."
611   (declare (vector vector))
612   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
613       (%array-fill-pointer vector)
614       (error 'simple-type-error
615              :datum vector
616              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
617              :format-control "~S is not an array with a fill pointer."
618              :format-arguments (list vector))))
619
620 (defun %set-fill-pointer (vector new)
621   (declare (vector vector) (fixnum new))
622   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
623       (if (> new (%array-available-elements vector))
624         (error
625          "The new fill pointer, ~S, is larger than the length of the vector."
626          new)
627         (setf (%array-fill-pointer vector) new))
628       (error 'simple-type-error
629              :datum vector
630              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
631              :format-control "~S is not an array with a fill pointer."
632              :format-arguments (list vector))))
633
634 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
635 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
636 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
637 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
638 ;;; back to CMU CL).
639 (defun vector-push (new-el array)
640   #!+sb-doc
641   "Attempt to set the element of ARRAY designated by its fill pointer
642    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
643    too large, NIL is returned, otherwise the index of the pushed element is
644    returned."
645   (declare (vector array))
646   (let ((fill-pointer (fill-pointer array)))
647     (declare (fixnum fill-pointer))
648     (cond ((= fill-pointer (%array-available-elements array))
649            nil)
650           (t
651            (setf (aref array fill-pointer) new-el)
652            (setf (%array-fill-pointer array) (1+ fill-pointer))
653            fill-pointer))))
654
655 (defun vector-push-extend (new-element
656                            vector
657                            &optional
658                            (extension (1+ (length vector))))
659   (declare (vector vector) (fixnum extension))
660   (let ((fill-pointer (fill-pointer vector)))
661     (declare (fixnum fill-pointer))
662     (when (= fill-pointer (%array-available-elements vector))
663       (adjust-array vector (+ fill-pointer extension)))
664     ;; disable bounds checking
665     (locally (declare (optimize (safety 0)))
666       (setf (aref vector fill-pointer) new-element))
667     (setf (%array-fill-pointer vector) (1+ fill-pointer))
668     fill-pointer))
669
670 (defun vector-pop (array)
671   #!+sb-doc
672   "Decrease the fill pointer by 1 and return the element pointed to by the
673   new fill pointer."
674   (declare (vector array))
675   (let ((fill-pointer (fill-pointer array)))
676     (declare (fixnum fill-pointer))
677     (if (zerop fill-pointer)
678         (error "There is nothing left to pop.")
679         ;; disable bounds checking (and any fixnum test)
680         (locally (declare (optimize (safety 0)))
681           (aref array
682                 (setf (%array-fill-pointer array)
683                       (1- fill-pointer)))))))
684
685 \f
686 ;;;; ADJUST-ARRAY
687
688 (defun adjust-array (array dimensions &key
689                            (element-type (array-element-type array))
690                            (initial-element nil initial-element-p)
691                            (initial-contents nil initial-contents-p)
692                            fill-pointer
693                            displaced-to displaced-index-offset)
694   #!+sb-doc
695   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
696   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
697     (cond ((/= (the fixnum (length (the list dimensions)))
698                (the fixnum (array-rank array)))
699            (error "The number of dimensions not equal to rank of array."))
700           ((not (subtypep element-type (array-element-type array)))
701            (error "The new element type, ~S, is incompatible with old type."
702                   element-type)))
703     (let ((array-rank (length (the list dimensions))))
704       (declare (fixnum array-rank))
705       (unless (= array-rank 1)
706         (when fill-pointer
707           (error "Only vectors can have fill pointers.")))
708       (cond (initial-contents-p
709              ;; array former contents replaced by INITIAL-CONTENTS
710              (if (or initial-element-p displaced-to)
711                  (error "INITIAL-CONTENTS may not be specified with ~
712                          the :INITIAL-ELEMENT or :DISPLACED-TO option."))
713              (let* ((array-size (apply #'* dimensions))
714                     (array-data (data-vector-from-inits
715                                  dimensions array-size element-type
716                                  initial-contents initial-contents-p
717                                  initial-element initial-element-p)))
718                (if (adjustable-array-p array)
719                    (set-array-header array array-data array-size
720                                  (get-new-fill-pointer array array-size
721                                                        fill-pointer)
722                                  0 dimensions nil)
723                    (if (array-header-p array)
724                        ;; simple multidimensional or single dimensional array
725                        (make-array dimensions
726                                    :element-type element-type
727                                    :initial-contents initial-contents)
728                        array-data))))
729             (displaced-to
730              ;; We already established that no INITIAL-CONTENTS was supplied.
731              (when initial-element
732                (error "The :INITIAL-ELEMENT option may not be specified ~
733                        with :DISPLACED-TO."))
734              (unless (subtypep element-type (array-element-type displaced-to))
735                (error "can't displace an array of type ~S into another of ~
736                        type ~S"
737                       element-type (array-element-type displaced-to)))
738              (let ((displacement (or displaced-index-offset 0))
739                    (array-size (apply #'* dimensions)))
740                (declare (fixnum displacement array-size))
741                (if (< (the fixnum (array-total-size displaced-to))
742                       (the fixnum (+ displacement array-size)))
743                    (error "The :DISPLACED-TO array is too small."))
744                (if (adjustable-array-p array)
745                    ;; None of the original contents appear in adjusted array.
746                    (set-array-header array displaced-to array-size
747                                      (get-new-fill-pointer array array-size
748                                                            fill-pointer)
749                                      displacement dimensions t)
750                    ;; simple multidimensional or single dimensional array
751                    (make-array dimensions
752                                :element-type element-type
753                                :displaced-to displaced-to
754                                :displaced-index-offset
755                                displaced-index-offset))))
756             ((= array-rank 1)
757              (let ((old-length (array-total-size array))
758                    (new-length (car dimensions))
759                    new-data)
760                (declare (fixnum old-length new-length))
761                (with-array-data ((old-data array) (old-start)
762                                  (old-end old-length))
763                  (cond ((or (%array-displaced-p array)
764                             (< old-length new-length))
765                         (setf new-data
766                               (data-vector-from-inits
767                                dimensions new-length element-type
768                                initial-contents initial-contents-p
769                                initial-element initial-element-p))
770                         (replace new-data old-data
771                                  :start2 old-start :end2 old-end))
772                        (t (setf new-data
773                                 (shrink-vector old-data new-length))))
774                  (if (adjustable-array-p array)
775                      (set-array-header array new-data new-length
776                                        (get-new-fill-pointer array new-length
777                                                              fill-pointer)
778                                        0 dimensions nil)
779                      new-data))))
780             (t
781              (let ((old-length (%array-available-elements array))
782                    (new-length (apply #'* dimensions)))
783                (declare (fixnum old-length new-length))
784                (with-array-data ((old-data array) (old-start)
785                                  (old-end old-length))
786                  (declare (ignore old-end))
787                  (let ((new-data (if (or (%array-displaced-p array)
788                                          (> new-length old-length))
789                                      (data-vector-from-inits
790                                       dimensions new-length
791                                       element-type () nil
792                                       initial-element initial-element-p)
793                                      old-data)))
794                    (if (or (zerop old-length) (zerop new-length))
795                        (when initial-element-p (fill new-data initial-element))
796                        (zap-array-data old-data (array-dimensions array)
797                                        old-start
798                                        new-data dimensions new-length
799                                        element-type initial-element
800                                        initial-element-p))
801                    (if (adjustable-array-p array)
802                        (set-array-header array new-data new-length
803                                          new-length 0 dimensions nil)
804                        (let ((new-array
805                               (make-array-header
806                                sb!vm:simple-array-widetag array-rank)))
807                          (set-array-header new-array new-data new-length
808                                            new-length 0 dimensions nil)))))))))))
809   
810
811 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
812   (cond ((not fill-pointer)
813          (when (array-has-fill-pointer-p old-array)
814            (when (> (%array-fill-pointer old-array) new-array-size)
815              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
816                      smaller than its fill pointer (~S)"
817                     old-array new-array-size (fill-pointer old-array)))
818            (%array-fill-pointer old-array)))
819         ((not (array-has-fill-pointer-p old-array))
820          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
821                  in ADJUST-ARRAY unless the array (~S) was originally ~
822                  created with a fill pointer"
823                 fill-pointer
824                 old-array))
825         ((numberp fill-pointer)
826          (when (> fill-pointer new-array-size)
827            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
828                    than the new length of the vector (~S)"
829                   fill-pointer new-array-size))
830          fill-pointer)
831         ((eq fill-pointer t)
832          new-array-size)
833         (t
834          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
835                 fill-pointer))))
836
837 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
838 ;;; which must be less than or equal to its current length.
839 (defun shrink-vector (vector new-length)
840   (declare (vector vector))
841   (unless (array-header-p vector)
842     (macrolet ((frob (name &rest things)
843                  `(etypecase ,name
844                     ((simple-array nil (*)) (error 'nil-array-accessed-error))
845                     ,@(mapcar (lambda (thing)
846                                 (destructuring-bind (type-spec fill-value)
847                                     thing
848                                   `(,type-spec
849                                     (fill (truly-the ,type-spec ,name)
850                                           ,fill-value
851                                           :start new-length))))
852                               things))))
853       #.`(frob vector
854           ,@(map 'list
855                  (lambda (saetp)
856                    `((simple-array ,(sb!vm:saetp-specifier saetp) (*))
857                      ,(if (eq (sb!vm:saetp-specifier saetp) 'character)
858                           *default-init-char-form*
859                           (sb!vm:saetp-initial-element-default saetp))))
860                  (remove-if-not
861                   #'sb!vm:saetp-specifier
862                   sb!vm:*specialized-array-element-type-properties*)))))
863   ;; Only arrays have fill-pointers, but vectors have their length
864   ;; parameter in the same place.
865   (setf (%array-fill-pointer vector) new-length)
866   vector)
867
868 ;;; Fill in array header with the provided information, and return the array.
869 (defun set-array-header (array data length fill-pointer displacement dimensions
870                          &optional displacedp)
871   (setf (%array-data-vector array) data)
872   (setf (%array-available-elements array) length)
873   (cond (fill-pointer
874          (setf (%array-fill-pointer array) fill-pointer)
875          (setf (%array-fill-pointer-p array) t))
876         (t
877          (setf (%array-fill-pointer array) length)
878          (setf (%array-fill-pointer-p array) nil)))
879   (setf (%array-displacement array) displacement)
880   (if (listp dimensions)
881       (dotimes (axis (array-rank array))
882         (declare (type index axis))
883         (setf (%array-dimension array axis) (pop dimensions)))
884       (setf (%array-dimension array 0) dimensions))
885   (setf (%array-displaced-p array) displacedp)
886   array)
887 \f
888 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
889
890 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
891 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice.
892 (defvar *zap-array-data-temp* (make-array 1000 :initial-element t))
893
894 (defun zap-array-data-temp (length element-type initial-element
895                             initial-element-p)
896   (declare (fixnum length))
897   (when (> length (the fixnum (length *zap-array-data-temp*)))
898     (setf *zap-array-data-temp*
899           (make-array length :initial-element t)))
900   (when initial-element-p
901     (unless (typep initial-element element-type)
902       (error "~S can't be used to initialize an array of type ~S."
903              initial-element element-type))
904     (fill (the simple-vector *zap-array-data-temp*) initial-element
905           :end length))
906   *zap-array-data-temp*)
907
908 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
909 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
910 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
911 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
912 ;;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and INITIAL-ELEMENT-P
913 ;;; are used when OLD-DATA and NEW-DATA are EQ; in this case, a
914 ;;; temporary must be used and filled appropriately. When OLD-DATA and
915 ;;; NEW-DATA are not EQ, NEW-DATA has already been filled with any
916 ;;; specified initial-element.
917 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
918                        element-type initial-element initial-element-p)
919   (declare (list old-dims new-dims))
920   (setq old-dims (nreverse old-dims))
921   (setq new-dims (reverse new-dims))
922   (if (eq old-data new-data)
923       (let ((temp (zap-array-data-temp new-length element-type
924                                        initial-element initial-element-p)))
925         (zap-array-data-aux old-data old-dims offset temp new-dims)
926         (dotimes (i new-length) (setf (aref new-data i) (aref temp i))))
927       (zap-array-data-aux old-data old-dims offset new-data new-dims)))
928
929 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
930   (declare (fixnum offset))
931   (let ((limits (mapcar (lambda (x y)
932                           (declare (fixnum x y))
933                           (1- (the fixnum (min x y))))
934                         old-dims new-dims)))
935     (macrolet ((bump-index-list (index limits)
936                  `(do ((subscripts ,index (cdr subscripts))
937                        (limits ,limits (cdr limits)))
938                       ((null subscripts) :eof)
939                     (cond ((< (the fixnum (car subscripts))
940                               (the fixnum (car limits)))
941                            (rplaca subscripts
942                                    (1+ (the fixnum (car subscripts))))
943                            (return ,index))
944                           (t (rplaca subscripts 0))))))
945       (do ((index (make-list (length old-dims) :initial-element 0)
946                   (bump-index-list index limits)))
947           ((eq index :eof))
948         (setf (aref new-data (row-major-index-from-dims index new-dims))
949               (aref old-data
950                     (+ (the fixnum (row-major-index-from-dims index old-dims))
951                        offset)))))))
952
953 ;;; Figure out the row-major-order index of an array reference from a
954 ;;; list of subscripts and a list of dimensions. This is for internal
955 ;;; calls only, and the subscripts and dim-list variables are assumed
956 ;;; to be reversed from what the user supplied.
957 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
958   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
959        (rev-dim-list rev-dim-list (cdr rev-dim-list))
960        (chunk-size 1)
961        (result 0))
962       ((null rev-dim-list) result)
963     (declare (fixnum chunk-size result))
964     (setq result (+ result
965                     (the fixnum (* (the fixnum (car rev-subscripts))
966                                    chunk-size))))
967     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
968 \f
969 ;;;; some bit stuff
970
971 (defun bit-array-same-dimensions-p (array1 array2)
972   (declare (type (array bit) array1 array2))
973   (and (= (array-rank array1)
974           (array-rank array2))
975        (dotimes (index (array-rank array1) t)
976          (when (/= (array-dimension array1 index)
977                    (array-dimension array2 index))
978            (return nil)))))
979
980 (defun pick-result-array (result-bit-array bit-array-1)
981   (case result-bit-array
982     ((t) bit-array-1)
983     ((nil) (make-array (array-dimensions bit-array-1)
984                        :element-type 'bit
985                        :initial-element 0))
986     (t
987      (unless (bit-array-same-dimensions-p bit-array-1
988                                           result-bit-array)
989        (error "~S and ~S don't have the same dimensions."
990               bit-array-1 result-bit-array))
991      result-bit-array)))
992
993 (defmacro def-bit-array-op (name function)
994   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
995      #!+sb-doc
996      ,(format nil
997               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
998                BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
999                If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1000                RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1001                All the arrays must have the same rank and dimensions."
1002               (symbol-name function))
1003      (declare (type (array bit) bit-array-1 bit-array-2)
1004               (type (or (array bit) (member t nil)) result-bit-array))
1005      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1006        (error "~S and ~S don't have the same dimensions."
1007               bit-array-1 bit-array-2))
1008      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1009        (if (and (simple-bit-vector-p bit-array-1)
1010                 (simple-bit-vector-p bit-array-2)
1011                 (simple-bit-vector-p result-bit-array))
1012            (locally (declare (optimize (speed 3) (safety 0)))
1013              (,name bit-array-1 bit-array-2 result-bit-array))
1014            (with-array-data ((data1 bit-array-1) (start1) (end1))
1015              (declare (ignore end1))
1016              (with-array-data ((data2 bit-array-2) (start2) (end2))
1017                (declare (ignore end2))
1018                (with-array-data ((data3 result-bit-array) (start3) (end3))
1019                  (do ((index-1 start1 (1+ index-1))
1020                       (index-2 start2 (1+ index-2))
1021                       (index-3 start3 (1+ index-3)))
1022                      ((>= index-3 end3) result-bit-array)
1023                    (declare (type index index-1 index-2 index-3))
1024                    (setf (sbit data3 index-3)
1025                          (logand (,function (sbit data1 index-1)
1026                                             (sbit data2 index-2))
1027                                  1))))))))))
1028
1029 (def-bit-array-op bit-and logand)
1030 (def-bit-array-op bit-ior logior)
1031 (def-bit-array-op bit-xor logxor)
1032 (def-bit-array-op bit-eqv logeqv)
1033 (def-bit-array-op bit-nand lognand)
1034 (def-bit-array-op bit-nor lognor)
1035 (def-bit-array-op bit-andc1 logandc1)
1036 (def-bit-array-op bit-andc2 logandc2)
1037 (def-bit-array-op bit-orc1 logorc1)
1038 (def-bit-array-op bit-orc2 logorc2)
1039
1040 (defun bit-not (bit-array &optional result-bit-array)
1041   #!+sb-doc
1042   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1043   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1044   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1045   created. Both arrays must have the same rank and dimensions."
1046   (declare (type (array bit) bit-array)
1047            (type (or (array bit) (member t nil)) result-bit-array))
1048   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1049     (if (and (simple-bit-vector-p bit-array)
1050              (simple-bit-vector-p result-bit-array))
1051         (locally (declare (optimize (speed 3) (safety 0)))
1052           (bit-not bit-array result-bit-array))
1053         (with-array-data ((src bit-array) (src-start) (src-end))
1054           (declare (ignore src-end))
1055           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1056             (do ((src-index src-start (1+ src-index))
1057                  (dst-index dst-start (1+ dst-index)))
1058                 ((>= dst-index dst-end) result-bit-array)
1059               (declare (type index src-index dst-index))
1060               (setf (sbit dst dst-index)
1061                     (logxor (sbit src src-index) 1))))))))