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