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