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