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