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