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