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