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