0.7.5.3:
[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 (defun hairy-data-vector-set (array index new-value)
337   (with-array-data ((vector array) (index index) (end))
338     (declare (ignore end))
339     (etypecase vector .
340                #.(mapcar (lambda (type)
341                            (let ((atype `(simple-array ,type (*))))
342                              `(,atype
343                                (data-vector-set (the ,atype vector)
344                                                 index
345                                                 (the ,type
346                                                   new-value))
347                                ;; For specialized arrays, the return
348                                ;; from data-vector-set would have to
349                                ;; be reboxed to be a (Lisp) return
350                                ;; value; instead, we use the
351                                ;; already-boxed value as the return.
352                                new-value)))
353                          *specialized-array-element-types*))))
354
355 (defun %array-row-major-index (array subscripts
356                                      &optional (invalid-index-error-p t))
357   (declare (array array)
358            (list subscripts))
359   (let ((rank (array-rank array)))
360     (unless (= rank (length subscripts))
361       (error "wrong number of subscripts, ~W, for array of rank ~W"
362              (length subscripts) rank))
363     (if (array-header-p array)
364         (do ((subs (nreverse subscripts) (cdr subs))
365              (axis (1- (array-rank array)) (1- axis))
366              (chunk-size 1)
367              (result 0))
368             ((null subs) result)
369           (declare (list subs) (fixnum axis chunk-size result))
370           (let ((index (car subs))
371                 (dim (%array-dimension array axis)))
372             (declare (fixnum index dim))
373             (unless (< -1 index dim)
374               (if invalid-index-error-p
375                   (error "invalid index ~W~[~;~:; on axis ~:*~W~] in ~S"
376                          index axis array)
377                   (return-from %array-row-major-index nil)))
378             (incf result (* chunk-size index))
379             (setf chunk-size (* chunk-size dim))))
380         (let ((index (first subscripts)))
381           (unless (< -1 index (length (the (simple-array * (*)) array)))
382             (if invalid-index-error-p
383                 (error "invalid index ~W in ~S" index array)
384                 (return-from %array-row-major-index nil)))
385           index))))
386
387 (defun array-in-bounds-p (array &rest subscripts)
388   #!+sb-doc
389   "Return T if the Subscipts are in bounds for the Array, Nil otherwise."
390   (if (%array-row-major-index array subscripts nil)
391       t))
392
393 (defun array-row-major-index (array &rest subscripts)
394   (%array-row-major-index array subscripts))
395
396 (defun aref (array &rest subscripts)
397   #!+sb-doc
398   "Return the element of the Array specified by the Subscripts."
399   (row-major-aref array (%array-row-major-index array subscripts)))
400
401 (defun %aset (array &rest stuff)
402   (let ((subscripts (butlast stuff))
403         (new-value (car (last stuff))))
404     (setf (row-major-aref array (%array-row-major-index array subscripts))
405           new-value)))
406
407 ;;; FIXME: What's supposed to happen with functions
408 ;;; like AREF when we (DEFUN (SETF FOO) ..) when
409 ;;; DEFSETF FOO is also defined? It seems as though the logical
410 ;;; thing to do would be to nuke the macro definition for (SETF FOO)
411 ;;; and replace it with the (SETF FOO) function, issuing a warning,
412 ;;; just as for ordinary functions
413 ;;;  * (LISP-IMPLEMENTATION-VERSION)
414 ;;;  "18a+ release x86-linux 2.4.7 6 November 1998 cvs"
415 ;;;  * (DEFMACRO ZOO (X) `(+ ,X ,X))
416 ;;;  ZOO
417 ;;;  * (DEFUN ZOO (X) (* 3 X))
418 ;;;  Warning: ZOO previously defined as a macro.
419 ;;;  ZOO
420 ;;; But that doesn't seem to be what happens in CMU CL.
421 ;;;
422 ;;; Also, it would be nice to make DESCRIBE FOO tell whether a symbol
423 ;;; has a setf expansion and/or a setf function defined.
424
425 #!-sb-fluid (declaim (inline (setf aref)))
426 (defun (setf aref) (new-value array &rest subscripts)
427   (declare (type array array))
428   (setf (row-major-aref array (%array-row-major-index array subscripts))
429         new-value))
430
431 (defun row-major-aref (array index)
432   #!+sb-doc
433   "Return the element of array corressponding to the row-major index. This is
434    SETF'able."
435   (declare (optimize (safety 1)))
436   (row-major-aref array index))
437
438 (defun %set-row-major-aref (array index new-value)
439   (declare (optimize (safety 1)))
440   (setf (row-major-aref array index) new-value))
441
442 (defun svref (simple-vector index)
443   #!+sb-doc
444   "Return the INDEX'th element of the given Simple-Vector."
445   (declare (optimize (safety 1)))
446   (aref simple-vector index))
447
448 (defun %svset (simple-vector index new)
449   (declare (optimize (safety 1)))
450   (setf (aref simple-vector index) new))
451
452 (defun bit (bit-array &rest subscripts)
453   #!+sb-doc
454   "Return the bit from the BIT-ARRAY at the specified SUBSCRIPTS."
455   (declare (type (array bit) bit-array) (optimize (safety 1)))
456   (row-major-aref bit-array (%array-row-major-index bit-array subscripts)))
457
458 (defun %bitset (bit-array &rest stuff)
459   (declare (type (array bit) bit-array) (optimize (safety 1)))
460   (let ((subscripts (butlast stuff))
461         (new-value (car (last stuff))))
462     (setf (row-major-aref bit-array
463                           (%array-row-major-index bit-array subscripts))
464           new-value)))
465
466 #!-sb-fluid (declaim (inline (setf bit)))
467 (defun (setf bit) (new-value bit-array &rest subscripts)
468   (declare (type (array bit) bit-array) (optimize (safety 1)))
469   (setf (row-major-aref bit-array
470                         (%array-row-major-index bit-array subscripts))
471         new-value))
472
473 (defun sbit (simple-bit-array &rest subscripts)
474   #!+sb-doc
475   "Return the bit from SIMPLE-BIT-ARRAY at the specified SUBSCRIPTS."
476   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
477   (row-major-aref simple-bit-array
478                   (%array-row-major-index simple-bit-array subscripts)))
479
480 ;;; KLUDGE: Not all these things (%SET-ROW-MAJOR-AREF, %SET-FILL-POINTER,
481 ;;; %SET-FDEFINITION, %SCHARSET, %SBITSET..) seem to deserve separate names.
482 ;;; Could we just DEFUN (SETF SBIT) etc. and get rid of the non-ANSI names?
483 ;;; -- WHN 19990911
484 (defun %sbitset (simple-bit-array &rest stuff)
485   (declare (type (simple-array bit) simple-bit-array) (optimize (safety 1)))
486   (let ((subscripts (butlast stuff))
487         (new-value (car (last stuff))))
488     (setf (row-major-aref simple-bit-array
489                           (%array-row-major-index simple-bit-array subscripts))
490           new-value)))
491
492 #!-sb-fluid (declaim (inline (setf sbit)))
493 (defun (setf sbit) (new-value bit-array &rest subscripts)
494   (declare (type (simple-array bit) bit-array) (optimize (safety 1)))
495   (setf (row-major-aref bit-array
496                         (%array-row-major-index bit-array subscripts))
497         new-value))
498 \f
499 ;;;; miscellaneous array properties
500
501 (defun array-element-type (array)
502   #!+sb-doc
503   "Return the type of the elements of the array"
504   (let ((widetag (widetag-of array)))
505     (macrolet ((pick-element-type (&rest stuff)
506                  `(cond ,@(mapcar (lambda (stuff)
507                                     (cons
508                                      (let ((item (car stuff)))
509                                        (cond ((eq item t)
510                                               t)
511                                              ((listp item)
512                                               (cons 'or
513                                                     (mapcar (lambda (x)
514                                                               `(= widetag ,x))
515                                                             item)))
516                                              (t
517                                               `(= widetag ,item))))
518                                      (cdr stuff)))
519                                   stuff))))
520       ;; FIXME: The data here are redundant with
521       ;; *SPECIALIZED-ARRAY-ELEMENT-TYPE-PROPERTIES*.
522       (pick-element-type
523        ((sb!vm:simple-string-widetag sb!vm:complex-string-widetag) 'base-char)
524        ((sb!vm:simple-bit-vector-widetag
525          sb!vm:complex-bit-vector-widetag) 'bit)
526        (sb!vm:simple-vector-widetag t)
527        (sb!vm:simple-array-unsigned-byte-2-widetag '(unsigned-byte 2))
528        (sb!vm:simple-array-unsigned-byte-4-widetag '(unsigned-byte 4))
529        (sb!vm:simple-array-unsigned-byte-8-widetag '(unsigned-byte 8))
530        (sb!vm:simple-array-unsigned-byte-16-widetag '(unsigned-byte 16))
531        (sb!vm:simple-array-unsigned-byte-32-widetag '(unsigned-byte 32))
532        (sb!vm:simple-array-signed-byte-8-widetag '(signed-byte 8))
533        (sb!vm:simple-array-signed-byte-16-widetag '(signed-byte 16))
534        (sb!vm:simple-array-signed-byte-30-widetag '(signed-byte 30))
535        (sb!vm:simple-array-signed-byte-32-widetag '(signed-byte 32))
536        (sb!vm:simple-array-single-float-widetag 'single-float)
537        (sb!vm:simple-array-double-float-widetag 'double-float)
538        #!+long-float
539        (sb!vm:simple-array-long-float-widetag 'long-float)
540        (sb!vm:simple-array-complex-single-float-widetag
541         '(complex single-float))
542        (sb!vm:simple-array-complex-double-float-widetag
543         '(complex double-float))
544        #!+long-float
545        (sb!vm:simple-array-complex-long-float-widetag '(complex long-float))
546        ((sb!vm:simple-array-widetag
547          sb!vm:complex-vector-widetag
548          sb!vm:complex-array-widetag)
549         (with-array-data ((array array) (start) (end))
550           (declare (ignore start end))
551           (array-element-type array)))
552        (t
553         (error 'type-error :datum array :expected-type 'array))))))
554
555 (defun array-rank (array)
556   #!+sb-doc
557   "Return the number of dimensions of ARRAY."
558   (if (array-header-p array)
559       (%array-rank array)
560       1))
561
562 (defun array-dimension (array axis-number)
563   #!+sb-doc
564   "Return the length of dimension AXIS-NUMBER of ARRAY."
565   (declare (array array) (type index axis-number))
566   (cond ((not (array-header-p array))
567          (unless (= axis-number 0)
568            (error "Vector axis is not zero: ~S" axis-number))
569          (length (the (simple-array * (*)) array)))
570         ((>= axis-number (%array-rank array))
571          (error "Axis number ~W is too big; ~S only has ~D dimension~:P."
572                 axis-number array (%array-rank array)))
573         (t
574          (%array-dimension array axis-number))))
575
576 (defun array-dimensions (array)
577   #!+sb-doc
578   "Return a list whose elements are the dimensions of the array"
579   (declare (array array))
580   (if (array-header-p array)
581       (do ((results nil (cons (array-dimension array index) results))
582            (index (1- (array-rank array)) (1- index)))
583           ((minusp index) results))
584       (list (array-dimension array 0))))
585
586 (defun array-total-size (array)
587   #!+sb-doc
588   "Return the total number of elements in the Array."
589   (declare (array array))
590   (if (array-header-p array)
591       (%array-available-elements array)
592       (length (the vector array))))
593
594 (defun array-displacement (array)
595   #!+sb-doc
596   "Return the values of :DISPLACED-TO and :DISPLACED-INDEX-offset
597    options to MAKE-ARRAY, or NIL and 0 if not a displaced array."
598   (declare (type array array))
599   (if (and (array-header-p array) ; if unsimple and
600            (%array-displaced-p array)) ; displaced
601       (values (%array-data-vector array) (%array-displacement array))
602       (values nil 0)))
603
604 (defun adjustable-array-p (array)
605   #!+sb-doc
606   "Return T if (ADJUST-ARRAY ARRAY...) would return an array identical
607    to the argument, this happens for complex arrays."
608   (declare (array array))
609   (not (typep array 'simple-array)))
610 \f
611 ;;;; fill pointer frobbing stuff
612
613 (defun array-has-fill-pointer-p (array)
614   #!+sb-doc
615   "Return T if the given ARRAY has a fill pointer, or NIL otherwise."
616   (declare (array array))
617   (and (array-header-p array) (%array-fill-pointer-p array)))
618
619 (defun fill-pointer (vector)
620   #!+sb-doc
621   "Return the FILL-POINTER of the given VECTOR."
622   (declare (vector vector))
623   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
624       (%array-fill-pointer vector)
625       (error 'simple-type-error
626              :datum vector
627              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
628              :format-control "~S is not an array with a fill pointer."
629              :format-arguments (list vector))))
630
631 (defun %set-fill-pointer (vector new)
632   (declare (vector vector) (fixnum new))
633   (if (and (array-header-p vector) (%array-fill-pointer-p vector))
634       (if (> new (%array-available-elements vector))
635         (error
636          "The new fill pointer, ~S, is larger than the length of the vector."
637          new)
638         (setf (%array-fill-pointer vector) new))
639       (error 'simple-type-error
640              :datum vector
641              :expected-type '(and vector (satisfies array-has-fill-pointer-p))
642              :format-control "~S is not an array with a fill pointer."
643              :format-arguments (list vector))))
644
645 ;;; FIXME: It'd probably make sense to use a MACROLET to share the
646 ;;; guts of VECTOR-PUSH between VECTOR-PUSH-EXTEND. Such a macro
647 ;;; should probably be based on the VECTOR-PUSH-EXTEND code (which is
648 ;;; new ca. sbcl-0.7.0) rather than the VECTOR-PUSH code (which dates
649 ;;; back to CMU CL).
650 (defun vector-push (new-el array)
651   #!+sb-doc
652   "Attempt to set the element of ARRAY designated by its fill pointer
653    to NEW-EL, and increment the fill pointer by one. If the fill pointer is
654    too large, NIL is returned, otherwise the index of the pushed element is
655    returned."
656   (declare (vector array))
657   (let ((fill-pointer (fill-pointer array)))
658     (declare (fixnum fill-pointer))
659     (cond ((= fill-pointer (%array-available-elements array))
660            nil)
661           (t
662            (setf (aref array fill-pointer) new-el)
663            (setf (%array-fill-pointer array) (1+ fill-pointer))
664            fill-pointer))))
665
666 (defun vector-push-extend (new-element
667                            vector
668                            &optional
669                            (extension (1+ (length vector))))
670   (declare (vector vector) (fixnum extension))
671   (let ((fill-pointer (fill-pointer vector)))
672     (declare (fixnum fill-pointer))
673     (when (= fill-pointer (%array-available-elements vector))
674       (adjust-array vector (+ fill-pointer extension)))
675     (setf (aref vector fill-pointer) new-element)
676     (setf (%array-fill-pointer vector) (1+ fill-pointer))
677     fill-pointer))
678
679 (defun vector-pop (array)
680   #!+sb-doc
681   "Decrease the fill pointer by 1 and return the element pointed to by the
682   new fill pointer."
683   (declare (vector array))
684   (let ((fill-pointer (fill-pointer array)))
685     (declare (fixnum fill-pointer))
686     (if (zerop fill-pointer)
687         (error "There is nothing left to pop.")
688         (aref array
689               (setf (%array-fill-pointer array)
690                     (1- fill-pointer))))))
691 \f
692 ;;;; ADJUST-ARRAY
693
694 (defun adjust-array (array dimensions &key
695                            (element-type (array-element-type array))
696                            (initial-element nil initial-element-p)
697                            initial-contents fill-pointer
698                            displaced-to displaced-index-offset)
699   #!+sb-doc
700   "Adjust ARRAY's dimensions to the given DIMENSIONS and stuff."
701   (let ((dimensions (if (listp dimensions) dimensions (list dimensions))))
702     (cond ((/= (the fixnum (length (the list dimensions)))
703                (the fixnum (array-rank array)))
704            (error "The number of dimensions not equal to rank of array."))
705           ((not (subtypep element-type (array-element-type array)))
706            (error "The new element type, ~S, is incompatible with old type."
707                   element-type)))
708     (let ((array-rank (length (the list dimensions))))
709       (declare (fixnum array-rank))
710       (when (and fill-pointer (> array-rank 1))
711         (error "Multidimensional arrays can't have fill pointers."))
712       (cond (initial-contents
713              ;; array former contents replaced by INITIAL-CONTENTS
714              (if (or initial-element-p displaced-to)
715                  (error "INITIAL-CONTENTS may not be specified with ~
716                  the :INITIAL-ELEMENT or :DISPLACED-TO option."))
717              (let* ((array-size (apply #'* dimensions))
718                     (array-data (data-vector-from-inits
719                                  dimensions array-size element-type
720                                  initial-contents initial-element
721                                  initial-element-p)))
722                (if (adjustable-array-p array)
723                    (set-array-header array array-data array-size
724                                  (get-new-fill-pointer array array-size
725                                                        fill-pointer)
726                                  0 dimensions nil)
727                    (if (array-header-p array)
728                        ;; simple multidimensional or single dimensional array
729                        (make-array dimensions
730                                    :element-type element-type
731                                    :initial-contents initial-contents)
732                        array-data))))
733             (displaced-to
734              ;; We already established that no INITIAL-CONTENTS was supplied.
735              (when initial-element
736                (error "The :INITIAL-ELEMENT option may not be specified ~
737                       with :DISPLACED-TO."))
738              (unless (subtypep element-type (array-element-type displaced-to))
739                (error "can't displace an array of type ~S into another of ~
740                        type ~S"
741                       element-type (array-element-type displaced-to)))
742              (let ((displacement (or displaced-index-offset 0))
743                    (array-size (apply #'* dimensions)))
744                (declare (fixnum displacement array-size))
745                (if (< (the fixnum (array-total-size displaced-to))
746                       (the fixnum (+ displacement array-size)))
747                    (error "The :DISPLACED-TO array is too small."))
748                (if (adjustable-array-p array)
749                    ;; None of the original contents appear in adjusted array.
750                    (set-array-header array displaced-to array-size
751                                      (get-new-fill-pointer array array-size
752                                                            fill-pointer)
753                                      displacement dimensions t)
754                    ;; simple multidimensional or single dimensional array
755                    (make-array dimensions
756                                :element-type element-type
757                                :displaced-to displaced-to
758                                :displaced-index-offset
759                                displaced-index-offset))))
760             ((= array-rank 1)
761              (let ((old-length (array-total-size array))
762                    (new-length (car dimensions))
763                    new-data)
764                (declare (fixnum old-length new-length))
765                (with-array-data ((old-data array) (old-start)
766                                  (old-end old-length))
767                  (cond ((or (%array-displaced-p array)
768                             (< old-length new-length))
769                         (setf new-data
770                               (data-vector-from-inits
771                                dimensions new-length element-type
772                                initial-contents initial-element
773                                initial-element-p))
774                         (replace new-data old-data
775                                  :start2 old-start :end2 old-end))
776                        (t (setf new-data
777                                 (shrink-vector old-data new-length))))
778                  (if (adjustable-array-p array)
779                      (set-array-header array new-data new-length
780                                        (get-new-fill-pointer array new-length
781                                                              fill-pointer)
782                                        0 dimensions nil)
783                      new-data))))
784             (t
785              (let ((old-length (%array-available-elements array))
786                    (new-length (apply #'* dimensions)))
787                (declare (fixnum old-length new-length))
788                (with-array-data ((old-data array) (old-start)
789                                  (old-end old-length))
790                  (declare (ignore old-end))
791                  (let ((new-data (if (or (%array-displaced-p array)
792                                          (> new-length old-length))
793                                      (data-vector-from-inits
794                                       dimensions new-length
795                                       element-type () initial-element
796                                       initial-element-p)
797                                      old-data)))
798                    (if (or (zerop old-length) (zerop new-length))
799                        (when initial-element-p (fill new-data initial-element))
800                        (zap-array-data old-data (array-dimensions array)
801                                        old-start
802                                        new-data dimensions new-length
803                                        element-type initial-element
804                                        initial-element-p))
805                    (set-array-header array new-data new-length
806                                      new-length 0 dimensions nil)))))))))
807
808 (defun get-new-fill-pointer (old-array new-array-size fill-pointer)
809   (cond ((not fill-pointer)
810          (when (array-has-fill-pointer-p old-array)
811            (when (> (%array-fill-pointer old-array) new-array-size)
812              (error "cannot ADJUST-ARRAY an array (~S) to a size (~S) that is ~
813                     smaller than its fill pointer (~S)"
814                     old-array new-array-size (fill-pointer old-array)))
815            (%array-fill-pointer old-array)))
816         ((not (array-has-fill-pointer-p old-array))
817          (error "cannot supply a non-NIL value (~S) for :FILL-POINTER ~
818                 in ADJUST-ARRAY unless the array (~S) was originally ~
819                 created with a fill pointer"
820                 fill-pointer
821                 old-array))
822         ((numberp fill-pointer)
823          (when (> fill-pointer new-array-size)
824            (error "can't supply a value for :FILL-POINTER (~S) that is larger ~
825                   than the new length of the vector (~S)"
826                   fill-pointer new-array-size))
827          fill-pointer)
828         ((eq fill-pointer t)
829          new-array-size)
830         (t
831          (error "bogus value for :FILL-POINTER in ADJUST-ARRAY: ~S"
832                 fill-pointer))))
833
834 ;;; Destructively alter VECTOR, changing its length to NEW-LENGTH,
835 ;;; which must be less than or equal to its current length.
836 (defun shrink-vector (vector new-length)
837   (declare (vector vector))
838   (unless (array-header-p vector)
839     (macrolet ((frob (name &rest things)
840                  `(etypecase ,name
841                     ,@(mapcar (lambda (thing)
842                                 (destructuring-bind (type-spec fill-value)
843                                     thing
844                                   `(,type-spec
845                                     (fill (truly-the ,type-spec ,name)
846                                           ,fill-value
847                                           :start new-length))))
848                               things))))
849       ;; FIXME: The associations between vector types and initial
850       ;; values here are redundant with
851       ;; *SPECIALIZED-ARRAY-ELEMENT-TYPE-PROPERTIES*.
852       (frob vector
853         (simple-vector 0)
854         (simple-base-string #.*default-init-char-form*)
855         (simple-bit-vector 0)
856         ((simple-array (unsigned-byte 2) (*)) 0)
857         ((simple-array (unsigned-byte 4) (*)) 0)
858         ((simple-array (unsigned-byte 8) (*)) 0)
859         ((simple-array (unsigned-byte 16) (*)) 0)
860         ((simple-array (unsigned-byte 32) (*)) 0)
861         ((simple-array (signed-byte 8) (*)) 0)
862         ((simple-array (signed-byte 16) (*)) 0)
863         ((simple-array (signed-byte 30) (*)) 0)
864         ((simple-array (signed-byte 32) (*)) 0)
865         ((simple-array single-float (*)) (coerce 0 'single-float))
866         ((simple-array double-float (*)) (coerce 0 'double-float))
867         #!+long-float
868         ((simple-array long-float (*)) (coerce 0 'long-float))
869         ((simple-array (complex single-float) (*))
870          (coerce 0 '(complex single-float)))
871         ((simple-array (complex double-float) (*))
872          (coerce 0 '(complex double-float)))
873         #!+long-float
874         ((simple-array (complex long-float) (*))
875          (coerce 0 '(complex long-float))))))
876   ;; Only arrays have fill-pointers, but vectors have their length
877   ;; parameter in the same place.
878   (setf (%array-fill-pointer vector) new-length)
879   vector)
880
881 ;;; Fill in array header with the provided information, and return the array.
882 (defun set-array-header (array data length fill-pointer displacement dimensions
883                          &optional displacedp)
884   (setf (%array-data-vector array) data)
885   (setf (%array-available-elements array) length)
886   (cond (fill-pointer
887          (setf (%array-fill-pointer array) fill-pointer)
888          (setf (%array-fill-pointer-p array) t))
889         (t
890          (setf (%array-fill-pointer array) length)
891          (setf (%array-fill-pointer-p array) nil)))
892   (setf (%array-displacement array) displacement)
893   (if (listp dimensions)
894       (dotimes (axis (array-rank array))
895         (declare (type index axis))
896         (setf (%array-dimension array axis) (pop dimensions)))
897       (setf (%array-dimension array 0) dimensions))
898   (setf (%array-displaced-p array) displacedp)
899   array)
900 \f
901 ;;;; ZAP-ARRAY-DATA for ADJUST-ARRAY
902
903 ;;; a temporary to be used when OLD-DATA and NEW-DATA are EQ.
904 ;;; KLUDGE: Boy, DYNAMIC-EXTENT would be nice.
905 (defvar *zap-array-data-temp* (make-array 1000 :initial-element t))
906
907 (defun zap-array-data-temp (length element-type initial-element
908                             initial-element-p)
909   (declare (fixnum length))
910   (when (> length (the fixnum (length *zap-array-data-temp*)))
911     (setf *zap-array-data-temp*
912           (make-array length :initial-element t)))
913   (when initial-element-p
914     (unless (typep initial-element element-type)
915       (error "~S can't be used to initialize an array of type ~S."
916              initial-element element-type))
917     (fill (the simple-vector *zap-array-data-temp*) initial-element
918           :end length))
919   *zap-array-data-temp*)
920
921 ;;; This does the grinding work for ADJUST-ARRAY. It zaps the data
922 ;;; from the OLD-DATA in an arrangement specified by the OLD-DIMS to
923 ;;; the NEW-DATA in an arrangement specified by the NEW-DIMS. OFFSET
924 ;;; is a displaced offset to be added to computed indices of OLD-DATA.
925 ;;; NEW-LENGTH, ELEMENT-TYPE, INITIAL-ELEMENT, and INITIAL-ELEMENT-P
926 ;;; are used when OLD-DATA and NEW-DATA are EQ; in this case, a
927 ;;; temporary must be used and filled appropriately. When OLD-DATA and
928 ;;; NEW-DATA are not EQ, NEW-DATA has already been filled with any
929 ;;; specified initial-element.
930 (defun zap-array-data (old-data old-dims offset new-data new-dims new-length
931                        element-type initial-element initial-element-p)
932   (declare (list old-dims new-dims))
933   (setq old-dims (nreverse old-dims))
934   (setq new-dims (reverse new-dims))
935   (if (eq old-data new-data)
936       (let ((temp (zap-array-data-temp new-length element-type
937                                        initial-element initial-element-p)))
938         (zap-array-data-aux old-data old-dims offset temp new-dims)
939         (dotimes (i new-length) (setf (aref new-data i) (aref temp i))))
940       (zap-array-data-aux old-data old-dims offset new-data new-dims)))
941
942 (defun zap-array-data-aux (old-data old-dims offset new-data new-dims)
943   (declare (fixnum offset))
944   (let ((limits (mapcar (lambda (x y)
945                           (declare (fixnum x y))
946                           (1- (the fixnum (min x y))))
947                         old-dims new-dims)))
948     (macrolet ((bump-index-list (index limits)
949                  `(do ((subscripts ,index (cdr subscripts))
950                        (limits ,limits (cdr limits)))
951                       ((null subscripts) nil)
952                     (cond ((< (the fixnum (car subscripts))
953                               (the fixnum (car limits)))
954                            (rplaca subscripts
955                                    (1+ (the fixnum (car subscripts))))
956                            (return ,index))
957                           (t (rplaca subscripts 0))))))
958       (do ((index (make-list (length old-dims) :initial-element 0)
959                   (bump-index-list index limits)))
960           ((null index))
961         (setf (aref new-data (row-major-index-from-dims index new-dims))
962               (aref old-data
963                     (+ (the fixnum (row-major-index-from-dims index old-dims))
964                        offset)))))))
965
966 ;;; Figure out the row-major-order index of an array reference from a
967 ;;; list of subscripts and a list of dimensions. This is for internal
968 ;;; calls only, and the subscripts and dim-list variables are assumed
969 ;;; to be reversed from what the user supplied.
970 (defun row-major-index-from-dims (rev-subscripts rev-dim-list)
971   (do ((rev-subscripts rev-subscripts (cdr rev-subscripts))
972        (rev-dim-list rev-dim-list (cdr rev-dim-list))
973        (chunk-size 1)
974        (result 0))
975       ((null rev-dim-list) result)
976     (declare (fixnum chunk-size result))
977     (setq result (+ result
978                     (the fixnum (* (the fixnum (car rev-subscripts))
979                                    chunk-size))))
980     (setq chunk-size (* chunk-size (the fixnum (car rev-dim-list))))))
981 \f
982 ;;;; some bit stuff
983
984 (defun bit-array-same-dimensions-p (array1 array2)
985   (declare (type (array bit) array1 array2))
986   (and (= (array-rank array1)
987           (array-rank array2))
988        (dotimes (index (array-rank array1) t)
989          (when (/= (array-dimension array1 index)
990                    (array-dimension array2 index))
991            (return nil)))))
992
993 (defun pick-result-array (result-bit-array bit-array-1)
994   (case result-bit-array
995     ((t) bit-array-1)
996     ((nil) (make-array (array-dimensions bit-array-1)
997                        :element-type 'bit
998                        :initial-element 0))
999     (t
1000      (unless (bit-array-same-dimensions-p bit-array-1
1001                                           result-bit-array)
1002        (error "~S and ~S don't have the same dimensions."
1003               bit-array-1 result-bit-array))
1004      result-bit-array)))
1005
1006 (defmacro def-bit-array-op (name function)
1007   `(defun ,name (bit-array-1 bit-array-2 &optional result-bit-array)
1008      ,(format nil
1009               "Perform a bit-wise ~A on the elements of BIT-ARRAY-1 and ~
1010               BIT-ARRAY-2,~%  putting the results in RESULT-BIT-ARRAY. ~
1011               If RESULT-BIT-ARRAY is T,~%  BIT-ARRAY-1 is used. If ~
1012               RESULT-BIT-ARRAY is NIL or omitted, a new array is~%  created. ~
1013               All the arrays must have the same rank and dimensions."
1014               (symbol-name function))
1015      (declare (type (array bit) bit-array-1 bit-array-2)
1016               (type (or (array bit) (member t nil)) result-bit-array))
1017      (unless (bit-array-same-dimensions-p bit-array-1 bit-array-2)
1018        (error "~S and ~S don't have the same dimensions."
1019               bit-array-1 bit-array-2))
1020      (let ((result-bit-array (pick-result-array result-bit-array bit-array-1)))
1021        (if (and (simple-bit-vector-p bit-array-1)
1022                 (simple-bit-vector-p bit-array-2)
1023                 (simple-bit-vector-p result-bit-array))
1024            (locally (declare (optimize (speed 3) (safety 0)))
1025              (,name bit-array-1 bit-array-2 result-bit-array))
1026            (with-array-data ((data1 bit-array-1) (start1) (end1))
1027              (declare (ignore end1))
1028              (with-array-data ((data2 bit-array-2) (start2) (end2))
1029                (declare (ignore end2))
1030                (with-array-data ((data3 result-bit-array) (start3) (end3))
1031                  (do ((index-1 start1 (1+ index-1))
1032                       (index-2 start2 (1+ index-2))
1033                       (index-3 start3 (1+ index-3)))
1034                      ((>= index-3 end3) result-bit-array)
1035                    (declare (type index index-1 index-2 index-3))
1036                    (setf (sbit data3 index-3)
1037                          (logand (,function (sbit data1 index-1)
1038                                             (sbit data2 index-2))
1039                                  1))))))))))
1040
1041 (def-bit-array-op bit-and logand)
1042 (def-bit-array-op bit-ior logior)
1043 (def-bit-array-op bit-xor logxor)
1044 (def-bit-array-op bit-eqv logeqv)
1045 (def-bit-array-op bit-nand lognand)
1046 (def-bit-array-op bit-nor lognor)
1047 (def-bit-array-op bit-andc1 logandc1)
1048 (def-bit-array-op bit-andc2 logandc2)
1049 (def-bit-array-op bit-orc1 logorc1)
1050 (def-bit-array-op bit-orc2 logorc2)
1051
1052 (defun bit-not (bit-array &optional result-bit-array)
1053   #!+sb-doc
1054   "Performs a bit-wise logical NOT on the elements of BIT-ARRAY,
1055   putting the results in RESULT-BIT-ARRAY. If RESULT-BIT-ARRAY is T,
1056   BIT-ARRAY is used. If RESULT-BIT-ARRAY is NIL or omitted, a new array is
1057   created. Both arrays must have the same rank and dimensions."
1058   (declare (type (array bit) bit-array)
1059            (type (or (array bit) (member t nil)) result-bit-array))
1060   (let ((result-bit-array (pick-result-array result-bit-array bit-array)))
1061     (if (and (simple-bit-vector-p bit-array)
1062              (simple-bit-vector-p result-bit-array))
1063         (locally (declare (optimize (speed 3) (safety 0)))
1064           (bit-not bit-array result-bit-array))
1065         (with-array-data ((src bit-array) (src-start) (src-end))
1066           (declare (ignore src-end))
1067           (with-array-data ((dst result-bit-array) (dst-start) (dst-end))
1068             (do ((src-index src-start (1+ src-index))
1069                  (dst-index dst-start (1+ dst-index)))
1070                 ((>= dst-index dst-end) result-bit-array)
1071               (declare (type index src-index dst-index))
1072               (setf (sbit dst dst-index)
1073                     (logxor (sbit src src-index) 1))))))))