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