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