automate widetag dispatching
[sbcl.git] / src / code / seq.lisp
1 ;;;; generic SEQUENCEs
2 ;;;;
3 ;;;; KLUDGE: comment from original CMU CL source:
4 ;;;;   Be careful when modifying code. A lot of the structure of the
5 ;;;;   code is affected by the fact that compiler transforms use the
6 ;;;;   lower level support functions. If transforms are written for
7 ;;;;   some sequence operation, note how the END argument is handled
8 ;;;;   in other operations with transforms.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!IMPL")
20 \f
21 ;;;; utilities
22
23 (defun %check-generic-sequence-bounds (seq start end)
24   (let ((length (sb!sequence:length seq)))
25     (if (<= 0 start (or end length) length)
26         (or end length)
27         (sequence-bounding-indices-bad-error seq start end))))
28
29 (eval-when (:compile-toplevel :load-toplevel :execute)
30
31 (defparameter *sequence-keyword-info*
32   ;; (name default supplied-p adjustment new-type)
33   `((count nil
34            nil
35            (etypecase count
36              (null (1- most-positive-fixnum))
37              (fixnum (max 0 count))
38              (integer (if (minusp count)
39                           0
40                           (1- most-positive-fixnum))))
41            (mod #.sb!xc:most-positive-fixnum))
42     ,@(mapcan (lambda (names)
43                 (destructuring-bind (start end length sequence) names
44                   (list
45                    `(,start
46                      0
47                      nil
48                      (if (<= 0 ,start ,length)
49                          ,start
50                          (sequence-bounding-indices-bad-error ,sequence ,start ,end))
51                      index)
52                   `(,end
53                     nil
54                     nil
55                     (if (or (null ,end) (<= ,start ,end ,length))
56                         ;; Defaulting of NIL is done inside the
57                         ;; bodies, for ease of sharing with compiler
58                         ;; transforms.
59                         ;;
60                         ;; FIXME: defend against non-number non-NIL
61                         ;; stuff?
62                         ,end
63                         (sequence-bounding-indices-bad-error ,sequence ,start ,end))
64                     (or null index)))))
65               '((start end length sequence)
66                 (start1 end1 length1 sequence1)
67                 (start2 end2 length2 sequence2)))
68     (key nil
69          nil
70          (and key (%coerce-callable-to-fun key))
71          (or null function))
72     (test #'eql
73           nil
74           (%coerce-callable-to-fun test)
75           function)
76     (test-not nil
77               nil
78               (and test-not (%coerce-callable-to-fun test-not))
79               (or null function))
80     ))
81
82 (sb!xc:defmacro define-sequence-traverser (name args &body body)
83   (multiple-value-bind (body declarations docstring)
84       (parse-body body :doc-string-allowed t)
85     (collect ((new-args) (new-declarations) (adjustments))
86       (dolist (arg args)
87         (case arg
88           ;; FIXME: make this robust.  And clean.
89           ((sequence)
90            (new-args arg)
91            (adjustments '(length (length sequence)))
92            (new-declarations '(type index length)))
93           ((sequence1)
94            (new-args arg)
95            (adjustments '(length1 (length sequence1)))
96            (new-declarations '(type index length1)))
97           ((sequence2)
98            (new-args arg)
99            (adjustments '(length2 (length sequence2)))
100            (new-declarations '(type index length2)))
101           ((function predicate)
102            (new-args arg)
103            (adjustments `(,arg (%coerce-callable-to-fun ,arg))))
104           (t (let ((info (cdr (assoc arg *sequence-keyword-info*))))
105                (cond (info
106                       (destructuring-bind (default supplied-p adjuster type) info
107                         (new-args `(,arg ,default ,@(when supplied-p (list supplied-p))))
108                         (adjustments `(,arg ,adjuster))
109                         (new-declarations `(type ,type ,arg))))
110                      (t (new-args arg)))))))
111       `(defun ,name ,(new-args)
112          ,@(when docstring (list docstring))
113          ,@declarations
114          (let* (,@(adjustments))
115            (declare ,@(new-declarations))
116            ,@body)))))
117
118 ;;; SEQ-DISPATCH does an efficient type-dispatch on the given SEQUENCE.
119 ;;;
120 ;;; FIXME: It might be worth making three cases here, LIST,
121 ;;; SIMPLE-VECTOR, and VECTOR, instead of the current LIST and VECTOR.
122 ;;; It tends to make code run faster but be bigger; some benchmarking
123 ;;; is needed to decide.
124 (sb!xc:defmacro seq-dispatch
125     (sequence list-form array-form &optional other-form)
126   `(if (listp ,sequence)
127        (let ((,sequence (truly-the list ,sequence)))
128          (declare (ignorable ,sequence))
129          ,list-form)
130        ,@(if other-form
131              `((if (arrayp ,sequence)
132                    (let ((,sequence (truly-the vector ,sequence)))
133                      (declare (ignorable ,sequence))
134                      ,array-form)
135                    ,other-form))
136              `((let ((,sequence (truly-the vector ,sequence)))
137                  (declare (ignorable ,sequence))
138                  ,array-form)))))
139
140 (sb!xc:defmacro %make-sequence-like (sequence length)
141   #!+sb-doc
142   "Return a sequence of the same type as SEQUENCE and the given LENGTH."
143   `(seq-dispatch ,sequence
144      (make-list ,length)
145      (make-array ,length :element-type (array-element-type ,sequence))
146      (sb!sequence:make-sequence-like ,sequence ,length)))
147
148 (sb!xc:defmacro bad-sequence-type-error (type-spec)
149   `(error 'simple-type-error
150           :datum ,type-spec
151           :expected-type '(satisfies is-a-valid-sequence-type-specifier-p)
152           :format-control "~S is a bad type specifier for sequences."
153           :format-arguments (list ,type-spec)))
154
155 (sb!xc:defmacro sequence-type-length-mismatch-error (type length)
156   `(error 'simple-type-error
157           :datum ,length
158           :expected-type (cond ((array-type-p ,type)
159                                 `(eql ,(car (array-type-dimensions ,type))))
160                                ((type= ,type (specifier-type 'null))
161                                 '(eql 0))
162                                ((cons-type-p ,type)
163                                 '(integer 1))
164                                (t (bug "weird type in S-T-L-M-ERROR")))
165           ;; FIXME: this format control causes ugly printing.  There's
166           ;; probably some ~<~@:_~> incantation that would make it
167           ;; nicer. -- CSR, 2002-10-18
168           :format-control "The length requested (~S) does not match the type restriction in ~S."
169           :format-arguments (list ,length (type-specifier ,type))))
170
171 (sb!xc:defmacro sequence-type-too-hairy (type-spec)
172   ;; FIXME: Should this be a BUG? I'm inclined to think not; there are
173   ;; words that give some but not total support to this position in
174   ;; ANSI.  Essentially, we are justified in throwing this on
175   ;; e.g. '(OR SIMPLE-VECTOR (VECTOR FIXNUM)), but maybe not (by ANSI)
176   ;; on '(CONS * (CONS * NULL)) -- CSR, 2002-10-18
177
178   ;; On the other hand, I'm not sure it deserves to be a type-error,
179   ;; either. -- bem, 2005-08-10
180   `(error 'simple-program-error
181           :format-control "~S is too hairy for sequence functions."
182           :format-arguments (list ,type-spec)))
183 ) ; EVAL-WHEN
184
185 (defun is-a-valid-sequence-type-specifier-p (type)
186   (let ((type (specifier-type type)))
187     (or (csubtypep type (specifier-type 'list))
188         (csubtypep type (specifier-type 'vector)))))
189
190 ;;; It's possible with some sequence operations to declare the length
191 ;;; of a result vector, and to be safe, we really ought to verify that
192 ;;; the actual result has the declared length.
193 (defun vector-of-checked-length-given-length (vector declared-length)
194   (declare (type vector vector))
195   (declare (type index declared-length))
196   (let ((actual-length (length vector)))
197     (unless (= actual-length declared-length)
198       (error 'simple-type-error
199              :datum vector
200              :expected-type `(vector ,declared-length)
201              :format-control
202              "Vector length (~W) doesn't match declared length (~W)."
203              :format-arguments (list actual-length declared-length))))
204   vector)
205 (defun sequence-of-checked-length-given-type (sequence result-type)
206   (let ((ctype (specifier-type result-type)))
207     (if (not (array-type-p ctype))
208         sequence
209         (let ((declared-length (first (array-type-dimensions ctype))))
210           (if (eq declared-length '*)
211               sequence
212               (vector-of-checked-length-given-length sequence
213                                                      declared-length))))))
214
215 (declaim (ftype (function (sequence index) nil) signal-index-too-large-error))
216 (defun signal-index-too-large-error (sequence index)
217   (let* ((length (length sequence))
218          (max-index (and (plusp length)
219                          (1- length))))
220     (error 'index-too-large-error
221            :datum index
222            :expected-type (if max-index
223                               `(integer 0 ,max-index)
224                               ;; This seems silly, is there something better?
225                               '(integer 0 (0))))))
226
227 (declaim (ftype (function (t t t) nil) sequence-bounding-indices-bad-error))
228 (defun sequence-bounding-indices-bad-error (sequence start end)
229   (let ((size (length sequence)))
230     (error 'bounding-indices-bad-error
231            :datum (cons start end)
232            :expected-type `(cons (integer 0 ,size)
233                                  (integer ,start ,size))
234            :object sequence)))
235
236 (declaim (ftype (function (t t t) nil) array-bounding-indices-bad-error))
237 (defun array-bounding-indices-bad-error (array start end)
238   (let ((size (array-total-size array)))
239     (error 'bounding-indices-bad-error
240            :datum (cons start end)
241            :expected-type `(cons (integer 0 ,size)
242                                  (integer ,start ,size))
243            :object array)))
244
245 (declaim (ftype (function (t) nil) circular-list-error))
246 (defun circular-list-error (list)
247   (let ((*print-circle* t))
248     (error 'simple-type-error
249            :format-control "List is circular:~%  ~S"
250            :format-arguments (list list)
251            :datum list
252            :type '(and list (satisfies list-length)))))
253
254 \f
255 (defun elt (sequence index)
256   #!+sb-doc "Return the element of SEQUENCE specified by INDEX."
257   (seq-dispatch sequence
258                 (do ((count index (1- count))
259                      (list sequence (cdr list)))
260                     ((= count 0)
261                      (if (endp list)
262                          (signal-index-too-large-error sequence index)
263                          (car list)))
264                   (declare (type (integer 0) count)))
265                 (progn
266                   (when (>= index (length sequence))
267                     (signal-index-too-large-error sequence index))
268                   (aref sequence index))
269                 (sb!sequence:elt sequence index)))
270
271 (defun %setelt (sequence index newval)
272   #!+sb-doc "Store NEWVAL as the component of SEQUENCE specified by INDEX."
273   (seq-dispatch sequence
274                 (do ((count index (1- count))
275                      (seq sequence))
276                     ((= count 0) (rplaca seq newval) newval)
277                   (declare (fixnum count))
278                   (if (atom (cdr seq))
279                       (signal-index-too-large-error sequence index)
280                       (setq seq (cdr seq))))
281                 (progn
282                   (when (>= index (length sequence))
283                     (signal-index-too-large-error sequence index))
284                   (setf (aref sequence index) newval))
285                 (setf (sb!sequence:elt sequence index) newval)))
286
287 (defun length (sequence)
288   #!+sb-doc "Return an integer that is the length of SEQUENCE."
289   (seq-dispatch sequence
290                 (length sequence)
291                 (length sequence)
292                 (sb!sequence:length sequence)))
293
294 (defun make-sequence (type length &key (initial-element nil iep))
295   #!+sb-doc
296   "Return a sequence of the given TYPE and LENGTH, with elements initialized
297   to INITIAL-ELEMENT."
298   (declare (fixnum length))
299   (let* ((expanded-type (typexpand type))
300          (adjusted-type
301           (typecase expanded-type
302             (atom (cond
303                     ((eq expanded-type 'string) '(vector character))
304                     ((eq expanded-type 'simple-string) '(simple-array character (*)))
305                     (t type)))
306             (cons (cond
307                     ((eq (car expanded-type) 'string) `(vector character ,@(cdr expanded-type)))
308                     ((eq (car expanded-type) 'simple-string)
309                      `(simple-array character ,(if (cdr expanded-type)
310                                                    (cdr expanded-type)
311                                                    '(*))))
312                     (t type)))
313             (t type)))
314          (type (specifier-type adjusted-type)))
315     (cond ((csubtypep type (specifier-type 'list))
316            (cond
317              ((type= type (specifier-type 'list))
318               (make-list length :initial-element initial-element))
319              ((eq type *empty-type*)
320               (bad-sequence-type-error nil))
321              ((type= type (specifier-type 'null))
322               (if (= length 0)
323                   'nil
324                   (sequence-type-length-mismatch-error type length)))
325              ((cons-type-p type)
326               (multiple-value-bind (min exactp)
327                   (sb!kernel::cons-type-length-info type)
328                 (if exactp
329                     (unless (= length min)
330                       (sequence-type-length-mismatch-error type length))
331                     (unless (>= length min)
332                       (sequence-type-length-mismatch-error type length)))
333                 (make-list length :initial-element initial-element)))
334              ;; We'll get here for e.g. (OR NULL (CONS INTEGER *)),
335              ;; which may seem strange and non-ideal, but then I'd say
336              ;; it was stranger to feed that type in to MAKE-SEQUENCE.
337              (t (sequence-type-too-hairy (type-specifier type)))))
338           ((csubtypep type (specifier-type 'vector))
339            (cond
340              (;; is it immediately obvious what the result type is?
341               (typep type 'array-type)
342               (progn
343                 (aver (= (length (array-type-dimensions type)) 1))
344                 (let* ((etype (type-specifier
345                                (array-type-specialized-element-type type)))
346                        (etype (if (eq etype '*) t etype))
347                        (type-length (car (array-type-dimensions type))))
348                   (unless (or (eq type-length '*)
349                               (= type-length length))
350                     (sequence-type-length-mismatch-error type length))
351                   ;; FIXME: These calls to MAKE-ARRAY can't be
352                   ;; open-coded, as the :ELEMENT-TYPE argument isn't
353                   ;; constant.  Probably we ought to write a
354                   ;; DEFTRANSFORM for MAKE-SEQUENCE.  -- CSR,
355                   ;; 2002-07-22
356                   (if iep
357                       (make-array length :element-type etype
358                                   :initial-element initial-element)
359                       (make-array length :element-type etype)))))
360              (t (sequence-type-too-hairy (type-specifier type)))))
361           ((and (csubtypep type (specifier-type 'sequence))
362                 (find-class adjusted-type nil))
363            (let* ((class (find-class adjusted-type nil)))
364              (unless (sb!mop:class-finalized-p class)
365                (sb!mop:finalize-inheritance class))
366              (if iep
367                  (sb!sequence:make-sequence-like
368                   (sb!mop:class-prototype class) length
369                   :initial-element initial-element)
370                  (sb!sequence:make-sequence-like
371                   (sb!mop:class-prototype class) length))))
372           (t (bad-sequence-type-error (type-specifier type))))))
373 \f
374 ;;;; SUBSEQ
375 ;;;;
376
377 (define-array-dispatch vector-subseq-dispatch (array start end)
378   (declare (optimize speed (safety 0)))
379   (declare (type index start end))
380   (subseq array start end))
381
382 ;;;; The support routines for SUBSEQ are used by compiler transforms,
383 ;;;; so we worry about dealing with END being supplied or defaulting
384 ;;;; to NIL at this level.
385
386 (defun vector-subseq* (sequence start end)
387   (declare (type vector sequence))
388   (declare (type index start)
389            (type (or null index) end)
390            (optimize speed))
391   (with-array-data ((data sequence)
392                     (start start)
393                     (end end)
394                     :check-fill-pointer t
395                     :force-inline t)
396     (vector-subseq-dispatch data start end)))
397
398 (defun list-subseq* (sequence start end)
399   (declare (type list sequence)
400            (type unsigned-byte start)
401            (type (or null unsigned-byte) end))
402   (flet ((oops ()
403            (sequence-bounding-indices-bad-error sequence start end)))
404     (let ((pointer sequence))
405       (unless (zerop start)
406         ;; If START > 0 the list cannot be empty. So CDR down to
407         ;; it START-1 times, check that we still have something, then
408         ;; CDR the final time.
409         ;;
410         ;; If START was zero, the list may be empty if END is NIL or
411         ;; also zero.
412         (when (> start 1)
413           (setf pointer (nthcdr (1- start) pointer)))
414         (if pointer
415             (pop pointer)
416             (oops)))
417       (if end
418           (let ((n (- end start)))
419             (declare (integer n))
420             (when (minusp n)
421               (oops))
422             (when (plusp n)
423               (let* ((head (list nil))
424                      (tail head))
425                 (macrolet ((pop-one ()
426                              `(let ((tmp (list (pop pointer))))
427                                 (setf (cdr tail) tmp
428                                       tail tmp))))
429                   ;; Bignum case
430                   (loop until (fixnump n)
431                         do (pop-one)
432                            (decf n))
433                   ;; Fixnum case, but leave last element, so we should
434                   ;; still have something left in the sequence.
435                   (let ((m (1- n)))
436                     (declare (fixnum m))
437                     (loop repeat m
438                           do (pop-one)))
439                   (unless pointer
440                     (oops))
441                   ;; OK, pop the last one.
442                   (pop-one)
443                   (cdr head)))))
444             (loop while pointer
445                   collect (pop pointer))))))
446
447 (defun subseq (sequence start &optional end)
448   #!+sb-doc
449   "Return a copy of a subsequence of SEQUENCE starting with element number
450    START and continuing to the end of SEQUENCE or the optional END."
451   (seq-dispatch sequence
452     (list-subseq* sequence start end)
453     (vector-subseq* sequence start end)
454     (sb!sequence:subseq sequence start end)))
455 \f
456 ;;;; COPY-SEQ
457
458 (defun copy-seq (sequence)
459   #!+sb-doc "Return a copy of SEQUENCE which is EQUAL to SEQUENCE but not EQ."
460   (seq-dispatch sequence
461     (list-copy-seq* sequence)
462     (vector-subseq* sequence 0 nil)
463     (sb!sequence:copy-seq sequence)))
464
465 (defun list-copy-seq* (sequence)
466   (!copy-list-macro sequence :check-proper-list t))
467 \f
468 ;;;; FILL
469
470 (defun list-fill* (sequence item start end)
471   (declare (type list sequence)
472            (type unsigned-byte start)
473            (type (or null unsigned-byte) end))
474   (flet ((oops ()
475            (sequence-bounding-indices-bad-error sequence start end)))
476     (let ((pointer sequence))
477       (unless (zerop start)
478         ;; If START > 0 the list cannot be empty. So CDR down to it
479         ;; START-1 times, check that we still have something, then CDR
480         ;; the final time.
481         ;;
482         ;; If START was zero, the list may be empty if END is NIL or
483         ;; also zero.
484         (unless (= start 1)
485           (setf pointer (nthcdr (1- start) pointer)))
486         (if pointer
487             (pop pointer)
488             (oops)))
489       (if end
490           (let ((n (- end start)))
491             (declare (integer n))
492             (when (minusp n)
493               (oops))
494             (when (plusp n)
495               (loop repeat n
496                     do (setf pointer (cdr (rplaca pointer item))))))
497           (loop while pointer
498                 do (setf pointer (cdr (rplaca pointer item)))))))
499   sequence)
500
501 (defun vector-fill* (sequence item start end)
502   (with-array-data ((data sequence)
503                     (start start)
504                     (end end)
505                     :force-inline t
506                     :check-fill-pointer t)
507     (let ((setter (!find-data-vector-setter data)))
508       (declare (optimize (speed 3) (safety 0)))
509       (do ((index start (1+ index)))
510           ((= index end) sequence)
511         (declare (index index))
512         (funcall setter data index item)))))
513
514 (defun string-fill* (sequence item start end)
515   (declare (string sequence))
516   (with-array-data ((data sequence)
517                     (start start)
518                     (end end)
519                     :force-inline t
520                     :check-fill-pointer t)
521     ;; DEFTRANSFORM for FILL will turn these into
522     ;; calls to UB*-BASH-FILL.
523     (etypecase data
524       #!+sb-unicode
525       ((simple-array character (*))
526        (let ((item (locally (declare (optimize (safety 3)))
527                      (the character item))))
528          (fill data item :start start :end end)))
529       ((simple-array base-char (*))
530        (let ((item (locally (declare (optimize (safety 3)))
531                      (the base-char item))))
532          (fill data item :start start :end end))))))
533
534 (defun fill (sequence item &key (start 0) end)
535   #!+sb-doc
536   "Replace the specified elements of SEQUENCE with ITEM."
537   (seq-dispatch sequence
538    (list-fill* sequence item start end)
539    (vector-fill* sequence item start end)
540    (sb!sequence:fill sequence item
541                      :start start
542                      :end (%check-generic-sequence-bounds sequence start end))))
543 \f
544 ;;;; REPLACE
545
546 (eval-when (:compile-toplevel :execute)
547
548 ;;; If we are copying around in the same vector, be careful not to copy the
549 ;;; same elements over repeatedly. We do this by copying backwards.
550 (sb!xc:defmacro mumble-replace-from-mumble ()
551   `(if (and (eq target-sequence source-sequence) (> target-start source-start))
552        (let ((nelts (min (- target-end target-start)
553                          (- source-end source-start))))
554          (do ((target-index (+ (the fixnum target-start) (the fixnum nelts) -1)
555                             (1- target-index))
556               (source-index (+ (the fixnum source-start) (the fixnum nelts) -1)
557                             (1- source-index)))
558              ((= target-index (the fixnum (1- target-start))) target-sequence)
559            (declare (fixnum target-index source-index))
560            ;; disable bounds checking
561            (declare (optimize (safety 0)))
562            (setf (aref target-sequence target-index)
563                  (aref source-sequence source-index))))
564        (do ((target-index target-start (1+ target-index))
565             (source-index source-start (1+ source-index)))
566            ((or (= target-index (the fixnum target-end))
567                 (= source-index (the fixnum source-end)))
568             target-sequence)
569          (declare (fixnum target-index source-index))
570          ;; disable bounds checking
571          (declare (optimize (safety 0)))
572          (setf (aref target-sequence target-index)
573                (aref source-sequence source-index)))))
574
575 (sb!xc:defmacro list-replace-from-list ()
576   `(if (and (eq target-sequence source-sequence) (> target-start source-start))
577        (let ((new-elts (subseq source-sequence source-start
578                                (+ (the fixnum source-start)
579                                   (the fixnum
580                                        (min (- (the fixnum target-end)
581                                                (the fixnum target-start))
582                                             (- (the fixnum source-end)
583                                                (the fixnum source-start))))))))
584          (do ((n new-elts (cdr n))
585               (o (nthcdr target-start target-sequence) (cdr o)))
586              ((null n) target-sequence)
587            (rplaca o (car n))))
588        (do ((target-index target-start (1+ target-index))
589             (source-index source-start (1+ source-index))
590             (target-sequence-ref (nthcdr target-start target-sequence)
591                                  (cdr target-sequence-ref))
592             (source-sequence-ref (nthcdr source-start source-sequence)
593                                  (cdr source-sequence-ref)))
594            ((or (= target-index (the fixnum target-end))
595                 (= source-index (the fixnum source-end))
596                 (null target-sequence-ref) (null source-sequence-ref))
597             target-sequence)
598          (declare (fixnum target-index source-index))
599          (rplaca target-sequence-ref (car source-sequence-ref)))))
600
601 (sb!xc:defmacro list-replace-from-mumble ()
602   `(do ((target-index target-start (1+ target-index))
603         (source-index source-start (1+ source-index))
604         (target-sequence-ref (nthcdr target-start target-sequence)
605                              (cdr target-sequence-ref)))
606        ((or (= target-index (the fixnum target-end))
607             (= source-index (the fixnum source-end))
608             (null target-sequence-ref))
609         target-sequence)
610      (declare (fixnum source-index target-index))
611      (rplaca target-sequence-ref (aref source-sequence source-index))))
612
613 (sb!xc:defmacro mumble-replace-from-list ()
614   `(do ((target-index target-start (1+ target-index))
615         (source-index source-start (1+ source-index))
616         (source-sequence (nthcdr source-start source-sequence)
617                          (cdr source-sequence)))
618        ((or (= target-index (the fixnum target-end))
619             (= source-index (the fixnum source-end))
620             (null source-sequence))
621         target-sequence)
622      (declare (fixnum target-index source-index))
623      (setf (aref target-sequence target-index) (car source-sequence))))
624
625 ) ; EVAL-WHEN
626
627 ;;;; The support routines for REPLACE are used by compiler transforms, so we
628 ;;;; worry about dealing with END being supplied or defaulting to NIL
629 ;;;; at this level.
630
631 (defun list-replace-from-list* (target-sequence source-sequence target-start
632                                 target-end source-start source-end)
633   (when (null target-end) (setq target-end (length target-sequence)))
634   (when (null source-end) (setq source-end (length source-sequence)))
635   (list-replace-from-list))
636
637 (defun list-replace-from-vector* (target-sequence source-sequence target-start
638                                   target-end source-start source-end)
639   (when (null target-end) (setq target-end (length target-sequence)))
640   (when (null source-end) (setq source-end (length source-sequence)))
641   (list-replace-from-mumble))
642
643 (defun vector-replace-from-list* (target-sequence source-sequence target-start
644                                   target-end source-start source-end)
645   (when (null target-end) (setq target-end (length target-sequence)))
646   (when (null source-end) (setq source-end (length source-sequence)))
647   (mumble-replace-from-list))
648
649 (defun vector-replace-from-vector* (target-sequence source-sequence
650                                     target-start target-end source-start
651                                     source-end)
652   (when (null target-end) (setq target-end (length target-sequence)))
653   (when (null source-end) (setq source-end (length source-sequence)))
654   (mumble-replace-from-mumble))
655
656 #!+sb-unicode
657 (defun simple-character-string-replace-from-simple-character-string*
658     (target-sequence source-sequence
659      target-start target-end source-start source-end)
660   (declare (type (simple-array character (*)) target-sequence source-sequence))
661   (when (null target-end) (setq target-end (length target-sequence)))
662   (when (null source-end) (setq source-end (length source-sequence)))
663   (mumble-replace-from-mumble))
664
665 (define-sequence-traverser replace
666     (sequence1 sequence2 &rest args &key start1 end1 start2 end2)
667   #!+sb-doc
668   "Destructively modifies SEQUENCE1 by copying successive elements
669 into it from the SEQUENCE2.
670
671 Elements are copied to the subseqeuence bounded by START1 and END1,
672 from the subsequence bounded by START2 and END2. If these subsequences
673 are not of the same length, then the shorter length determines how
674 many elements are copied."
675   (declare (truly-dynamic-extent args))
676   (let* (;; KLUDGE: absent either rewriting FOO-REPLACE-FROM-BAR, or
677          ;; excessively polluting DEFINE-SEQUENCE-TRAVERSER, we rebind
678          ;; these things here so that legacy code gets the names it's
679          ;; expecting.  We could use &AUX instead :-/.
680          (target-sequence sequence1)
681          (source-sequence sequence2)
682          (target-start start1)
683          (source-start start2)
684          (target-end (or end1 length1))
685          (source-end (or end2 length2)))
686     (seq-dispatch target-sequence
687       (seq-dispatch source-sequence
688         (list-replace-from-list)
689         (list-replace-from-mumble)
690         (apply #'sb!sequence:replace sequence1 sequence2 args))
691       (seq-dispatch source-sequence
692         (mumble-replace-from-list)
693         (mumble-replace-from-mumble)
694         (apply #'sb!sequence:replace sequence1 sequence2 args))
695       (apply #'sb!sequence:replace sequence1 sequence2 args))))
696 \f
697 ;;;; REVERSE
698
699 (eval-when (:compile-toplevel :execute)
700
701 (sb!xc:defmacro vector-reverse (sequence)
702   `(let ((length (length ,sequence)))
703      (declare (fixnum length))
704      (do ((forward-index 0 (1+ forward-index))
705           (backward-index (1- length) (1- backward-index))
706           (new-sequence (%make-sequence-like sequence length)))
707          ((= forward-index length) new-sequence)
708        (declare (fixnum forward-index backward-index))
709        (setf (aref new-sequence forward-index)
710              (aref ,sequence backward-index)))))
711
712 (sb!xc:defmacro list-reverse-macro (sequence)
713   `(do ((new-list ()))
714        ((endp ,sequence) new-list)
715      (push (pop ,sequence) new-list)))
716
717 ) ; EVAL-WHEN
718
719 (defun reverse (sequence)
720   #!+sb-doc
721   "Return a new sequence containing the same elements but in reverse order."
722   (seq-dispatch sequence
723     (list-reverse* sequence)
724     (vector-reverse* sequence)
725     (sb!sequence:reverse sequence)))
726
727 ;;; internal frobs
728
729 (defun list-reverse* (sequence)
730   (list-reverse-macro sequence))
731
732 (defun vector-reverse* (sequence)
733   (vector-reverse sequence))
734 \f
735 ;;;; NREVERSE
736
737 (eval-when (:compile-toplevel :execute)
738
739 (sb!xc:defmacro vector-nreverse (sequence)
740   `(let ((length (length (the vector ,sequence))))
741      (when (>= length 2)
742        (do ((left-index 0 (1+ left-index))
743             (right-index (1- length) (1- right-index)))
744            ((<= right-index left-index))
745          (declare (type index left-index right-index))
746          (rotatef (aref ,sequence left-index)
747                   (aref ,sequence right-index))))
748      ,sequence))
749
750 (sb!xc:defmacro list-nreverse-macro (list)
751   `(do ((1st (cdr ,list) (if (endp 1st) 1st (cdr 1st)))
752         (2nd ,list 1st)
753         (3rd '() 2nd))
754        ((atom 2nd) 3rd)
755      (rplacd 2nd 3rd)))
756
757 ) ; EVAL-WHEN
758
759 (defun list-nreverse* (sequence)
760   (list-nreverse-macro sequence))
761
762 (defun vector-nreverse* (sequence)
763   (vector-nreverse sequence))
764
765 (defun nreverse (sequence)
766   #!+sb-doc
767   "Return a sequence of the same elements in reverse order; the argument
768    is destroyed."
769   (seq-dispatch sequence
770     (list-nreverse* sequence)
771     (vector-nreverse* sequence)
772     (sb!sequence:nreverse sequence)))
773 \f
774 ;;;; CONCATENATE
775
776 (defmacro sb!sequence:dosequence ((e sequence &optional return) &body body)
777   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
778     (let ((s sequence)
779           (sequence (gensym "SEQUENCE")))
780       `(block nil
781         (let ((,sequence ,s))
782           (seq-dispatch ,sequence
783             (dolist (,e ,sequence ,return) ,@body)
784             (dovector (,e ,sequence ,return) ,@body)
785             (multiple-value-bind (state limit from-end step endp elt)
786                 (sb!sequence:make-sequence-iterator ,sequence)
787               (do ((state state (funcall step ,sequence state from-end)))
788                   ((funcall endp ,sequence state limit from-end)
789                    (let ((,e nil))
790                      ,@(filter-dolist-declarations decls)
791                      ,e
792                      ,return))
793                 (let ((,e (funcall elt ,sequence state)))
794                   ,@decls
795                   (tagbody
796                      ,@forms))))))))))
797 \f
798 (defun concatenate (output-type-spec &rest sequences)
799   #!+sb-doc
800   "Return a new sequence of all the argument sequences concatenated together
801   which shares no structure with the original argument sequences of the
802   specified OUTPUT-TYPE-SPEC."
803   (flet ((concat-to-list* (sequences)
804            (let ((result (list nil)))
805              (do ((sequences sequences (cdr sequences))
806                   (splice result))
807                  ((null sequences) (cdr result))
808                (let ((sequence (car sequences)))
809                  (sb!sequence:dosequence (e sequence)
810                    (setq splice (cdr (rplacd splice (list e)))))))))
811          (concat-to-simple* (type-spec sequences)
812            (do ((seqs sequences (cdr seqs))
813                 (total-length 0)
814                 (lengths ()))
815                ((null seqs)
816                 (do ((sequences sequences (cdr sequences))
817                      (lengths lengths (cdr lengths))
818                      (index 0)
819                      (result (make-sequence type-spec total-length)))
820                     ((= index total-length) result)
821                   (declare (fixnum index))
822                   (let ((sequence (car sequences)))
823                     (sb!sequence:dosequence (e sequence)
824                       (setf (aref result index) e)
825                       (incf index)))))
826              (let ((length (length (car seqs))))
827                (declare (fixnum length))
828                (setq lengths (nconc lengths (list length)))
829                (setq total-length (+ total-length length))))))
830     (let ((type (specifier-type output-type-spec)))
831       (cond
832         ((csubtypep type (specifier-type 'list))
833          (cond
834            ((type= type (specifier-type 'list))
835             (concat-to-list* sequences))
836            ((eq type *empty-type*)
837             (bad-sequence-type-error nil))
838            ((type= type (specifier-type 'null))
839             (if (every (lambda (x) (or (null x)
840                                        (and (vectorp x) (= (length x) 0))))
841                        sequences)
842                 'nil
843                 (sequence-type-length-mismatch-error
844                  type
845                  ;; FIXME: circular list issues.
846                  (reduce #'+ sequences :key #'length))))
847            ((cons-type-p type)
848             (multiple-value-bind (min exactp)
849                 (sb!kernel::cons-type-length-info type)
850               (let ((length (reduce #'+ sequences :key #'length)))
851                 (if exactp
852                     (unless (= length min)
853                       (sequence-type-length-mismatch-error type length))
854                     (unless (>= length min)
855                       (sequence-type-length-mismatch-error type length)))
856                 (concat-to-list* sequences))))
857            (t (sequence-type-too-hairy (type-specifier type)))))
858         ((csubtypep type (specifier-type 'vector))
859          (concat-to-simple* output-type-spec sequences))
860         ((and (csubtypep type (specifier-type 'sequence))
861               (find-class output-type-spec nil))
862          (coerce (concat-to-simple* 'vector sequences) output-type-spec))
863         (t
864          (bad-sequence-type-error output-type-spec))))))
865
866 ;;; Efficient out-of-line concatenate for strings. Compiler transforms
867 ;;; CONCATENATE 'STRING &co into these.
868 (macrolet ((def (name element-type)
869              `(defun ,name (&rest sequences)
870                 (declare (dynamic-extent sequences)
871                          (optimize speed)
872                          (optimize (sb!c::insert-array-bounds-checks 0)))
873                 (let* ((lengths (mapcar #'length sequences))
874                        (result (make-array (the integer (apply #'+ lengths))
875                                            :element-type ',element-type))
876                        (start 0))
877                   (declare (index start))
878                   (dolist (seq sequences)
879                     (string-dispatch
880                         ((simple-array character (*))
881                          (simple-array base-char (*))
882                          t)
883                         seq
884                       (replace result seq :start1 start))
885                     (incf start (the index (pop lengths))))
886                   result))))
887   (def %concatenate-to-string character)
888   (def %concatenate-to-base-string base-char))
889 \f
890 ;;;; MAP and MAP-INTO
891
892 ;;; helper functions to handle arity-1 subcases of MAP
893 (declaim (ftype (function (function sequence) list) %map-list-arity-1))
894 (declaim (ftype (function (function sequence) simple-vector)
895                 %map-simple-vector-arity-1))
896 (defun %map-to-list-arity-1 (fun sequence)
897   (let ((reversed-result nil)
898         (really-fun (%coerce-callable-to-fun fun)))
899     (sb!sequence:dosequence (element sequence)
900       (push (funcall really-fun element)
901             reversed-result))
902     (nreverse reversed-result)))
903 (defun %map-to-simple-vector-arity-1 (fun sequence)
904   (let ((result (make-array (length sequence)))
905         (index 0)
906         (really-fun (%coerce-callable-to-fun fun)))
907     (declare (type index index))
908     (sb!sequence:dosequence (element sequence)
909       (setf (aref result index)
910             (funcall really-fun element))
911       (incf index))
912     result))
913 (defun %map-for-effect-arity-1 (fun sequence)
914   (let ((really-fun (%coerce-callable-to-fun fun)))
915     (sb!sequence:dosequence (element sequence)
916       (funcall really-fun element)))
917   nil)
918
919 (declaim (maybe-inline %map-for-effect))
920 (defun %map-for-effect (fun sequences)
921   (declare (type function fun) (type list sequences))
922   (let ((%sequences sequences)
923         (%iters (mapcar (lambda (s)
924                           (seq-dispatch s
925                             s
926                             0
927                             (multiple-value-list
928                              (sb!sequence:make-sequence-iterator s))))
929                         sequences))
930         (%apply-args (make-list (length sequences))))
931     ;; this is almost efficient (except in the general case where we
932     ;; trampoline to MAKE-SEQUENCE-ITERATOR; if we had DX allocation
933     ;; of MAKE-LIST, the whole of %MAP would be cons-free.
934     (declare (type list %sequences %iters %apply-args))
935     (loop
936      (do ((in-sequences  %sequences  (cdr in-sequences))
937           (in-iters      %iters      (cdr in-iters))
938           (in-apply-args %apply-args (cdr in-apply-args)))
939          ((null in-sequences) (apply fun %apply-args))
940        (let ((i (car in-iters)))
941          (declare (type (or list index) i))
942          (cond
943            ((listp (car in-sequences))
944             (if (null i)
945                 (return-from %map-for-effect nil)
946                 (setf (car in-apply-args) (car i)
947                       (car in-iters) (cdr i))))
948            ((typep i 'index)
949             (let ((v (the vector (car in-sequences))))
950               (if (>= i (length v))
951                   (return-from %map-for-effect nil)
952                   (setf (car in-apply-args) (aref v i)
953                         (car in-iters) (1+ i)))))
954            (t
955             (destructuring-bind (state limit from-end step endp elt &rest ignore)
956                 i
957               (declare (type function step endp elt)
958                        (ignore ignore))
959               (let ((s (car in-sequences)))
960                 (if (funcall endp s state limit from-end)
961                     (return-from %map-for-effect nil)
962                     (progn
963                       (setf (car in-apply-args) (funcall elt s state))
964                       (setf (caar in-iters) (funcall step s state from-end)))))))))))))
965 (defun %map-to-list (fun sequences)
966   (declare (type function fun)
967            (type list sequences))
968   (let ((result nil))
969     (flet ((f (&rest args)
970              (declare (truly-dynamic-extent args))
971              (push (apply fun args) result)))
972       (declare (truly-dynamic-extent #'f))
973       (%map-for-effect #'f sequences))
974     (nreverse result)))
975 (defun %map-to-vector (output-type-spec fun sequences)
976   (declare (type function fun)
977            (type list sequences))
978   (let ((min-len 0))
979     (flet ((f (&rest args)
980              (declare (truly-dynamic-extent args))
981              (declare (ignore args))
982              (incf min-len)))
983       (declare (truly-dynamic-extent #'f))
984       (%map-for-effect #'f sequences))
985     (let ((result (make-sequence output-type-spec min-len))
986           (i 0))
987       (declare (type (simple-array * (*)) result))
988       (flet ((f (&rest args)
989                (declare (truly-dynamic-extent args))
990                (setf (aref result i) (apply fun args))
991                (incf i)))
992         (declare (truly-dynamic-extent #'f))
993         (%map-for-effect #'f sequences))
994       result)))
995 (defun %map-to-sequence (result-type fun sequences)
996   (declare (type function fun)
997            (type list sequences))
998   (let ((min-len 0))
999     (flet ((f (&rest args)
1000              (declare (truly-dynamic-extent args))
1001              (declare (ignore args))
1002              (incf min-len)))
1003       (declare (truly-dynamic-extent #'f))
1004       (%map-for-effect #'f sequences))
1005     (let ((result (make-sequence result-type min-len)))
1006       (multiple-value-bind (state limit from-end step endp elt setelt)
1007           (sb!sequence:make-sequence-iterator result)
1008         (declare (ignore limit endp elt))
1009         (flet ((f (&rest args)
1010                  (declare (truly-dynamic-extent args))
1011                  (funcall setelt (apply fun args) result state)
1012                  (setq state (funcall step result state from-end))))
1013           (declare (truly-dynamic-extent #'f))
1014           (%map-for-effect #'f sequences)))
1015       result)))
1016
1017 ;;; %MAP is just MAP without the final just-to-be-sure check that
1018 ;;; length of the output sequence matches any length specified
1019 ;;; in RESULT-TYPE.
1020 (defun %map (result-type function first-sequence &rest more-sequences)
1021   (let ((really-fun (%coerce-callable-to-fun function))
1022         (type (specifier-type result-type)))
1023     ;; Handle one-argument MAP NIL specially, using ETYPECASE to turn
1024     ;; it into something which can be DEFTRANSFORMed away. (It's
1025     ;; fairly important to handle this case efficiently, since
1026     ;; quantifiers like SOME are transformed into this case, and since
1027     ;; there's no consing overhead to dwarf our inefficiency.)
1028     (if (and (null more-sequences)
1029              (null result-type))
1030         (%map-for-effect-arity-1 really-fun first-sequence)
1031         ;; Otherwise, use the industrial-strength full-generality
1032         ;; approach, consing O(N-ARGS) temporary storage (which can have
1033         ;; DYNAMIC-EXTENT), then using O(N-ARGS * RESULT-LENGTH) time.
1034         (let ((sequences (cons first-sequence more-sequences)))
1035           (cond
1036             ((eq type *empty-type*) (%map-for-effect really-fun sequences))
1037             ((csubtypep type (specifier-type 'list))
1038              (%map-to-list really-fun sequences))
1039             ((csubtypep type (specifier-type 'vector))
1040              (%map-to-vector result-type really-fun sequences))
1041             ((and (csubtypep type (specifier-type 'sequence))
1042                   (find-class result-type nil))
1043              (%map-to-sequence result-type really-fun sequences))
1044             (t
1045              (bad-sequence-type-error result-type)))))))
1046
1047 (defun map (result-type function first-sequence &rest more-sequences)
1048   (apply #'%map
1049          result-type
1050          function
1051          first-sequence
1052          more-sequences))
1053
1054 ;;; Uses the machinery of (MAP NIL ...). For non-vectors we avoid
1055 ;;; computing the length of the result sequence since we can detect
1056 ;;; the end during mapping (if MAP even gets that far).
1057 (defun map-into (result-sequence function &rest sequences)
1058   (declare (truly-dynamic-extent sequences))
1059   (let ((really-fun (%coerce-callable-to-fun function)))
1060     ;; For each result type, define a mapping function which is
1061     ;; responsible for replacing RESULT-SEQUENCE elements and for
1062     ;; terminating itself if the end of RESULT-SEQUENCE is reached.
1063     ;;
1064     ;; The mapping function is defined with the MAP-LAMBDA macrolet,
1065     ;; whose syntax matches that of LAMBDA.
1066     (macrolet ((map-lambda (params &body body)
1067                  `(flet ((f ,params ,@body))
1068                     (declare (truly-dynamic-extent #'f))
1069                     ;; Note (MAP-INTO SEQ (LAMBDA () ...)) is a
1070                     ;; different animal, hence the awkward flip
1071                     ;; between MAP and LOOP.
1072                     (if sequences
1073                         (apply #'map nil #'f sequences)
1074                         (loop (f))))))
1075       ;; Optimize MAP-LAMBDAs since they are the inner loops. Because
1076       ;; we are manually doing bounds checking with known types, turn
1077       ;; off safety for vectors and lists but keep it for generic
1078       ;; sequences.
1079       (etypecase result-sequence
1080         (vector
1081          (locally (declare (optimize speed (safety 0)))
1082            (with-array-data ((data result-sequence) (start) (end)
1083                              ;; MAP-INTO ignores fill pointer when mapping
1084                              :check-fill-pointer nil)
1085              (let ((index start))
1086                (declare (type index index))
1087                (macrolet ((dispatch ()
1088                             `(block mapping
1089                                (map-lambda (&rest args)
1090                                  (declare (truly-dynamic-extent args))
1091                                  (when (eql index end)
1092                                    (return-from mapping))
1093                                  (setf (aref data index)
1094                                        (apply really-fun args))
1095                                  (incf index)))))
1096                  (typecase data
1097                    (simple-vector (dispatch))
1098                    (otherwise (dispatch))))
1099                (when (array-has-fill-pointer-p result-sequence)
1100                  (setf (fill-pointer result-sequence) (- index start)))))))
1101         (list
1102          (let ((node result-sequence))
1103            (declare (type list node))
1104            (map-lambda (&rest args)
1105              (declare (truly-dynamic-extent args) (optimize speed (safety 0)))
1106              (when (null node)
1107                (return-from map-into result-sequence))
1108              (setf (car node) (apply really-fun args))
1109              (setf node (cdr node)))))
1110         (sequence
1111          (multiple-value-bind (iter limit from-end)
1112              (sb!sequence:make-sequence-iterator result-sequence)
1113            (map-lambda (&rest args)
1114              (declare (truly-dynamic-extent args) (optimize speed))
1115              (when (sb!sequence:iterator-endp result-sequence
1116                                               iter limit from-end)
1117                (return-from map-into result-sequence))
1118              (setf (sb!sequence:iterator-element result-sequence iter)
1119                    (apply really-fun args))
1120              (setf iter (sb!sequence:iterator-step result-sequence
1121                                                    iter from-end))))))))
1122   result-sequence)
1123 \f
1124 ;;;; quantifiers
1125
1126 ;;; We borrow the logic from (MAP NIL ..) to handle iteration over
1127 ;;; arbitrary sequence arguments, both in the full call case and in
1128 ;;; the open code case.
1129 (macrolet ((defquantifier (name found-test found-result
1130                                 &key doc (unfound-result (not found-result)))
1131              `(progn
1132                 ;; KLUDGE: It would be really nice if we could simply
1133                 ;; do something like this
1134                 ;;  (declaim (inline ,name))
1135                 ;;  (defun ,name (pred first-seq &rest more-seqs)
1136                 ;;    ,doc
1137                 ;;    (flet ((map-me (&rest rest)
1138                 ;;             (let ((pred-value (apply pred rest)))
1139                 ;;               (,found-test pred-value
1140                 ;;                 (return-from ,name
1141                 ;;                   ,found-result)))))
1142                 ;;      (declare (inline map-me))
1143                 ;;      (apply #'map nil #'map-me first-seq more-seqs)
1144                 ;;      ,unfound-result))
1145                 ;; but Python doesn't seem to be smart enough about
1146                 ;; inlining and APPLY to recognize that it can use
1147                 ;; the DEFTRANSFORM for MAP in the resulting inline
1148                 ;; expansion. I don't have any appetite for deep
1149                 ;; compiler hacking right now, so I'll just work
1150                 ;; around the apparent problem by using a compiler
1151                 ;; macro instead. -- WHN 20000410
1152                 (defun ,name (pred first-seq &rest more-seqs)
1153                   #!+sb-doc ,doc
1154                   (flet ((map-me (&rest rest)
1155                            (let ((pred-value (apply pred rest)))
1156                              (,found-test pred-value
1157                                           (return-from ,name
1158                                             ,found-result)))))
1159                     (declare (inline map-me))
1160                     (apply #'map nil #'map-me first-seq more-seqs)
1161                     ,unfound-result))
1162                 ;; KLUDGE: It would be more obviously correct -- but
1163                 ;; also significantly messier -- for PRED-VALUE to be
1164                 ;; a gensym. However, a private symbol really does
1165                 ;; seem to be good enough; and anyway the really
1166                 ;; obviously correct solution is to make Python smart
1167                 ;; enough that we can use an inline function instead
1168                 ;; of a compiler macro (as above). -- WHN 20000410
1169                 ;;
1170                 ;; FIXME: The DEFINE-COMPILER-MACRO here can be
1171                 ;; important for performance, and it'd be good to have
1172                 ;; it be visible throughout the compilation of all the
1173                 ;; target SBCL code. That could be done by defining
1174                 ;; SB-XC:DEFINE-COMPILER-MACRO and using it here,
1175                 ;; moving this DEFQUANTIFIER stuff (and perhaps other
1176                 ;; inline definitions in seq.lisp as well) into a new
1177                 ;; seq.lisp, and moving remaining target-only stuff
1178                 ;; from the old seq.lisp into target-seq.lisp.
1179                 (define-compiler-macro ,name (pred first-seq &rest more-seqs)
1180                   (let ((elements (make-gensym-list (1+ (length more-seqs))))
1181                         (blockname (gensym "BLOCK")))
1182                     (once-only ((pred pred))
1183                       `(block ,blockname
1184                          (map nil
1185                               (lambda (,@elements)
1186                                 (let ((pred-value (funcall ,pred ,@elements)))
1187                                   (,',found-test pred-value
1188                                     (return-from ,blockname
1189                                       ,',found-result))))
1190                               ,first-seq
1191                               ,@more-seqs)
1192                          ,',unfound-result)))))))
1193   (defquantifier some when pred-value :unfound-result nil :doc
1194   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1195    possibly to those with index 1, and so on. Return the first
1196    non-NIL value encountered, or NIL if the end of any sequence is reached.")
1197   (defquantifier every unless nil :doc
1198   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1199    possibly to those with index 1, and so on. Return NIL as soon
1200    as any invocation of PREDICATE returns NIL, or T if every invocation
1201    is non-NIL.")
1202   (defquantifier notany when nil :doc
1203   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1204    possibly to those with index 1, and so on. Return NIL as soon
1205    as any invocation of PREDICATE returns a non-NIL value, or T if the end
1206    of any sequence is reached.")
1207   (defquantifier notevery unless t :doc
1208   "Apply PREDICATE to 0-indexed elements of the sequences, then
1209    possibly to those with index 1, and so on. Return T as soon
1210    as any invocation of PREDICATE returns NIL, or NIL if every invocation
1211    is non-NIL."))
1212 \f
1213 ;;;; REDUCE
1214
1215 (eval-when (:compile-toplevel :execute)
1216
1217 (sb!xc:defmacro mumble-reduce (function
1218                                sequence
1219                                key
1220                                start
1221                                end
1222                                initial-value
1223                                ref)
1224   `(do ((index ,start (1+ index))
1225         (value ,initial-value))
1226        ((>= index ,end) value)
1227      (setq value (funcall ,function value
1228                           (apply-key ,key (,ref ,sequence index))))))
1229
1230 (sb!xc:defmacro mumble-reduce-from-end (function
1231                                         sequence
1232                                         key
1233                                         start
1234                                         end
1235                                         initial-value
1236                                         ref)
1237   `(do ((index (1- ,end) (1- index))
1238         (value ,initial-value)
1239         (terminus (1- ,start)))
1240        ((<= index terminus) value)
1241      (setq value (funcall ,function
1242                           (apply-key ,key (,ref ,sequence index))
1243                           value))))
1244
1245 (sb!xc:defmacro list-reduce (function
1246                              sequence
1247                              key
1248                              start
1249                              end
1250                              initial-value
1251                              ivp)
1252   `(let ((sequence (nthcdr ,start ,sequence)))
1253      (do ((count (if ,ivp ,start (1+ ,start))
1254                  (1+ count))
1255           (sequence (if ,ivp sequence (cdr sequence))
1256                     (cdr sequence))
1257           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1258                  (funcall ,function value (apply-key ,key (car sequence)))))
1259          ((>= count ,end) value))))
1260
1261 (sb!xc:defmacro list-reduce-from-end (function
1262                                       sequence
1263                                       key
1264                                       start
1265                                       end
1266                                       initial-value
1267                                       ivp)
1268   `(let ((sequence (nthcdr (- (length ,sequence) ,end)
1269                            (reverse ,sequence))))
1270      (do ((count (if ,ivp ,start (1+ ,start))
1271                  (1+ count))
1272           (sequence (if ,ivp sequence (cdr sequence))
1273                     (cdr sequence))
1274           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1275                  (funcall ,function (apply-key ,key (car sequence)) value)))
1276          ((>= count ,end) value))))
1277
1278 ) ; EVAL-WHEN
1279
1280 (define-sequence-traverser reduce (function sequence &rest args &key key
1281                                    from-end start end (initial-value nil ivp))
1282   (declare (type index start))
1283   (declare (truly-dynamic-extent args))
1284   (let ((start start)
1285         (end (or end length)))
1286     (declare (type index start end))
1287     (seq-dispatch sequence
1288       (if (= end start)
1289           (if ivp initial-value (funcall function))
1290           (if from-end
1291               (list-reduce-from-end function sequence key start end
1292                                     initial-value ivp)
1293               (list-reduce function sequence key start end
1294                            initial-value ivp)))
1295       (if (= end start)
1296           (if ivp initial-value (funcall function))
1297           (if from-end
1298               (progn
1299                 (when (not ivp)
1300                   (setq end (1- (the fixnum end)))
1301                   (setq initial-value (apply-key key (aref sequence end))))
1302                 (mumble-reduce-from-end function sequence key start end
1303                                         initial-value aref))
1304               (progn
1305                 (when (not ivp)
1306                   (setq initial-value (apply-key key (aref sequence start)))
1307                   (setq start (1+ start)))
1308                 (mumble-reduce function sequence key start end
1309                                initial-value aref))))
1310       (apply #'sb!sequence:reduce function sequence args))))
1311 \f
1312 ;;;; DELETE
1313
1314 (eval-when (:compile-toplevel :execute)
1315
1316 (sb!xc:defmacro mumble-delete (pred)
1317   `(do ((index start (1+ index))
1318         (jndex start)
1319         (number-zapped 0))
1320        ((or (= index (the fixnum end)) (= number-zapped count))
1321         (do ((index index (1+ index))           ; Copy the rest of the vector.
1322              (jndex jndex (1+ jndex)))
1323             ((= index (the fixnum length))
1324              (shrink-vector sequence jndex))
1325           (declare (fixnum index jndex))
1326           (setf (aref sequence jndex) (aref sequence index))))
1327      (declare (fixnum index jndex number-zapped))
1328      (setf (aref sequence jndex) (aref sequence index))
1329      (if ,pred
1330          (incf number-zapped)
1331          (incf jndex))))
1332
1333 (sb!xc:defmacro mumble-delete-from-end (pred)
1334   `(do ((index (1- (the fixnum end)) (1- index)) ; Find the losers.
1335         (number-zapped 0)
1336         (losers ())
1337         this-element
1338         (terminus (1- start)))
1339        ((or (= index terminus) (= number-zapped count))
1340         (do ((losers losers)                     ; Delete the losers.
1341              (index start (1+ index))
1342              (jndex start))
1343             ((or (null losers) (= index (the fixnum end)))
1344              (do ((index index (1+ index))       ; Copy the rest of the vector.
1345                   (jndex jndex (1+ jndex)))
1346                  ((= index (the fixnum length))
1347                   (shrink-vector sequence jndex))
1348                (declare (fixnum index jndex))
1349                (setf (aref sequence jndex) (aref sequence index))))
1350           (declare (fixnum index jndex))
1351           (setf (aref sequence jndex) (aref sequence index))
1352           (if (= index (the fixnum (car losers)))
1353               (pop losers)
1354               (incf jndex))))
1355      (declare (fixnum index number-zapped terminus))
1356      (setq this-element (aref sequence index))
1357      (when ,pred
1358        (incf number-zapped)
1359        (push index losers))))
1360
1361 (sb!xc:defmacro normal-mumble-delete ()
1362   `(mumble-delete
1363     (if test-not
1364         (not (funcall test-not item (apply-key key (aref sequence index))))
1365         (funcall test item (apply-key key (aref sequence index))))))
1366
1367 (sb!xc:defmacro normal-mumble-delete-from-end ()
1368   `(mumble-delete-from-end
1369     (if test-not
1370         (not (funcall test-not item (apply-key key this-element)))
1371         (funcall test item (apply-key key this-element)))))
1372
1373 (sb!xc:defmacro list-delete (pred)
1374   `(let ((handle (cons nil sequence)))
1375      (do ((current (nthcdr start sequence) (cdr current))
1376           (previous (nthcdr start handle))
1377           (index start (1+ index))
1378           (number-zapped 0))
1379          ((or (= index (the fixnum end)) (= number-zapped count))
1380           (cdr handle))
1381        (declare (fixnum index number-zapped))
1382        (cond (,pred
1383               (rplacd previous (cdr current))
1384               (incf number-zapped))
1385              (t
1386               (setq previous (cdr previous)))))))
1387
1388 (sb!xc:defmacro list-delete-from-end (pred)
1389   `(let* ((reverse (nreverse (the list sequence)))
1390           (handle (cons nil reverse)))
1391      (do ((current (nthcdr (- (the fixnum length) (the fixnum end)) reverse)
1392                    (cdr current))
1393           (previous (nthcdr (- (the fixnum length) (the fixnum end)) handle))
1394           (index start (1+ index))
1395           (number-zapped 0))
1396          ((or (= index (the fixnum end)) (= number-zapped count))
1397           (nreverse (cdr handle)))
1398        (declare (fixnum index number-zapped))
1399        (cond (,pred
1400               (rplacd previous (cdr current))
1401               (incf number-zapped))
1402              (t
1403               (setq previous (cdr previous)))))))
1404
1405 (sb!xc:defmacro normal-list-delete ()
1406   '(list-delete
1407     (if test-not
1408         (not (funcall test-not item (apply-key key (car current))))
1409         (funcall test item (apply-key key (car current))))))
1410
1411 (sb!xc:defmacro normal-list-delete-from-end ()
1412   '(list-delete-from-end
1413     (if test-not
1414         (not (funcall test-not item (apply-key key (car current))))
1415         (funcall test item (apply-key key (car current))))))
1416
1417 ) ; EVAL-WHEN
1418
1419 (define-sequence-traverser delete
1420     (item sequence &rest args &key from-end test test-not start
1421      end count key)
1422   #!+sb-doc
1423   "Return a sequence formed by destructively removing the specified ITEM from
1424   the given SEQUENCE."
1425   (declare (fixnum start))
1426   (declare (truly-dynamic-extent args))
1427   (let ((end (or end length)))
1428     (declare (type index end))
1429     (seq-dispatch sequence
1430       (if from-end
1431           (normal-list-delete-from-end)
1432           (normal-list-delete))
1433       (if from-end
1434           (normal-mumble-delete-from-end)
1435           (normal-mumble-delete))
1436       (apply #'sb!sequence:delete item sequence args))))
1437
1438 (eval-when (:compile-toplevel :execute)
1439
1440 (sb!xc:defmacro if-mumble-delete ()
1441   `(mumble-delete
1442     (funcall predicate (apply-key key (aref sequence index)))))
1443
1444 (sb!xc:defmacro if-mumble-delete-from-end ()
1445   `(mumble-delete-from-end
1446     (funcall predicate (apply-key key this-element))))
1447
1448 (sb!xc:defmacro if-list-delete ()
1449   '(list-delete
1450     (funcall predicate (apply-key key (car current)))))
1451
1452 (sb!xc:defmacro if-list-delete-from-end ()
1453   '(list-delete-from-end
1454     (funcall predicate (apply-key key (car current)))))
1455
1456 ) ; EVAL-WHEN
1457
1458 (define-sequence-traverser delete-if
1459     (predicate sequence &rest args &key from-end start key end count)
1460   #!+sb-doc
1461   "Return a sequence formed by destructively removing the elements satisfying
1462   the specified PREDICATE from the given SEQUENCE."
1463   (declare (fixnum start))
1464   (declare (truly-dynamic-extent args))
1465   (let ((end (or end length)))
1466     (declare (type index end))
1467     (seq-dispatch sequence
1468       (if from-end
1469           (if-list-delete-from-end)
1470           (if-list-delete))
1471       (if from-end
1472           (if-mumble-delete-from-end)
1473           (if-mumble-delete))
1474       (apply #'sb!sequence:delete-if predicate sequence args))))
1475
1476 (eval-when (:compile-toplevel :execute)
1477
1478 (sb!xc:defmacro if-not-mumble-delete ()
1479   `(mumble-delete
1480     (not (funcall predicate (apply-key key (aref sequence index))))))
1481
1482 (sb!xc:defmacro if-not-mumble-delete-from-end ()
1483   `(mumble-delete-from-end
1484     (not (funcall predicate (apply-key key this-element)))))
1485
1486 (sb!xc:defmacro if-not-list-delete ()
1487   '(list-delete
1488     (not (funcall predicate (apply-key key (car current))))))
1489
1490 (sb!xc:defmacro if-not-list-delete-from-end ()
1491   '(list-delete-from-end
1492     (not (funcall predicate (apply-key key (car current))))))
1493
1494 ) ; EVAL-WHEN
1495
1496 (define-sequence-traverser delete-if-not
1497     (predicate sequence &rest args &key from-end start end key count)
1498   #!+sb-doc
1499   "Return a sequence formed by destructively removing the elements not
1500   satisfying the specified PREDICATE from the given SEQUENCE."
1501   (declare (fixnum start))
1502   (declare (truly-dynamic-extent args))
1503   (let ((end (or end length)))
1504     (declare (type index end))
1505     (seq-dispatch sequence
1506       (if from-end
1507           (if-not-list-delete-from-end)
1508           (if-not-list-delete))
1509       (if from-end
1510           (if-not-mumble-delete-from-end)
1511           (if-not-mumble-delete))
1512       (apply #'sb!sequence:delete-if-not predicate sequence args))))
1513 \f
1514 ;;;; REMOVE
1515
1516 (eval-when (:compile-toplevel :execute)
1517
1518 ;;; MUMBLE-REMOVE-MACRO does not include (removes) each element that
1519 ;;; satisfies the predicate.
1520 (sb!xc:defmacro mumble-remove-macro (bump left begin finish right pred)
1521   `(do ((index ,begin (,bump index))
1522         (result
1523          (do ((index ,left (,bump index))
1524               (result (%make-sequence-like sequence length)))
1525              ((= index (the fixnum ,begin)) result)
1526            (declare (fixnum index))
1527            (setf (aref result index) (aref sequence index))))
1528         (new-index ,begin)
1529         (number-zapped 0)
1530         (this-element))
1531        ((or (= index (the fixnum ,finish))
1532             (= number-zapped count))
1533         (do ((index index (,bump index))
1534              (new-index new-index (,bump new-index)))
1535             ((= index (the fixnum ,right)) (%shrink-vector result new-index))
1536           (declare (fixnum index new-index))
1537           (setf (aref result new-index) (aref sequence index))))
1538      (declare (fixnum index new-index number-zapped))
1539      (setq this-element (aref sequence index))
1540      (cond (,pred (incf number-zapped))
1541            (t (setf (aref result new-index) this-element)
1542               (setq new-index (,bump new-index))))))
1543
1544 (sb!xc:defmacro mumble-remove (pred)
1545   `(mumble-remove-macro 1+ 0 start end length ,pred))
1546
1547 (sb!xc:defmacro mumble-remove-from-end (pred)
1548   `(let ((sequence (copy-seq sequence)))
1549      (mumble-delete-from-end ,pred)))
1550
1551 (sb!xc:defmacro normal-mumble-remove ()
1552   `(mumble-remove
1553     (if test-not
1554         (not (funcall test-not item (apply-key key this-element)))
1555         (funcall test item (apply-key key this-element)))))
1556
1557 (sb!xc:defmacro normal-mumble-remove-from-end ()
1558   `(mumble-remove-from-end
1559     (if test-not
1560         (not (funcall test-not item (apply-key key this-element)))
1561         (funcall test item (apply-key key this-element)))))
1562
1563 (sb!xc:defmacro if-mumble-remove ()
1564   `(mumble-remove (funcall predicate (apply-key key this-element))))
1565
1566 (sb!xc:defmacro if-mumble-remove-from-end ()
1567   `(mumble-remove-from-end (funcall predicate (apply-key key this-element))))
1568
1569 (sb!xc:defmacro if-not-mumble-remove ()
1570   `(mumble-remove (not (funcall predicate (apply-key key this-element)))))
1571
1572 (sb!xc:defmacro if-not-mumble-remove-from-end ()
1573   `(mumble-remove-from-end
1574     (not (funcall predicate (apply-key key this-element)))))
1575
1576 ;;; LIST-REMOVE-MACRO does not include (removes) each element that satisfies
1577 ;;; the predicate.
1578 (sb!xc:defmacro list-remove-macro (pred reverse?)
1579   `(let* ((sequence ,(if reverse?
1580                          '(reverse (the list sequence))
1581                          'sequence))
1582           (%start ,(if reverse? '(- length end) 'start))
1583           (%end ,(if reverse? '(- length start) 'end))
1584           (splice (list nil))
1585           (results (do ((index 0 (1+ index))
1586                         (before-start splice))
1587                        ((= index (the fixnum %start)) before-start)
1588                      (declare (fixnum index))
1589                      (setq splice
1590                            (cdr (rplacd splice (list (pop sequence))))))))
1591      (do ((index %start (1+ index))
1592           (this-element)
1593           (number-zapped 0))
1594          ((or (= index (the fixnum %end)) (= number-zapped count))
1595           (do ((index index (1+ index)))
1596               ((null sequence)
1597                ,(if reverse?
1598                     '(nreverse (the list (cdr results)))
1599                     '(cdr results)))
1600             (declare (fixnum index))
1601             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1602        (declare (fixnum index number-zapped))
1603        (setq this-element (pop sequence))
1604        (if ,pred
1605            (setq number-zapped (1+ number-zapped))
1606            (setq splice (cdr (rplacd splice (list this-element))))))))
1607
1608 (sb!xc:defmacro list-remove (pred)
1609   `(list-remove-macro ,pred nil))
1610
1611 (sb!xc:defmacro list-remove-from-end (pred)
1612   `(list-remove-macro ,pred t))
1613
1614 (sb!xc:defmacro normal-list-remove ()
1615   `(list-remove
1616     (if test-not
1617         (not (funcall test-not item (apply-key key this-element)))
1618         (funcall test item (apply-key key this-element)))))
1619
1620 (sb!xc:defmacro normal-list-remove-from-end ()
1621   `(list-remove-from-end
1622     (if test-not
1623         (not (funcall test-not item (apply-key key this-element)))
1624         (funcall test item (apply-key key this-element)))))
1625
1626 (sb!xc:defmacro if-list-remove ()
1627   `(list-remove
1628     (funcall predicate (apply-key key this-element))))
1629
1630 (sb!xc:defmacro if-list-remove-from-end ()
1631   `(list-remove-from-end
1632     (funcall predicate (apply-key key this-element))))
1633
1634 (sb!xc:defmacro if-not-list-remove ()
1635   `(list-remove
1636     (not (funcall predicate (apply-key key this-element)))))
1637
1638 (sb!xc:defmacro if-not-list-remove-from-end ()
1639   `(list-remove-from-end
1640     (not (funcall predicate (apply-key key this-element)))))
1641
1642 ) ; EVAL-WHEN
1643
1644 (define-sequence-traverser remove
1645     (item sequence &rest args &key from-end test test-not start
1646      end count key)
1647   #!+sb-doc
1648   "Return a copy of SEQUENCE with elements satisfying the test (default is
1649    EQL) with ITEM removed."
1650   (declare (fixnum start))
1651   (declare (truly-dynamic-extent args))
1652   (let ((end (or end length)))
1653     (declare (type index end))
1654     (seq-dispatch sequence
1655       (if from-end
1656           (normal-list-remove-from-end)
1657           (normal-list-remove))
1658       (if from-end
1659           (normal-mumble-remove-from-end)
1660           (normal-mumble-remove))
1661       (apply #'sb!sequence:remove item sequence args))))
1662
1663 (define-sequence-traverser remove-if
1664     (predicate sequence &rest args &key from-end start end count key)
1665   #!+sb-doc
1666   "Return a copy of sequence with elements satisfying PREDICATE removed."
1667   (declare (fixnum start))
1668   (declare (truly-dynamic-extent args))
1669   (let ((end (or end length)))
1670     (declare (type index end))
1671     (seq-dispatch sequence
1672       (if from-end
1673           (if-list-remove-from-end)
1674           (if-list-remove))
1675       (if from-end
1676           (if-mumble-remove-from-end)
1677           (if-mumble-remove))
1678       (apply #'sb!sequence:remove-if predicate sequence args))))
1679
1680 (define-sequence-traverser remove-if-not
1681     (predicate sequence &rest args &key from-end start end count key)
1682   #!+sb-doc
1683   "Return a copy of sequence with elements not satisfying PREDICATE removed."
1684   (declare (fixnum start))
1685   (declare (truly-dynamic-extent args))
1686   (let ((end (or end length)))
1687     (declare (type index end))
1688     (seq-dispatch sequence
1689       (if from-end
1690           (if-not-list-remove-from-end)
1691           (if-not-list-remove))
1692       (if from-end
1693           (if-not-mumble-remove-from-end)
1694           (if-not-mumble-remove))
1695       (apply #'sb!sequence:remove-if-not predicate sequence args))))
1696 \f
1697 ;;;; REMOVE-DUPLICATES
1698
1699 ;;; Remove duplicates from a list. If from-end, remove the later duplicates,
1700 ;;; not the earlier ones. Thus if we check from-end we don't copy an item
1701 ;;; if we look into the already copied structure (from after :start) and see
1702 ;;; the item. If we check from beginning we check into the rest of the
1703 ;;; original list up to the :end marker (this we have to do by running a
1704 ;;; do loop down the list that far and using our test.
1705 (defun list-remove-duplicates* (list test test-not start end key from-end)
1706   (declare (fixnum start))
1707   (let* ((result (list ())) ; Put a marker on the beginning to splice with.
1708          (splice result)
1709          (current list)
1710          (end (or end (length list)))
1711          (hash (and (> (- end start) 20)
1712                     test
1713                     (not key)
1714                     (not test-not)
1715                     (or (eql test #'eql)
1716                         (eql test #'eq)
1717                         (eql test #'equal)
1718                         (eql test #'equalp))
1719                     (make-hash-table :test test :size (- end start)))))
1720     (do ((index 0 (1+ index)))
1721         ((= index start))
1722       (declare (fixnum index))
1723       (setq splice (cdr (rplacd splice (list (car current)))))
1724       (setq current (cdr current)))
1725     (if hash
1726         (do ((index start (1+ index)))
1727             ((or (and end (= index (the fixnum end)))
1728                  (atom current)))
1729           (declare (fixnum index))
1730           ;; The hash table contains links from values that are
1731           ;; already in result to the cons cell *preceding* theirs
1732           ;; in the list.  That is, for each value v in the list,
1733           ;; v and (cadr (gethash v hash)) are equal under TEST.
1734           (let ((prev (gethash (car current) hash)))
1735             (cond
1736              ((not prev)
1737               (setf (gethash (car current) hash) splice)
1738               (setq splice (cdr (rplacd splice (list (car current))))))
1739              ((not from-end)
1740               (let* ((old (cdr prev))
1741                      (next (cdr old)))
1742                 (if next
1743                   (let ((next-val (car next)))
1744                     ;; (assert (eq (gethash next-val hash) old))
1745                     (setf (cdr prev) next
1746                           (gethash next-val hash) prev
1747                           (gethash (car current) hash) splice
1748                           splice (cdr (rplacd splice (list (car current))))))
1749                   (setf (car old) (car current)))))))
1750           (setq current (cdr current)))
1751       (do ((index start (1+ index)))
1752           ((or (and end (= index (the fixnum end)))
1753                (atom current)))
1754         (declare (fixnum index))
1755         (if (or (and from-end
1756                      (not (if test-not
1757                               (member (apply-key key (car current))
1758                                       (nthcdr (1+ start) result)
1759                                       :test-not test-not
1760                                       :key key)
1761                             (member (apply-key key (car current))
1762                                     (nthcdr (1+ start) result)
1763                                     :test test
1764                                     :key key))))
1765                 (and (not from-end)
1766                      (not (do ((it (apply-key key (car current)))
1767                                (l (cdr current) (cdr l))
1768                                (i (1+ index) (1+ i)))
1769                               ((or (atom l) (and end (= i (the fixnum end))))
1770                                ())
1771                             (declare (fixnum i))
1772                             (if (if test-not
1773                                     (not (funcall test-not
1774                                                   it
1775                                                   (apply-key key (car l))))
1776                                   (funcall test it (apply-key key (car l))))
1777                                 (return t))))))
1778             (setq splice (cdr (rplacd splice (list (car current))))))
1779         (setq current (cdr current))))
1780     (do ()
1781         ((atom current))
1782       (setq splice (cdr (rplacd splice (list (car current)))))
1783       (setq current (cdr current)))
1784     (cdr result)))
1785
1786 (defun vector-remove-duplicates* (vector test test-not start end key from-end
1787                                          &optional (length (length vector)))
1788   (declare (vector vector) (fixnum start length))
1789   (when (null end) (setf end (length vector)))
1790   (let ((result (%make-sequence-like vector length))
1791         (index 0)
1792         (jndex start))
1793     (declare (fixnum index jndex))
1794     (do ()
1795         ((= index start))
1796       (setf (aref result index) (aref vector index))
1797       (setq index (1+ index)))
1798     (do ((elt))
1799         ((= index end))
1800       (setq elt (aref vector index))
1801       (unless (or (and from-end
1802                        (if test-not
1803                            (position (apply-key key elt) result
1804                                      :start start :end jndex
1805                                      :test-not test-not :key key)
1806                            (position (apply-key key elt) result
1807                                      :start start :end jndex
1808                                      :test test :key key)))
1809                   (and (not from-end)
1810                        (if test-not
1811                            (position (apply-key key elt) vector
1812                                      :start (1+ index) :end end
1813                                      :test-not test-not :key key)
1814                            (position (apply-key key elt) vector
1815                                      :start (1+ index) :end end
1816                                      :test test :key key))))
1817         (setf (aref result jndex) elt)
1818         (setq jndex (1+ jndex)))
1819       (setq index (1+ index)))
1820     (do ()
1821         ((= index length))
1822       (setf (aref result jndex) (aref vector index))
1823       (setq index (1+ index))
1824       (setq jndex (1+ jndex)))
1825     (%shrink-vector result jndex)))
1826
1827 (define-sequence-traverser remove-duplicates
1828     (sequence &rest args &key test test-not start end from-end key)
1829   #!+sb-doc
1830   "The elements of SEQUENCE are compared pairwise, and if any two match,
1831    the one occurring earlier is discarded, unless FROM-END is true, in
1832    which case the one later in the sequence is discarded. The resulting
1833    sequence is returned.
1834
1835    The :TEST-NOT argument is deprecated."
1836   (declare (fixnum start))
1837   (declare (truly-dynamic-extent args))
1838   (seq-dispatch sequence
1839     (if sequence
1840         (list-remove-duplicates* sequence test test-not
1841                                  start end key from-end))
1842     (vector-remove-duplicates* sequence test test-not start end key from-end)
1843     (apply #'sb!sequence:remove-duplicates sequence args)))
1844 \f
1845 ;;;; DELETE-DUPLICATES
1846
1847 (defun list-delete-duplicates* (list test test-not key from-end start end)
1848   (declare (fixnum start))
1849   (let ((handle (cons nil list)))
1850     (do ((current (nthcdr start list) (cdr current))
1851          (previous (nthcdr start handle))
1852          (index start (1+ index)))
1853         ((or (and end (= index (the fixnum end))) (null current))
1854          (cdr handle))
1855       (declare (fixnum index))
1856       (if (do ((x (if from-end
1857                       (nthcdr (1+ start) handle)
1858                       (cdr current))
1859                   (cdr x))
1860                (i (1+ index) (1+ i)))
1861               ((or (null x)
1862                    (and (not from-end) end (= i (the fixnum end)))
1863                    (eq x current))
1864                nil)
1865             (declare (fixnum i))
1866             (if (if test-not
1867                     (not (funcall test-not
1868                                   (apply-key key (car current))
1869                                   (apply-key key (car x))))
1870                     (funcall test
1871                              (apply-key key (car current))
1872                              (apply-key key (car x))))
1873                 (return t)))
1874           (rplacd previous (cdr current))
1875           (setq previous (cdr previous))))))
1876
1877 (defun vector-delete-duplicates* (vector test test-not key from-end start end
1878                                          &optional (length (length vector)))
1879   (declare (vector vector) (fixnum start length))
1880   (when (null end) (setf end (length vector)))
1881   (do ((index start (1+ index))
1882        (jndex start))
1883       ((= index end)
1884        (do ((index index (1+ index))            ; copy the rest of the vector
1885             (jndex jndex (1+ jndex)))
1886            ((= index length)
1887             (shrink-vector vector jndex))
1888          (setf (aref vector jndex) (aref vector index))))
1889     (declare (fixnum index jndex))
1890     (setf (aref vector jndex) (aref vector index))
1891     (unless (if test-not
1892                 (position (apply-key key (aref vector index)) vector :key key
1893                           :start (if from-end start (1+ index))
1894                           :end (if from-end jndex end)
1895                           :test-not test-not)
1896                 (position (apply-key key (aref vector index)) vector :key key
1897                           :start (if from-end start (1+ index))
1898                           :end (if from-end jndex end)
1899                           :test test))
1900       (setq jndex (1+ jndex)))))
1901
1902 (define-sequence-traverser delete-duplicates
1903     (sequence &rest args &key test test-not start end from-end key)
1904   #!+sb-doc
1905   "The elements of SEQUENCE are examined, and if any two match, one is
1906    discarded. The resulting sequence, which may be formed by destroying the
1907    given sequence, is returned.
1908
1909    The :TEST-NOT argument is deprecated."
1910   (declare (truly-dynamic-extent args))
1911   (seq-dispatch sequence
1912     (if sequence
1913         (list-delete-duplicates* sequence test test-not
1914                                  key from-end start end))
1915     (vector-delete-duplicates* sequence test test-not key from-end start end)
1916     (apply #'sb!sequence:delete-duplicates sequence args)))
1917 \f
1918 ;;;; SUBSTITUTE
1919
1920 (defun list-substitute* (pred new list start end count key test test-not old)
1921   (declare (fixnum start end count))
1922   (let* ((result (list nil))
1923          elt
1924          (splice result)
1925          (list list))      ; Get a local list for a stepper.
1926     (do ((index 0 (1+ index)))
1927         ((= index start))
1928       (declare (fixnum index))
1929       (setq splice (cdr (rplacd splice (list (car list)))))
1930       (setq list (cdr list)))
1931     (do ((index start (1+ index)))
1932         ((or (= index end) (null list) (= count 0)))
1933       (declare (fixnum index))
1934       (setq elt (car list))
1935       (setq splice
1936             (cdr (rplacd splice
1937                          (list
1938                           (cond
1939                            ((case pred
1940                                    (normal
1941                                     (if test-not
1942                                         (not
1943                                          (funcall test-not old (apply-key key elt)))
1944                                         (funcall test old (apply-key key elt))))
1945                                    (if (funcall test (apply-key key elt)))
1946                                    (if-not (not (funcall test (apply-key key elt)))))
1947                             (decf count)
1948                             new)
1949                                 (t elt))))))
1950       (setq list (cdr list)))
1951     (do ()
1952         ((null list))
1953       (setq splice (cdr (rplacd splice (list (car list)))))
1954       (setq list (cdr list)))
1955     (cdr result)))
1956
1957 ;;; Replace old with new in sequence moving from left to right by incrementer
1958 ;;; on each pass through the loop. Called by all three substitute functions.
1959 (defun vector-substitute* (pred new sequence incrementer left right length
1960                            start end count key test test-not old)
1961   (declare (fixnum start count end incrementer right))
1962   (let ((result (%make-sequence-like sequence length))
1963         (index left))
1964     (declare (fixnum index))
1965     (do ()
1966         ((= index start))
1967       (setf (aref result index) (aref sequence index))
1968       (setq index (+ index incrementer)))
1969     (do ((elt))
1970         ((or (= index end) (= count 0)))
1971       (setq elt (aref sequence index))
1972       (setf (aref result index)
1973             (cond ((case pred
1974                           (normal
1975                             (if test-not
1976                                 (not (funcall test-not old (apply-key key elt)))
1977                                 (funcall test old (apply-key key elt))))
1978                           (if (funcall test (apply-key key elt)))
1979                           (if-not (not (funcall test (apply-key key elt)))))
1980                    (setq count (1- count))
1981                    new)
1982                   (t elt)))
1983       (setq index (+ index incrementer)))
1984     (do ()
1985         ((= index right))
1986       (setf (aref result index) (aref sequence index))
1987       (setq index (+ index incrementer)))
1988     result))
1989
1990 (eval-when (:compile-toplevel :execute)
1991
1992 (sb!xc:defmacro subst-dispatch (pred)
1993   `(seq-dispatch sequence
1994      (if from-end
1995          (nreverse (list-substitute* ,pred
1996                                      new
1997                                      (reverse sequence)
1998                                      (- (the fixnum length)
1999                                         (the fixnum end))
2000                                      (- (the fixnum length)
2001                                         (the fixnum start))
2002                                      count key test test-not old))
2003          (list-substitute* ,pred
2004                            new sequence start end count key test test-not
2005                            old))
2006     (if from-end
2007         (vector-substitute* ,pred new sequence -1 (1- (the fixnum length))
2008                             -1 length (1- (the fixnum end))
2009                             (1- (the fixnum start))
2010                             count key test test-not old)
2011         (vector-substitute* ,pred new sequence 1 0 length length
2012                             start end count key test test-not old))
2013     ;; FIXME: wow, this is an odd way to implement the dispatch.  PRED
2014     ;; here is (QUOTE [NORMAL|IF|IF-NOT]).  Not only is this pretty
2015     ;; pointless, but also LIST-SUBSTITUTE* and VECTOR-SUBSTITUTE*
2016     ;; dispatch once per element on PRED's run-time identity.
2017     ,(ecase (cadr pred)
2018        ((normal) `(apply #'sb!sequence:substitute new old sequence args))
2019        ((if) `(apply #'sb!sequence:substitute-if new predicate sequence args))
2020        ((if-not) `(apply #'sb!sequence:substitute-if-not new predicate sequence args)))))
2021 ) ; EVAL-WHEN
2022
2023 (define-sequence-traverser substitute
2024     (new old sequence &rest args &key from-end test test-not
2025          start count end key)
2026   #!+sb-doc
2027   "Return a sequence of the same kind as SEQUENCE with the same elements,
2028   except that all elements equal to OLD are replaced with NEW."
2029   (declare (fixnum start))
2030   (declare (truly-dynamic-extent args))
2031   (let ((end (or end length)))
2032     (declare (type index end))
2033     (subst-dispatch 'normal)))
2034 \f
2035 ;;;; SUBSTITUTE-IF, SUBSTITUTE-IF-NOT
2036
2037 (define-sequence-traverser substitute-if
2038     (new predicate sequence &rest args &key from-end start end count key)
2039   #!+sb-doc
2040   "Return a sequence of the same kind as SEQUENCE with the same elements
2041   except that all elements satisfying the PRED are replaced with NEW."
2042   (declare (truly-dynamic-extent args))
2043   (declare (fixnum start))
2044   (let ((end (or end length))
2045         (test predicate)
2046         (test-not nil)
2047         old)
2048     (declare (type index length end))
2049     (subst-dispatch 'if)))
2050
2051 (define-sequence-traverser substitute-if-not
2052     (new predicate sequence &rest args &key from-end start end count key)
2053   #!+sb-doc
2054   "Return a sequence of the same kind as SEQUENCE with the same elements
2055   except that all elements not satisfying the PRED are replaced with NEW."
2056   (declare (truly-dynamic-extent args))
2057   (declare (fixnum start))
2058   (let ((end (or end length))
2059         (test predicate)
2060         (test-not nil)
2061         old)
2062     (declare (type index length end))
2063     (subst-dispatch 'if-not)))
2064 \f
2065 ;;;; NSUBSTITUTE
2066
2067 (define-sequence-traverser nsubstitute
2068     (new old sequence &rest args &key from-end test test-not
2069          end count key start)
2070   #!+sb-doc
2071   "Return a sequence of the same kind as SEQUENCE with the same elements
2072   except that all elements equal to OLD are replaced with NEW. SEQUENCE
2073   may be destructively modified."
2074   (declare (fixnum start))
2075   (declare (truly-dynamic-extent args))
2076   (let ((end (or end length)))
2077     (seq-dispatch sequence
2078       (if from-end
2079           (let ((length (length sequence)))
2080             (nreverse (nlist-substitute*
2081                        new old (nreverse (the list sequence))
2082                        test test-not (- length end) (- length start)
2083                        count key)))
2084           (nlist-substitute* new old sequence
2085                              test test-not start end count key))
2086       (if from-end
2087           (nvector-substitute* new old sequence -1
2088                                test test-not (1- end) (1- start) count key)
2089           (nvector-substitute* new old sequence 1
2090                                test test-not start end count key))
2091       (apply #'sb!sequence:nsubstitute new old sequence args))))
2092
2093 (defun nlist-substitute* (new old sequence test test-not start end count key)
2094   (declare (fixnum start count end))
2095   (do ((list (nthcdr start sequence) (cdr list))
2096        (index start (1+ index)))
2097       ((or (= index end) (null list) (= count 0)) sequence)
2098     (declare (fixnum index))
2099     (when (if test-not
2100               (not (funcall test-not old (apply-key key (car list))))
2101               (funcall test old (apply-key key (car list))))
2102       (rplaca list new)
2103       (setq count (1- count)))))
2104
2105 (defun nvector-substitute* (new old sequence incrementer
2106                             test test-not start end count key)
2107   (declare (fixnum start incrementer count end))
2108   (do ((index start (+ index incrementer)))
2109       ((or (= index end) (= count 0)) sequence)
2110     (declare (fixnum index))
2111     (when (if test-not
2112               (not (funcall test-not
2113                             old
2114                             (apply-key key (aref sequence index))))
2115               (funcall test old (apply-key key (aref sequence index))))
2116       (setf (aref sequence index) new)
2117       (setq count (1- count)))))
2118 \f
2119 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
2120
2121 (define-sequence-traverser nsubstitute-if
2122     (new predicate sequence &rest args &key from-end start end count key)
2123   #!+sb-doc
2124   "Return a sequence of the same kind as SEQUENCE with the same elements
2125    except that all elements satisfying PREDICATE are replaced with NEW.
2126    SEQUENCE may be destructively modified."
2127   (declare (fixnum start))
2128   (declare (truly-dynamic-extent args))
2129   (let ((end (or end length)))
2130     (declare (fixnum end))
2131     (seq-dispatch sequence
2132       (if from-end
2133           (let ((length (length sequence)))
2134             (nreverse (nlist-substitute-if*
2135                        new predicate (nreverse (the list sequence))
2136                        (- length end) (- length start) count key)))
2137           (nlist-substitute-if* new predicate sequence
2138                                 start end count key))
2139       (if from-end
2140           (nvector-substitute-if* new predicate sequence -1
2141                                   (1- end) (1- start) count key)
2142           (nvector-substitute-if* new predicate sequence 1
2143                                   start end count key))
2144       (apply #'sb!sequence:nsubstitute-if new predicate sequence args))))
2145
2146 (defun nlist-substitute-if* (new test sequence start end count key)
2147   (declare (fixnum end))
2148   (do ((list (nthcdr start sequence) (cdr list))
2149        (index start (1+ index)))
2150       ((or (= index end) (null list) (= count 0)) sequence)
2151     (when (funcall test (apply-key key (car list)))
2152       (rplaca list new)
2153       (setq count (1- count)))))
2154
2155 (defun nvector-substitute-if* (new test sequence incrementer
2156                                start end count key)
2157   (do ((index start (+ index incrementer)))
2158       ((or (= index end) (= count 0)) sequence)
2159     (when (funcall test (apply-key key (aref sequence index)))
2160       (setf (aref sequence index) new)
2161       (setq count (1- count)))))
2162
2163 (define-sequence-traverser nsubstitute-if-not
2164     (new predicate sequence &rest args &key from-end start end count key)
2165   #!+sb-doc
2166   "Return a sequence of the same kind as SEQUENCE with the same elements
2167    except that all elements not satisfying PREDICATE are replaced with NEW.
2168    SEQUENCE may be destructively modified."
2169   (declare (fixnum start))
2170   (declare (truly-dynamic-extent args))
2171   (let ((end (or end length)))
2172     (declare (fixnum end))
2173     (seq-dispatch sequence
2174       (if from-end
2175           (let ((length (length sequence)))
2176             (nreverse (nlist-substitute-if-not*
2177                        new predicate (nreverse (the list sequence))
2178                        (- length end) (- length start) count key)))
2179           (nlist-substitute-if-not* new predicate sequence
2180                                     start end count key))
2181       (if from-end
2182           (nvector-substitute-if-not* new predicate sequence -1
2183                                       (1- end) (1- start) count key)
2184           (nvector-substitute-if-not* new predicate sequence 1
2185                                       start end count key))
2186       (apply #'sb!sequence:nsubstitute-if-not new predicate sequence args))))
2187
2188 (defun nlist-substitute-if-not* (new test sequence start end count key)
2189   (declare (fixnum end))
2190   (do ((list (nthcdr start sequence) (cdr list))
2191        (index start (1+ index)))
2192       ((or (= index end) (null list) (= count 0)) sequence)
2193     (when (not (funcall test (apply-key key (car list))))
2194       (rplaca list new)
2195       (decf count))))
2196
2197 (defun nvector-substitute-if-not* (new test sequence incrementer
2198                                    start end count key)
2199   (do ((index start (+ index incrementer)))
2200       ((or (= index end) (= count 0)) sequence)
2201     (when (not (funcall test (apply-key key (aref sequence index))))
2202       (setf (aref sequence index) new)
2203       (decf count))))
2204 \f
2205 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
2206
2207 (defun effective-find-position-test (test test-not)
2208   (effective-find-position-test test test-not))
2209 (defun effective-find-position-key (key)
2210   (effective-find-position-key key))
2211
2212 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
2213 (macrolet (;; shared logic for defining %FIND-POSITION and
2214            ;; %FIND-POSITION-IF in terms of various inlineable cases
2215            ;; of the expression defined in FROB and VECTOR*-FROB
2216            (frobs (&optional bit-frob)
2217              `(seq-dispatch sequence-arg
2218                (frob sequence-arg from-end)
2219                (with-array-data ((sequence sequence-arg :offset-var offset)
2220                                  (start start)
2221                                  (end end)
2222                                  :check-fill-pointer t)
2223                  (multiple-value-bind (f p)
2224                      (macrolet ((frob2 () `(if from-end
2225                                                (frob sequence t)
2226                                                (frob sequence nil))))
2227                        (typecase sequence
2228                          #!+sb-unicode
2229                          ((simple-array character (*)) (frob2))
2230                          ((simple-array base-char (*)) (frob2))
2231                          ,@(when bit-frob
2232                              `((simple-bit-vector
2233                                 (if (and (eq #'identity key)
2234                                          (or (eq #'eq test)
2235                                              (eq #'eql test)
2236                                              (eq #'equal test)))
2237                                     (let ((p (%bit-position (the bit item) sequence
2238                                                             from-end start end)))
2239                                       (if p
2240                                           (values item p)
2241                                           (values nil nil)))
2242                                     (vector*-frob sequence)))))
2243                          (t
2244                           (vector*-frob sequence))))
2245                    (declare (type (or index null) p))
2246                    (values f (and p (the index (- p offset)))))))))
2247   (defun %find-position (item sequence-arg from-end start end key test)
2248     (macrolet ((frob (sequence from-end)
2249                  `(%find-position item ,sequence
2250                                   ,from-end start end key test))
2251                (vector*-frob (sequence)
2252                  `(%find-position-vector-macro item ,sequence
2253                                                from-end start end key test)))
2254       (frobs t)))
2255   (defun %find-position-if (predicate sequence-arg from-end start end key)
2256     (macrolet ((frob (sequence from-end)
2257                  `(%find-position-if predicate ,sequence
2258                                      ,from-end start end key))
2259                (vector*-frob (sequence)
2260                  `(%find-position-if-vector-macro predicate ,sequence
2261                                                   from-end start end key)))
2262       (frobs)))
2263   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
2264     (macrolet ((frob (sequence from-end)
2265                  `(%find-position-if-not predicate ,sequence
2266                                          ,from-end start end key))
2267                (vector*-frob (sequence)
2268                  `(%find-position-if-not-vector-macro predicate ,sequence
2269                                                   from-end start end key)))
2270       (frobs))))
2271
2272 (defun find
2273     (item sequence &rest args &key from-end (start 0) end key test test-not)
2274   (declare (truly-dynamic-extent args))
2275   (seq-dispatch sequence
2276     (nth-value 0 (%find-position
2277                   item sequence from-end start end
2278                   (effective-find-position-key key)
2279                   (effective-find-position-test test test-not)))
2280     (nth-value 0 (%find-position
2281                   item sequence from-end start end
2282                   (effective-find-position-key key)
2283                   (effective-find-position-test test test-not)))
2284     (apply #'sb!sequence:find item sequence args)))
2285 (defun position
2286     (item sequence &rest args &key from-end (start 0) end key test test-not)
2287   (declare (truly-dynamic-extent args))
2288   (seq-dispatch sequence
2289     (nth-value 1 (%find-position
2290                   item sequence from-end start end
2291                   (effective-find-position-key key)
2292                   (effective-find-position-test test test-not)))
2293     (nth-value 1 (%find-position
2294                   item sequence from-end start end
2295                   (effective-find-position-key key)
2296                   (effective-find-position-test test test-not)))
2297     (apply #'sb!sequence:position item sequence args)))
2298
2299 (defun find-if (predicate sequence &rest args &key from-end (start 0) end key)
2300   (declare (truly-dynamic-extent args))
2301   (seq-dispatch sequence
2302     (nth-value 0 (%find-position-if
2303                   (%coerce-callable-to-fun predicate)
2304                   sequence from-end start end
2305                   (effective-find-position-key key)))
2306     (nth-value 0 (%find-position-if
2307                   (%coerce-callable-to-fun predicate)
2308                   sequence from-end start end
2309                   (effective-find-position-key key)))
2310     (apply #'sb!sequence:find-if predicate sequence args)))
2311 (defun position-if
2312     (predicate sequence &rest args &key from-end (start 0) end key)
2313   (declare (truly-dynamic-extent args))
2314   (seq-dispatch sequence
2315     (nth-value 1 (%find-position-if
2316                   (%coerce-callable-to-fun predicate)
2317                   sequence from-end start end
2318                   (effective-find-position-key key)))
2319     (nth-value 1 (%find-position-if
2320                   (%coerce-callable-to-fun predicate)
2321                   sequence from-end start end
2322                   (effective-find-position-key key)))
2323     (apply #'sb!sequence:position-if predicate sequence args)))
2324
2325 (defun find-if-not
2326     (predicate sequence &rest args &key from-end (start 0) end key)
2327   (declare (truly-dynamic-extent args))
2328   (seq-dispatch sequence
2329     (nth-value 0 (%find-position-if-not
2330                   (%coerce-callable-to-fun predicate)
2331                   sequence from-end start end
2332                   (effective-find-position-key key)))
2333     (nth-value 0 (%find-position-if-not
2334                   (%coerce-callable-to-fun predicate)
2335                   sequence from-end start end
2336                   (effective-find-position-key key)))
2337     (apply #'sb!sequence:find-if-not predicate sequence args)))
2338 (defun position-if-not
2339     (predicate sequence &rest args &key from-end (start 0) end key)
2340   (declare (truly-dynamic-extent args))
2341   (seq-dispatch sequence
2342     (nth-value 1 (%find-position-if-not
2343                   (%coerce-callable-to-fun predicate)
2344                   sequence from-end start end
2345                   (effective-find-position-key key)))
2346     (nth-value 1 (%find-position-if-not
2347                   (%coerce-callable-to-fun predicate)
2348                   sequence from-end start end
2349                   (effective-find-position-key key)))
2350     (apply #'sb!sequence:position-if-not predicate sequence args)))
2351 \f
2352 ;;;; COUNT-IF, COUNT-IF-NOT, and COUNT
2353
2354 (eval-when (:compile-toplevel :execute)
2355
2356 (sb!xc:defmacro vector-count-if (notp from-end-p predicate sequence)
2357   (let ((next-index (if from-end-p '(1- index) '(1+ index)))
2358         (pred `(funcall ,predicate (apply-key key (aref ,sequence index)))))
2359     `(let ((%start ,(if from-end-p '(1- end) 'start))
2360            (%end ,(if from-end-p '(1- start) 'end)))
2361       (do ((index %start ,next-index)
2362            (count 0))
2363           ((= index (the fixnum %end)) count)
2364         (declare (fixnum index count))
2365         (,(if notp 'unless 'when) ,pred
2366           (setq count (1+ count)))))))
2367
2368 (sb!xc:defmacro list-count-if (notp from-end-p predicate sequence)
2369   (let ((pred `(funcall ,predicate (apply-key key (pop sequence)))))
2370     `(let ((%start ,(if from-end-p '(- length end) 'start))
2371            (%end ,(if from-end-p '(- length start) 'end))
2372            (sequence ,(if from-end-p '(reverse sequence) 'sequence)))
2373       (do ((sequence (nthcdr %start ,sequence))
2374            (index %start (1+ index))
2375            (count 0))
2376           ((or (= index (the fixnum %end)) (null sequence)) count)
2377         (declare (fixnum index count))
2378         (,(if notp 'unless 'when) ,pred
2379           (setq count (1+ count)))))))
2380
2381
2382 ) ; EVAL-WHEN
2383
2384 (define-sequence-traverser count-if
2385     (pred sequence &rest args &key from-end start end key)
2386   #!+sb-doc
2387   "Return the number of elements in SEQUENCE satisfying PRED(el)."
2388   (declare (fixnum start))
2389   (declare (truly-dynamic-extent args))
2390   (let ((end (or end length))
2391         (pred (%coerce-callable-to-fun pred)))
2392     (declare (type index end))
2393     (seq-dispatch sequence
2394       (if from-end
2395           (list-count-if nil t pred sequence)
2396           (list-count-if nil nil pred sequence))
2397       (if from-end
2398           (vector-count-if nil t pred sequence)
2399           (vector-count-if nil nil pred sequence))
2400       (apply #'sb!sequence:count-if pred sequence args))))
2401
2402 (define-sequence-traverser count-if-not
2403     (pred sequence &rest args &key from-end start end key)
2404   #!+sb-doc
2405   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2406   (declare (fixnum start))
2407   (declare (truly-dynamic-extent args))
2408   (let ((end (or end length))
2409         (pred (%coerce-callable-to-fun pred)))
2410     (declare (type index end))
2411     (seq-dispatch sequence
2412       (if from-end
2413           (list-count-if t t pred sequence)
2414           (list-count-if t nil pred sequence))
2415       (if from-end
2416           (vector-count-if t t pred sequence)
2417           (vector-count-if t nil pred sequence))
2418       (apply #'sb!sequence:count-if-not pred sequence args))))
2419
2420 (define-sequence-traverser count
2421     (item sequence &rest args &key from-end start end
2422           key (test #'eql test-p) (test-not nil test-not-p))
2423   #!+sb-doc
2424   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2425    which defaults to EQL."
2426   (declare (fixnum start))
2427   (declare (truly-dynamic-extent args))
2428   (when (and test-p test-not-p)
2429     ;; ANSI Common Lisp has left the behavior in this situation unspecified.
2430     ;; (CLHS 17.2.1)
2431     (error ":TEST and :TEST-NOT are both present."))
2432   (let ((end (or end length)))
2433     (declare (type index end))
2434     (let ((%test (if test-not-p
2435                      (lambda (x)
2436                        (not (funcall test-not item x)))
2437                      (lambda (x)
2438                        (funcall test item x)))))
2439       (seq-dispatch sequence
2440         (if from-end
2441             (list-count-if nil t %test sequence)
2442             (list-count-if nil nil %test sequence))
2443         (if from-end
2444             (vector-count-if nil t %test sequence)
2445             (vector-count-if nil nil %test sequence))
2446         (apply #'sb!sequence:count item sequence args)))))
2447 \f
2448 ;;;; MISMATCH
2449
2450 (eval-when (:compile-toplevel :execute)
2451
2452 (sb!xc:defmacro match-vars (&rest body)
2453   `(let ((inc (if from-end -1 1))
2454          (start1 (if from-end (1- (the fixnum end1)) start1))
2455          (start2 (if from-end (1- (the fixnum end2)) start2))
2456          (end1 (if from-end (1- (the fixnum start1)) end1))
2457          (end2 (if from-end (1- (the fixnum start2)) end2)))
2458      (declare (fixnum inc start1 start2 end1 end2))
2459      ,@body))
2460
2461 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2462   (declare (ignore end)) ;; ### Should END be used below?
2463   `(let ((,sequence (if from-end
2464                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2465                                 (reverse (the list ,sequence)))
2466                         (nthcdr ,start ,sequence))))
2467      (declare (type list ,sequence))
2468      ,@body))
2469
2470 ) ; EVAL-WHEN
2471
2472 (eval-when (:compile-toplevel :execute)
2473
2474 (sb!xc:defmacro if-mismatch (elt1 elt2)
2475   `(cond ((= (the fixnum index1) (the fixnum end1))
2476           (return (if (= (the fixnum index2) (the fixnum end2))
2477                       nil
2478                       (if from-end
2479                           (1+ (the fixnum index1))
2480                           (the fixnum index1)))))
2481          ((= (the fixnum index2) (the fixnum end2))
2482           (return (if from-end (1+ (the fixnum index1)) index1)))
2483          (test-not
2484           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2485               (return (if from-end (1+ (the fixnum index1)) index1))))
2486          (t (if (not (funcall test (apply-key key ,elt1)
2487                               (apply-key key ,elt2)))
2488                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2489
2490 (sb!xc:defmacro mumble-mumble-mismatch ()
2491   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2492         (index2 start2 (+ index2 (the fixnum inc))))
2493        (())
2494      (declare (fixnum index1 index2))
2495      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2496
2497 (sb!xc:defmacro mumble-list-mismatch ()
2498   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2499         (index2 start2 (+ index2 (the fixnum inc))))
2500        (())
2501      (declare (fixnum index1 index2))
2502      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2503 \f
2504 (sb!xc:defmacro list-mumble-mismatch ()
2505   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2506         (index2 start2 (+ index2 (the fixnum inc))))
2507        (())
2508      (declare (fixnum index1 index2))
2509      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2510
2511 (sb!xc:defmacro list-list-mismatch ()
2512   `(do ((sequence1 sequence1)
2513         (sequence2 sequence2)
2514         (index1 start1 (+ index1 (the fixnum inc)))
2515         (index2 start2 (+ index2 (the fixnum inc))))
2516        (())
2517      (declare (fixnum index1 index2))
2518      (if-mismatch (pop sequence1) (pop sequence2))))
2519
2520 ) ; EVAL-WHEN
2521
2522 (define-sequence-traverser mismatch
2523     (sequence1 sequence2 &rest args &key from-end test test-not
2524      start1 end1 start2 end2 key)
2525   #!+sb-doc
2526   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2527    element-wise. If they are of equal length and match in every element, the
2528    result is NIL. Otherwise, the result is a non-negative integer, the index
2529    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2530    if one is shorter than and a matching prefix of the other, the index within
2531    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2532    :FROM-END argument is given, then one plus the index of the rightmost
2533    position in which the sequences differ is returned."
2534   (declare (fixnum start1 start2))
2535   (declare (truly-dynamic-extent args))
2536   (let* ((end1 (or end1 length1))
2537          (end2 (or end2 length2)))
2538     (declare (type index end1 end2))
2539     (match-vars
2540      (seq-dispatch sequence1
2541        (seq-dispatch sequence2
2542          (matchify-list (sequence1 start1 length1 end1)
2543            (matchify-list (sequence2 start2 length2 end2)
2544              (list-list-mismatch)))
2545          (matchify-list (sequence1 start1 length1 end1)
2546            (list-mumble-mismatch))
2547          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2548        (seq-dispatch sequence2
2549          (matchify-list (sequence2 start2 length2 end2)
2550            (mumble-list-mismatch))
2551          (mumble-mumble-mismatch)
2552          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2553        (apply #'sb!sequence:mismatch sequence1 sequence2 args)))))
2554 \f
2555 ;;; search comparison functions
2556
2557 (eval-when (:compile-toplevel :execute)
2558
2559 ;;; Compare two elements and return if they don't match.
2560 (sb!xc:defmacro compare-elements (elt1 elt2)
2561   `(if test-not
2562        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2563            (return nil)
2564            t)
2565        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2566            (return nil)
2567            t)))
2568
2569 (sb!xc:defmacro search-compare-list-list (main sub)
2570   `(do ((main ,main (cdr main))
2571         (jndex start1 (1+ jndex))
2572         (sub (nthcdr start1 ,sub) (cdr sub)))
2573        ((or (endp main) (endp sub) (<= end1 jndex))
2574         t)
2575      (declare (type (integer 0) jndex))
2576      (compare-elements (car sub) (car main))))
2577
2578 (sb!xc:defmacro search-compare-list-vector (main sub)
2579   `(do ((main ,main (cdr main))
2580         (index start1 (1+ index)))
2581        ((or (endp main) (= index end1)) t)
2582      (compare-elements (aref ,sub index) (car main))))
2583
2584 (sb!xc:defmacro search-compare-vector-list (main sub index)
2585   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2586         (jndex start1 (1+ jndex))
2587         (index ,index (1+ index)))
2588        ((or (<= end1 jndex) (endp sub)) t)
2589      (declare (type (integer 0) jndex))
2590      (compare-elements (car sub) (aref ,main index))))
2591
2592 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2593   `(do ((index ,index (1+ index))
2594         (sub-index start1 (1+ sub-index)))
2595        ((= sub-index end1) t)
2596      (compare-elements (aref ,sub sub-index) (aref ,main index))))
2597
2598 (sb!xc:defmacro search-compare (main-type main sub index)
2599   (if (eq main-type 'list)
2600       `(seq-dispatch ,sub
2601          (search-compare-list-list ,main ,sub)
2602          (search-compare-list-vector ,main ,sub)
2603          ;; KLUDGE: just hack it together so that it works
2604          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))
2605       `(seq-dispatch ,sub
2606          (search-compare-vector-list ,main ,sub ,index)
2607          (search-compare-vector-vector ,main ,sub ,index)
2608          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))))
2609
2610 ) ; EVAL-WHEN
2611 \f
2612 ;;;; SEARCH
2613
2614 (eval-when (:compile-toplevel :execute)
2615
2616 (sb!xc:defmacro list-search (main sub)
2617   `(do ((main (nthcdr start2 ,main) (cdr main))
2618         (index2 start2 (1+ index2))
2619         (terminus (- end2 (the (integer 0) (- end1 start1))))
2620         (last-match ()))
2621        ((> index2 terminus) last-match)
2622      (declare (type (integer 0) index2))
2623      (if (search-compare list main ,sub index2)
2624          (if from-end
2625              (setq last-match index2)
2626              (return index2)))))
2627
2628 (sb!xc:defmacro vector-search (main sub)
2629   `(do ((index2 start2 (1+ index2))
2630         (terminus (- end2 (the (integer 0) (- end1 start1))))
2631         (last-match ()))
2632        ((> index2 terminus) last-match)
2633      (declare (type (integer 0) index2))
2634      (if (search-compare vector ,main ,sub index2)
2635          (if from-end
2636              (setq last-match index2)
2637              (return index2)))))
2638
2639 ) ; EVAL-WHEN
2640
2641 (define-sequence-traverser search
2642     (sequence1 sequence2 &rest args &key
2643      from-end test test-not start1 end1 start2 end2 key)
2644   (declare (fixnum start1 start2))
2645   (declare (truly-dynamic-extent args))
2646   (let ((end1 (or end1 length1))
2647         (end2 (or end2 length2)))
2648     (seq-dispatch sequence2
2649       (list-search sequence2 sequence1)
2650       (vector-search sequence2 sequence1)
2651       (apply #'sb!sequence:search sequence1 sequence2 args))))
2652
2653 ;;; FIXME: this was originally in array.lisp; it might be better to
2654 ;;; put it back there, and make DOSEQUENCE and SEQ-DISPATCH be in
2655 ;;; a new early-seq.lisp file.
2656 (defun fill-data-vector (vector dimensions initial-contents)
2657   (let ((index 0))
2658     (labels ((frob (axis dims contents)
2659                (cond ((null dims)
2660                       (setf (aref vector index) contents)
2661                       (incf index))
2662                      (t
2663                       (unless (typep contents 'sequence)
2664                         (error "malformed :INITIAL-CONTENTS: ~S is not a ~
2665                                 sequence, but ~W more layer~:P needed."
2666                                contents
2667                                (- (length dimensions) axis)))
2668                       (unless (= (length contents) (car dims))
2669                         (error "malformed :INITIAL-CONTENTS: Dimension of ~
2670                                 axis ~W is ~W, but ~S is ~W long."
2671                                axis (car dims) contents (length contents)))
2672                       (sb!sequence:dosequence (content contents)
2673                         (frob (1+ axis) (cdr dims) content))))))
2674       (frob 0 dimensions initial-contents))))