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