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