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