b8a9fcdf184f49b34ea8b601809b431cb30fa5ca
[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
630              "~S is not an array with a fill-pointer."
631              :format-arguments (list vector))))
632
633 (defun %set-fill-pointer (vector new)
634   (declare (vector vector) (fixnum new))
635   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
636       (if (> new (%array-available-elements vector))
637         (error
638          "The new fill pointer, ~S, is larger than the length of the vector."
639          new)
640         (setf (%array-fill-pointer vector) new))
641       (error 'simple-type-error
642              :datum vector
643              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
644              :format-control "~S is not an array with a fill-pointer."
645              :format-arguments (list vector))))
646
647 (defun vector-push (new-el array)
648   #!+sb-doc
649   "Attempt to set the element of ARRAY designated by its fill pointer
650    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
651    too large, NIL is returned, otherwise the index of the pushed element is
652    returned."
653   (declare (vector array))
654   (let ((fill-pointer (fill-pointer array)))
655     (declare (fixnum fill-pointer))
656     (cond ((= fill-pointer (%array-available-elements array))
657            nil)
658           (t
659            (setf (aref array fill-pointer) new-el)
660            (setf (%array-fill-pointer array) (1+ fill-pointer))
661            fill-pointer))))
662
663 (defun vector-push-extend (new-element
664                            vector
665                            &optional
666                            (extension (1+ (length vector))))
667   #!+sb-doc
668   "This is like Vector-Push except that if the fill pointer gets too
669    large, the Vector is extended rather than Nil being returned."
670   (declare (vector vector) (fixnum extension))
671   (let ((fill-pointer (fill-pointer vector)))
672     (declare (fixnum fill-pointer))
673     (when (= fill-pointer (%array-available-elements vector))
674       (adjust-array vector (+ fill-pointer extension)))
675     (setf (aref vector fill-pointer) new-element)
676     (setf (%array-fill-pointer vector) (1+ fill-pointer))
677     fill-pointer))
678
679 (defun vector-pop (array)
680   #!+sb-doc
681   "Attempts to decrease the fill-pointer by 1 and return the element
682    pointer to by the new fill pointer. If the original value of the fill
683    pointer is 0, an error occurs."
684   (declare (vector array))
685   (let ((fill-pointer (fill-pointer array)))
686     (declare (fixnum fill-pointer))
687     (if (zerop fill-pointer)
688         (error "There is nothing left to pop.")
689         (aref array
690               (setf (%array-fill-pointer array)
691                     (1- fill-pointer))))))
692 \f
693 ;;;; ADJUST-ARRAY
694
695 (defun adjust-array (array dimensions &key
696                            (element-type (array-element-type array))
697                            (initial-element nil initial-element-p)
698                            initial-contents fill-pointer
699                            displaced-to displaced-index-offset)
700   #!+sb-doc
701   "Adjusts the Array's dimensions to the given Dimensions and stuff."
702   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
703     (cond ((/= (the fixnum (length (the list dimensions)))
704                (the fixnum (array-rank array)))
705            (error "The number of dimensions not equal to rank of array."))
706           ((not (subtypep element-type (array-element-type array)))
707            (error "The new element type, ~S, is incompatible with old type."
708                   element-type)))
709     (let ((array-rank (length (the list dimensions))))
710       (declare (fixnum array-rank))
711       (when (and fill-pointer (> array-rank 1))
712         (error "Multidimensional arrays can't have fill pointers."))
713       (cond (initial-contents
714              ;; array former contents replaced by INITIAL-CONTENTS
715              (if (or initial-element-p displaced-to)
716                  (error "INITIAL-CONTENTS may not be specified with ~
717                  the :INITIAL-ELEMENT or :DISPLACED-TO option."))
718              (let* ((array-size (apply #'* dimensions))
719                     (array-data (data-vector-from-inits
720                                  dimensions array-size element-type
721                                  initial-contents initial-element
722                                  initial-element-p)))
723                (if (adjustable-array-p array)
724                    (set-array-header array array-data array-size
725                                  (get-new-fill-pointer array array-size
726                                                        fill-pointer)
727                                  0 dimensions nil)
728                    (if (array-header-p array)
729                        ;; simple multidimensional or single dimensional array
730                        (make-array dimensions
731                                    :element-type element-type
732                                    :initial-contents initial-contents)
733                        array-data))))
734             (displaced-to
735              ;; We already established that no INITIAL-CONTENTS was supplied.
736              (when initial-element
737                (error "The :INITIAL-ELEMENT option may not be specified ~
738                       with :DISPLACED-TO."))
739              (unless (subtypep element-type (array-element-type displaced-to))
740                (error "can't displace an array of type ~S into another of ~
741                        type ~S"
742                       element-type (array-element-type displaced-to)))
743              (let ((displacement (or displaced-index-offset 0))
744                    (array-size (apply #'* dimensions)))
745                (declare (fixnum displacement array-size))
746                (if (< (the fixnum (array-total-size displaced-to))
747                       (the fixnum (+ displacement array-size)))
748                    (error "The :DISPLACED-TO array is too small."))
749                (if (adjustable-array-p array)
750                    ;; None of the original contents appear in adjusted array.
751                    (set-array-header array displaced-to array-size
752                                      (get-new-fill-pointer array array-size
753                                                            fill-pointer)
754                                      displacement dimensions t)
755                    ;; simple multidimensional or single dimensional array
756                    (make-array dimensions
757                                :element-type element-type
758                                :displaced-to displaced-to
759                                :displaced-index-offset
760                                displaced-index-offset))))
761             ((= array-rank 1)
762              (let ((old-length (array-total-size array))
763                    (new-length (car dimensions))
764                    new-data)
765                (declare (fixnum old-length new-length))
766                (with-array-data ((old-data array) (old-start)
767                                  (old-end old-length))
768                  (cond ((or (%array-displaced-p array)
769                             (< old-length new-length))
770                         (setf new-data
771                               (data-vector-from-inits
772                                dimensions new-length element-type
773                                initial-contents initial-element
774                                initial-element-p))
775                         (replace new-data old-data
776                                  :start2 old-start :end2 old-end))
777                        (t (setf new-data
778                                 (shrink-vector old-data new-length))))
779                  (if (adjustable-array-p array)
780                      (set-array-header array new-data new-length
781                                        (get-new-fill-pointer array new-length
782                                                              fill-pointer)
783                                        0 dimensions nil)
784                      new-data))))
785             (t
786              (let ((old-length (%array-available-elements array))
787                    (new-length (apply #'* dimensions)))
788                (declare (fixnum old-length new-length))
789                (with-array-data ((old-data array) (old-start)
790                                  (old-end old-length))
791                  (declare (ignore old-end))
792                  (let ((new-data (if (or (%array-displaced-p array)
793                                          (> new-length old-length))
794                                      (data-vector-from-inits
795                                       dimensions new-length
796                                       element-type () initial-element
797                                       initial-element-p)
798                                      old-data)))
799                    (if (or (zerop old-length) (zerop new-length))
800                        (when initial-element-p (fill new-data initial-element))
801                        (zap-array-data old-data (array-dimensions array)
802                                        old-start
803                                        new-data dimensions new-length
804                                        element-type initial-element
805                                        initial-element-p))
806                    (set-array-header array new-data new-length
807                                      new-length 0 dimensions nil)))))))))
808
809 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
810   (cond ((not fill-pointer)
811          (when (array-has-fill-pointer-p old-array)
812            (when (> (%array-fill-pointer old-array) new-array-size)
813              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
814                     smaller than its fill pointer (~S)"
815                     old-array new-array-size (fill-pointer old-array)))
816            (%array-fill-pointer old-array)))
817         ((not (array-has-fill-pointer-p old-array))
818          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
819                 in ADJUST-ARRAY unless the array (~S) was originally ~
820                 created with a fill pointer"
821                 fill-pointer
822                 old-array))
823         ((numberp fill-pointer)
824          (when (> fill-pointer new-array-size)
825            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
826                   than the new length of the vector (~S)."
827                   fill-pointer new-array-size))
828          fill-pointer)
829         ((eq fill-pointer t)
830          new-array-size)
831         (t
832          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
833                 fill-pointer))))
834
835 (defun shrink-vector (vector new-length)
836   #!+sb-doc
837   "Destructively alter VECTOR, changing its length to NEW-LENGTH, which
838    must be less than or equal to its current length."
839   (declare (vector vector))
840   (unless (array-header-p vector)
841     (macrolet ((frob (name &rest things)
842                  `(etypecase ,name
843                     ,@(mapcar #'(lambda (thing)
844                                   `(,(car thing)
845                                     (fill (truly-the ,(car thing) ,name)
846                                           ,(cadr thing)
847                                           :start new-length)))
848                               things))))
849       (frob vector
850         (simple-vector 0)
851         (simple-base-string #.default-init-char)
852         (simple-bit-vector 0)
853         ((simple-array (unsigned-byte 2) (*)) 0)
854         ((simple-array (unsigned-byte 4) (*)) 0)
855         ((simple-array (unsigned-byte 8) (*)) 0)
856         ((simple-array (unsigned-byte 16) (*)) 0)
857         ((simple-array (unsigned-byte 32) (*)) 0)
858         ((simple-array (signed-byte 8) (*)) 0)
859         ((simple-array (signed-byte 16) (*)) 0)
860         ((simple-array (signed-byte 30) (*)) 0)
861         ((simple-array (signed-byte 32) (*)) 0)
862         ((simple-array single-float (*)) (coerce 0 'single-float))
863         ((simple-array double-float (*)) (coerce 0 'double-float))
864         #!+long-float
865         ((simple-array long-float (*)) (coerce 0 'long-float))
866         ((simple-array (complex single-float) (*))
867          (coerce 0 '(complex single-float)))
868         ((simple-array (complex double-float) (*))
869          (coerce 0 '(complex double-float)))
870         #!+long-float
871         ((simple-array (complex long-float) (*))
872          (coerce 0 '(complex long-float))))))
873   ;; Only arrays have fill-pointers, but vectors have their length
874   ;; parameter in the same place.
875   (setf (%array-fill-pointer vector) new-length)
876   vector)
877
878 (defun set-array-header (array data length fill-pointer displacement dimensions
879                          &optional displacedp)
880   #!+sb-doc
881   "Fills in array header with provided information. Returns array."
882   (setf (%array-data-vector array) data)
883   (setf (%array-available-elements array) length)
884   (cond (fill-pointer
885          (setf (%array-fill-pointer array) fill-pointer)
886          (setf (%array-fill-pointer-p array) t))
887         (t
888          (setf (%array-fill-pointer array) length)
889          (setf (%array-fill-pointer-p array) nil)))
890   (setf (%array-displacement array) displacement)
891   (if (listp dimensions)
892       (dotimes (axis (array-rank array))
893         (declare (type index axis))
894         (setf (%array-dimension array axis) (pop dimensions)))
895       (setf (%array-dimension array 0) dimensions))
896   (setf (%array-displaced-p array) displacedp)
897   array)
898 \f
899 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
900
901 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
902 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice.
903 (defvar *zap-array-data-temp* (make-array 1000 :initial-element t))
904
905 (defun zap-array-data-temp (length element-type initial-element
906                             initial-element-p)
907   (declare (fixnum length))
908   (when (> length (the fixnum (length *zap-array-data-temp*)))
909     (setf *zap-array-data-temp*
910           (make-array length :initial-element t)))
911   (when initial-element-p
912     (unless (typep initial-element element-type)
913       (error "~S can't be used to initialize an array of type ~S."
914              initial-element element-type))
915     (fill (the simple-vector *zap-array-data-temp*) initial-element
916           :end length))
917   *zap-array-data-temp*)
918
919 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
920 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
921 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
922 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
923 ;;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and INITIAL-ELEMENT-P
924 ;;; are used when OLD-DATA and NEW-DATA are EQ; in this case, a
925 ;;; temporary must be used and filled appropriately. When OLD-DATA and
926 ;;; NEW-DATA are not EQ, NEW-DATA has already been filled with any
927 ;;; specified initial-element.
928 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
929                        element-type initial-element initial-element-p)
930   (declare (list old-dims new-dims))
931   (setq old-dims (nreverse old-dims))
932   (setq new-dims (reverse new-dims))
933   (if (eq old-data new-data)
934       (let ((temp (zap-array-data-temp new-length element-type
935                                        initial-element initial-element-p)))
936         (zap-array-data-aux old-data old-dims offset temp new-dims)
937         (dotimes (i new-length) (setf (aref new-data i) (aref temp i))))
938       (zap-array-data-aux old-data old-dims offset new-data new-dims)))
939
940 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
941   (declare (fixnum offset))
942   (let ((limits (mapcar #'(lambda (x y)
943                             (declare (fixnum x y))
944                             (1- (the fixnum (min x y))))
945                         old-dims new-dims)))
946     (macrolet ((bump-index-list (index limits)
947                  `(do ((subscripts ,index (cdr subscripts))
948                        (limits ,limits (cdr limits)))
949                       ((null subscripts) nil)
950                     (cond ((< (the fixnum (car subscripts))
951                               (the fixnum (car limits)))
952                            (rplaca subscripts
953                                    (1+ (the fixnum (car subscripts))))
954                            (return ,index))
955                           (t (rplaca subscripts 0))))))
956       (do ((index (make-list (length old-dims) :initial-element 0)
957                   (bump-index-list index limits)))
958           ((null index))
959         (setf (aref new-data (row-major-index-from-dims index new-dims))
960               (aref old-data
961                     (+ (the fixnum (row-major-index-from-dims index old-dims))
962                        offset)))))))
963
964 ;;; Figure out the row-major-order index of an array reference from a
965 ;;; list of subscripts and a list of dimensions. This is for internal
966 ;;; calls only, and the subscripts and dim-list variables are assumed
967 ;;; to be reversed from what the user supplied.
968 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
969   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
970        (rev-dim-list rev-dim-list (cdr rev-dim-list))
971        (chunk-size 1)
972        (result 0))
973       ((null rev-dim-list) result)
974     (declare (fixnum chunk-size result))
975     (setq result (+ result
976                     (the fixnum (* (the fixnum (car rev-subscripts))
977                                    chunk-size))))
978     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
979 \f
980 ;;;; some bit stuff
981
982 (defun bit-array-same-dimensions-p (array1 array2)
983   (declare (type (array bit) array1 array2))
984   (and (= (array-rank array1)
985           (array-rank array2))
986        (dotimes (index (array-rank array1) t)
987          (when (/= (array-dimension array1 index)
988                    (array-dimension array2 index))
989            (return nil)))))
990
991 (defun pick-result-array (result-bit-array bit-array-1)
992   (case result-bit-array
993     ((t) bit-array-1)
994     ((nil) (make-array (array-dimensions bit-array-1)
995                        :element-type 'bit
996                        :initial-element 0))
997     (t
998      (unless (bit-array-same-dimensions-p bit-array-1
999                                           result-bit-array)
1000        (error "~S and ~S don't have the same dimensions."
1001               bit-array-1 result-bit-array))
1002      result-bit-array)))
1003
1004 (defmacro def-bit-array-op (name function)
1005   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
1006      ,(format nil
1007               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
1008               BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
1009               If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1010               RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1011               All the arrays must have the same rank and dimensions."
1012               (symbol-name function))
1013      (declare (type (array bit) bit-array-1 bit-array-2)
1014               (type (or (array bit) (member t nil)) result-bit-array))
1015      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1016        (error "~S and ~S don't have the same dimensions."
1017               bit-array-1 bit-array-2))
1018      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1019        (if (and (simple-bit-vector-p bit-array-1)
1020                 (simple-bit-vector-p bit-array-2)
1021                 (simple-bit-vector-p result-bit-array))
1022            (locally (declare (optimize (speed 3) (safety 0)))
1023              (,name bit-array-1 bit-array-2 result-bit-array))
1024            (with-array-data ((data1 bit-array-1) (start1) (end1))
1025              (declare (ignore end1))
1026              (with-array-data ((data2 bit-array-2) (start2) (end2))
1027                (declare (ignore end2))
1028                (with-array-data ((data3 result-bit-array) (start3) (end3))
1029                  (do ((index-1 start1 (1+ index-1))
1030                       (index-2 start2 (1+ index-2))
1031                       (index-3 start3 (1+ index-3)))
1032                      ((>= index-3 end3) result-bit-array)
1033                    (declare (type index index-1 index-2 index-3))
1034                    (setf (sbit data3 index-3)
1035                          (logand (,function (sbit data1 index-1)
1036                                             (sbit data2 index-2))
1037                                  1))))))))))
1038
1039 (def-bit-array-op bit-and logand)
1040 (def-bit-array-op bit-ior logior)
1041 (def-bit-array-op bit-xor logxor)
1042 (def-bit-array-op bit-eqv logeqv)
1043 (def-bit-array-op bit-nand lognand)
1044 (def-bit-array-op bit-nor lognor)
1045 (def-bit-array-op bit-andc1 logandc1)
1046 (def-bit-array-op bit-andc2 logandc2)
1047 (def-bit-array-op bit-orc1 logorc1)
1048 (def-bit-array-op bit-orc2 logorc2)
1049
1050 (defun bit-not (bit-array &optional result-bit-array)
1051   #!+sb-doc
1052   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1053   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1054   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1055   created. Both arrays must have the same rank and dimensions."
1056   (declare (type (array bit) bit-array)
1057            (type (or (array bit) (member t nil)) result-bit-array))
1058   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1059     (if (and (simple-bit-vector-p bit-array)
1060              (simple-bit-vector-p result-bit-array))
1061         (locally (declare (optimize (speed 3) (safety 0)))
1062           (bit-not bit-array result-bit-array))
1063         (with-array-data ((src bit-array) (src-start) (src-end))
1064           (declare (ignore src-end))
1065           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1066             (do ((src-index src-start (1+ src-index))
1067                  (dst-index dst-start (1+ dst-index)))
1068                 ((>= dst-index dst-end) result-bit-array)
1069               (declare (type index src-index dst-index))
1070               (setf (sbit dst dst-index)
1071                     (logxor (sbit src src-index) 1))))))))