90036a62c0432dc9318a27ab93b4c76602a4b625
[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             (do-vector-data (,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
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 ;;;; MAP-INTO
1055
1056 (defmacro map-into-lambda (sequences params &body body)
1057   (check-type sequences symbol)
1058   `(flet ((f ,params ,@body))
1059      (declare (truly-dynamic-extent #'f))
1060      ;; Note (MAP-INTO SEQ (LAMBDA () ...)) is a different animal,
1061      ;; hence the awkward flip between MAP and LOOP.
1062      (if ,sequences
1063          (apply #'map nil #'f ,sequences)
1064          (loop (f)))))
1065
1066 (define-array-dispatch vector-map-into (data start end fun sequences)
1067   (declare (optimize speed (safety 0))
1068            (type index start end)
1069            (type function fun)
1070            (type list sequences))
1071   (let ((index start))
1072     (declare (type index index))
1073     (block mapping
1074       (map-into-lambda sequences (&rest args)
1075         (declare (truly-dynamic-extent args))
1076         (when (eql index end)
1077           (return-from mapping))
1078         (setf (aref data index) (apply fun args))
1079         (incf index)))
1080     index))
1081
1082 ;;; Uses the machinery of (MAP NIL ...). For non-vectors we avoid
1083 ;;; computing the length of the result sequence since we can detect
1084 ;;; the end during mapping (if MAP even gets that far).
1085 ;;;
1086 ;;; For each result type, define a mapping function which is
1087 ;;; responsible for replacing RESULT-SEQUENCE elements and for
1088 ;;; terminating itself if the end of RESULT-SEQUENCE is reached.
1089 ;;; The mapping function is defined with MAP-INTO-LAMBDA.
1090 ;;;
1091 ;;; MAP-INTO-LAMBDAs are optimized since they are the inner loops.
1092 ;;; Because we are manually doing bounds checking with known types,
1093 ;;; safety is turned off for vectors and lists but kept for generic
1094 ;;; sequences.
1095 (defun map-into (result-sequence function &rest sequences)
1096   (let ((really-fun (%coerce-callable-to-fun function)))
1097     (etypecase result-sequence
1098       (vector
1099        (with-array-data ((data result-sequence) (start) (end)
1100                          ;; MAP-INTO ignores fill pointer when mapping
1101                          :check-fill-pointer nil)
1102          (let ((new-end (vector-map-into data start end really-fun sequences)))
1103            (when (array-has-fill-pointer-p result-sequence)
1104              (setf (fill-pointer result-sequence) (- new-end start))))))
1105       (list
1106        (let ((node result-sequence))
1107          (declare (type list node))
1108          (map-into-lambda sequences (&rest args)
1109            (declare (truly-dynamic-extent args)
1110                     (optimize speed (safety 0)))
1111            (when (null node)
1112              (return-from map-into result-sequence))
1113            (setf (car node) (apply really-fun args))
1114            (setf node (cdr node)))))
1115       (sequence
1116        (multiple-value-bind (iter limit from-end)
1117            (sb!sequence:make-sequence-iterator result-sequence)
1118          (map-into-lambda sequences (&rest args)
1119            (declare (truly-dynamic-extent args) (optimize speed))
1120            (when (sb!sequence:iterator-endp result-sequence
1121                                             iter limit from-end)
1122              (return-from map-into result-sequence))
1123            (setf (sb!sequence:iterator-element result-sequence iter)
1124                  (apply really-fun args))
1125            (setf iter (sb!sequence:iterator-step result-sequence
1126                                                            iter from-end)))))))
1127   result-sequence)
1128 \f
1129 ;;;; quantifiers
1130
1131 ;;; We borrow the logic from (MAP NIL ..) to handle iteration over
1132 ;;; arbitrary sequence arguments, both in the full call case and in
1133 ;;; the open code case.
1134 (macrolet ((defquantifier (name found-test found-result
1135                                 &key doc (unfound-result (not found-result)))
1136              `(progn
1137                 ;; KLUDGE: It would be really nice if we could simply
1138                 ;; do something like this
1139                 ;;  (declaim (inline ,name))
1140                 ;;  (defun ,name (pred first-seq &rest more-seqs)
1141                 ;;    ,doc
1142                 ;;    (flet ((map-me (&rest rest)
1143                 ;;             (let ((pred-value (apply pred rest)))
1144                 ;;               (,found-test pred-value
1145                 ;;                 (return-from ,name
1146                 ;;                   ,found-result)))))
1147                 ;;      (declare (inline map-me))
1148                 ;;      (apply #'map nil #'map-me first-seq more-seqs)
1149                 ;;      ,unfound-result))
1150                 ;; but Python doesn't seem to be smart enough about
1151                 ;; inlining and APPLY to recognize that it can use
1152                 ;; the DEFTRANSFORM for MAP in the resulting inline
1153                 ;; expansion. I don't have any appetite for deep
1154                 ;; compiler hacking right now, so I'll just work
1155                 ;; around the apparent problem by using a compiler
1156                 ;; macro instead. -- WHN 20000410
1157                 (defun ,name (pred first-seq &rest more-seqs)
1158                   #!+sb-doc ,doc
1159                   (flet ((map-me (&rest rest)
1160                            (let ((pred-value (apply pred rest)))
1161                              (,found-test pred-value
1162                                           (return-from ,name
1163                                             ,found-result)))))
1164                     (declare (inline map-me))
1165                     (apply #'map nil #'map-me first-seq more-seqs)
1166                     ,unfound-result))
1167                 ;; KLUDGE: It would be more obviously correct -- but
1168                 ;; also significantly messier -- for PRED-VALUE to be
1169                 ;; a gensym. However, a private symbol really does
1170                 ;; seem to be good enough; and anyway the really
1171                 ;; obviously correct solution is to make Python smart
1172                 ;; enough that we can use an inline function instead
1173                 ;; of a compiler macro (as above). -- WHN 20000410
1174                 ;;
1175                 ;; FIXME: The DEFINE-COMPILER-MACRO here can be
1176                 ;; important for performance, and it'd be good to have
1177                 ;; it be visible throughout the compilation of all the
1178                 ;; target SBCL code. That could be done by defining
1179                 ;; SB-XC:DEFINE-COMPILER-MACRO and using it here,
1180                 ;; moving this DEFQUANTIFIER stuff (and perhaps other
1181                 ;; inline definitions in seq.lisp as well) into a new
1182                 ;; seq.lisp, and moving remaining target-only stuff
1183                 ;; from the old seq.lisp into target-seq.lisp.
1184                 (define-compiler-macro ,name (pred first-seq &rest more-seqs)
1185                   (let ((elements (make-gensym-list (1+ (length more-seqs))))
1186                         (blockname (gensym "BLOCK")))
1187                     (once-only ((pred pred))
1188                       `(block ,blockname
1189                          (map nil
1190                               (lambda (,@elements)
1191                                 (let ((pred-value (funcall ,pred ,@elements)))
1192                                   (,',found-test pred-value
1193                                     (return-from ,blockname
1194                                       ,',found-result))))
1195                               ,first-seq
1196                               ,@more-seqs)
1197                          ,',unfound-result)))))))
1198   (defquantifier some when pred-value :unfound-result nil :doc
1199   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1200    possibly to those with index 1, and so on. Return the first
1201    non-NIL value encountered, or NIL if the end of any sequence is reached.")
1202   (defquantifier every unless 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 NIL, or T if every invocation
1206    is non-NIL.")
1207   (defquantifier notany when nil :doc
1208   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1209    possibly to those with index 1, and so on. Return NIL as soon
1210    as any invocation of PREDICATE returns a non-NIL value, or T if the end
1211    of any sequence is reached.")
1212   (defquantifier notevery unless t :doc
1213   "Apply PREDICATE to 0-indexed elements of the sequences, then
1214    possibly to those with index 1, and so on. Return T as soon
1215    as any invocation of PREDICATE returns NIL, or NIL if every invocation
1216    is non-NIL."))
1217 \f
1218 ;;;; REDUCE
1219
1220 (eval-when (:compile-toplevel :execute)
1221
1222 (sb!xc:defmacro mumble-reduce (function
1223                                sequence
1224                                key
1225                                start
1226                                end
1227                                initial-value
1228                                ref)
1229   `(do ((index ,start (1+ index))
1230         (value ,initial-value))
1231        ((>= index ,end) value)
1232      (setq value (funcall ,function value
1233                           (apply-key ,key (,ref ,sequence index))))))
1234
1235 (sb!xc:defmacro mumble-reduce-from-end (function
1236                                         sequence
1237                                         key
1238                                         start
1239                                         end
1240                                         initial-value
1241                                         ref)
1242   `(do ((index (1- ,end) (1- index))
1243         (value ,initial-value)
1244         (terminus (1- ,start)))
1245        ((<= index terminus) value)
1246      (setq value (funcall ,function
1247                           (apply-key ,key (,ref ,sequence index))
1248                           value))))
1249
1250 (sb!xc:defmacro list-reduce (function
1251                              sequence
1252                              key
1253                              start
1254                              end
1255                              initial-value
1256                              ivp)
1257   `(let ((sequence (nthcdr ,start ,sequence)))
1258      (do ((count (if ,ivp ,start (1+ ,start))
1259                  (1+ count))
1260           (sequence (if ,ivp sequence (cdr sequence))
1261                     (cdr sequence))
1262           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1263                  (funcall ,function value (apply-key ,key (car sequence)))))
1264          ((>= count ,end) value))))
1265
1266 (sb!xc:defmacro list-reduce-from-end (function
1267                                       sequence
1268                                       key
1269                                       start
1270                                       end
1271                                       initial-value
1272                                       ivp)
1273   `(let ((sequence (nthcdr (- (length ,sequence) ,end)
1274                            (reverse ,sequence))))
1275      (do ((count (if ,ivp ,start (1+ ,start))
1276                  (1+ count))
1277           (sequence (if ,ivp sequence (cdr sequence))
1278                     (cdr sequence))
1279           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1280                  (funcall ,function (apply-key ,key (car sequence)) value)))
1281          ((>= count ,end) value))))
1282
1283 ) ; EVAL-WHEN
1284
1285 (define-sequence-traverser reduce (function sequence &rest args &key key
1286                                    from-end start end (initial-value nil ivp))
1287   (declare (type index start))
1288   (declare (truly-dynamic-extent args))
1289   (let ((start start)
1290         (end (or end length)))
1291     (declare (type index start end))
1292     (seq-dispatch sequence
1293       (if (= end start)
1294           (if ivp initial-value (funcall function))
1295           (if from-end
1296               (list-reduce-from-end function sequence key start end
1297                                     initial-value ivp)
1298               (list-reduce function sequence key start end
1299                            initial-value ivp)))
1300       (if (= end start)
1301           (if ivp initial-value (funcall function))
1302           (if from-end
1303               (progn
1304                 (when (not ivp)
1305                   (setq end (1- (the fixnum end)))
1306                   (setq initial-value (apply-key key (aref sequence end))))
1307                 (mumble-reduce-from-end function sequence key start end
1308                                         initial-value aref))
1309               (progn
1310                 (when (not ivp)
1311                   (setq initial-value (apply-key key (aref sequence start)))
1312                   (setq start (1+ start)))
1313                 (mumble-reduce function sequence key start end
1314                                initial-value aref))))
1315       (apply #'sb!sequence:reduce function sequence args))))
1316 \f
1317 ;;;; DELETE
1318
1319 (eval-when (:compile-toplevel :execute)
1320
1321 (sb!xc:defmacro mumble-delete (pred)
1322   `(do ((index start (1+ index))
1323         (jndex start)
1324         (number-zapped 0))
1325        ((or (= index (the fixnum end)) (= number-zapped count))
1326         (do ((index index (1+ index))           ; Copy the rest of the vector.
1327              (jndex jndex (1+ jndex)))
1328             ((= index (the fixnum length))
1329              (shrink-vector sequence jndex))
1330           (declare (fixnum index jndex))
1331           (setf (aref sequence jndex) (aref sequence index))))
1332      (declare (fixnum index jndex number-zapped))
1333      (setf (aref sequence jndex) (aref sequence index))
1334      (if ,pred
1335          (incf number-zapped)
1336          (incf jndex))))
1337
1338 (sb!xc:defmacro mumble-delete-from-end (pred)
1339   `(do ((index (1- (the fixnum end)) (1- index)) ; Find the losers.
1340         (number-zapped 0)
1341         (losers ())
1342         this-element
1343         (terminus (1- start)))
1344        ((or (= index terminus) (= number-zapped count))
1345         (do ((losers losers)                     ; Delete the losers.
1346              (index start (1+ index))
1347              (jndex start))
1348             ((or (null losers) (= index (the fixnum end)))
1349              (do ((index index (1+ index))       ; Copy the rest of the vector.
1350                   (jndex jndex (1+ jndex)))
1351                  ((= index (the fixnum length))
1352                   (shrink-vector sequence jndex))
1353                (declare (fixnum index jndex))
1354                (setf (aref sequence jndex) (aref sequence index))))
1355           (declare (fixnum index jndex))
1356           (setf (aref sequence jndex) (aref sequence index))
1357           (if (= index (the fixnum (car losers)))
1358               (pop losers)
1359               (incf jndex))))
1360      (declare (fixnum index number-zapped terminus))
1361      (setq this-element (aref sequence index))
1362      (when ,pred
1363        (incf number-zapped)
1364        (push index losers))))
1365
1366 (sb!xc:defmacro normal-mumble-delete ()
1367   `(mumble-delete
1368     (if test-not
1369         (not (funcall test-not item (apply-key key (aref sequence index))))
1370         (funcall test item (apply-key key (aref sequence index))))))
1371
1372 (sb!xc:defmacro normal-mumble-delete-from-end ()
1373   `(mumble-delete-from-end
1374     (if test-not
1375         (not (funcall test-not item (apply-key key this-element)))
1376         (funcall test item (apply-key key this-element)))))
1377
1378 (sb!xc:defmacro list-delete (pred)
1379   `(let ((handle (cons nil sequence)))
1380      (do ((current (nthcdr start sequence) (cdr current))
1381           (previous (nthcdr start handle))
1382           (index start (1+ index))
1383           (number-zapped 0))
1384          ((or (= index (the fixnum end)) (= number-zapped count))
1385           (cdr handle))
1386        (declare (fixnum index number-zapped))
1387        (cond (,pred
1388               (rplacd previous (cdr current))
1389               (incf number-zapped))
1390              (t
1391               (setq previous (cdr previous)))))))
1392
1393 (sb!xc:defmacro list-delete-from-end (pred)
1394   `(let* ((reverse (nreverse (the list sequence)))
1395           (handle (cons nil reverse)))
1396      (do ((current (nthcdr (- (the fixnum length) (the fixnum end)) reverse)
1397                    (cdr current))
1398           (previous (nthcdr (- (the fixnum length) (the fixnum end)) handle))
1399           (index start (1+ index))
1400           (number-zapped 0))
1401          ((or (= index (the fixnum end)) (= number-zapped count))
1402           (nreverse (cdr handle)))
1403        (declare (fixnum index number-zapped))
1404        (cond (,pred
1405               (rplacd previous (cdr current))
1406               (incf number-zapped))
1407              (t
1408               (setq previous (cdr previous)))))))
1409
1410 (sb!xc:defmacro normal-list-delete ()
1411   '(list-delete
1412     (if test-not
1413         (not (funcall test-not item (apply-key key (car current))))
1414         (funcall test item (apply-key key (car current))))))
1415
1416 (sb!xc:defmacro normal-list-delete-from-end ()
1417   '(list-delete-from-end
1418     (if test-not
1419         (not (funcall test-not item (apply-key key (car current))))
1420         (funcall test item (apply-key key (car current))))))
1421
1422 ) ; EVAL-WHEN
1423
1424 (define-sequence-traverser delete
1425     (item sequence &rest args &key from-end test test-not start
1426      end count key)
1427   #!+sb-doc
1428   "Return a sequence formed by destructively removing the specified ITEM from
1429   the given SEQUENCE."
1430   (declare (fixnum start))
1431   (declare (truly-dynamic-extent args))
1432   (let ((end (or end length)))
1433     (declare (type index end))
1434     (seq-dispatch sequence
1435       (if from-end
1436           (normal-list-delete-from-end)
1437           (normal-list-delete))
1438       (if from-end
1439           (normal-mumble-delete-from-end)
1440           (normal-mumble-delete))
1441       (apply #'sb!sequence:delete item sequence args))))
1442
1443 (eval-when (:compile-toplevel :execute)
1444
1445 (sb!xc:defmacro if-mumble-delete ()
1446   `(mumble-delete
1447     (funcall predicate (apply-key key (aref sequence index)))))
1448
1449 (sb!xc:defmacro if-mumble-delete-from-end ()
1450   `(mumble-delete-from-end
1451     (funcall predicate (apply-key key this-element))))
1452
1453 (sb!xc:defmacro if-list-delete ()
1454   '(list-delete
1455     (funcall predicate (apply-key key (car current)))))
1456
1457 (sb!xc:defmacro if-list-delete-from-end ()
1458   '(list-delete-from-end
1459     (funcall predicate (apply-key key (car current)))))
1460
1461 ) ; EVAL-WHEN
1462
1463 (define-sequence-traverser delete-if
1464     (predicate sequence &rest args &key from-end start key end count)
1465   #!+sb-doc
1466   "Return a sequence formed by destructively removing the elements satisfying
1467   the specified PREDICATE from the given SEQUENCE."
1468   (declare (fixnum start))
1469   (declare (truly-dynamic-extent args))
1470   (let ((end (or end length)))
1471     (declare (type index end))
1472     (seq-dispatch sequence
1473       (if from-end
1474           (if-list-delete-from-end)
1475           (if-list-delete))
1476       (if from-end
1477           (if-mumble-delete-from-end)
1478           (if-mumble-delete))
1479       (apply #'sb!sequence:delete-if predicate sequence args))))
1480
1481 (eval-when (:compile-toplevel :execute)
1482
1483 (sb!xc:defmacro if-not-mumble-delete ()
1484   `(mumble-delete
1485     (not (funcall predicate (apply-key key (aref sequence index))))))
1486
1487 (sb!xc:defmacro if-not-mumble-delete-from-end ()
1488   `(mumble-delete-from-end
1489     (not (funcall predicate (apply-key key this-element)))))
1490
1491 (sb!xc:defmacro if-not-list-delete ()
1492   '(list-delete
1493     (not (funcall predicate (apply-key key (car current))))))
1494
1495 (sb!xc:defmacro if-not-list-delete-from-end ()
1496   '(list-delete-from-end
1497     (not (funcall predicate (apply-key key (car current))))))
1498
1499 ) ; EVAL-WHEN
1500
1501 (define-sequence-traverser delete-if-not
1502     (predicate sequence &rest args &key from-end start end key count)
1503   #!+sb-doc
1504   "Return a sequence formed by destructively removing the elements not
1505   satisfying the specified PREDICATE from the given SEQUENCE."
1506   (declare (fixnum start))
1507   (declare (truly-dynamic-extent args))
1508   (let ((end (or end length)))
1509     (declare (type index end))
1510     (seq-dispatch sequence
1511       (if from-end
1512           (if-not-list-delete-from-end)
1513           (if-not-list-delete))
1514       (if from-end
1515           (if-not-mumble-delete-from-end)
1516           (if-not-mumble-delete))
1517       (apply #'sb!sequence:delete-if-not predicate sequence args))))
1518 \f
1519 ;;;; REMOVE
1520
1521 (eval-when (:compile-toplevel :execute)
1522
1523 ;;; MUMBLE-REMOVE-MACRO does not include (removes) each element that
1524 ;;; satisfies the predicate.
1525 (sb!xc:defmacro mumble-remove-macro (bump left begin finish right pred)
1526   `(do ((index ,begin (,bump index))
1527         (result
1528          (do ((index ,left (,bump index))
1529               (result (%make-sequence-like sequence length)))
1530              ((= index (the fixnum ,begin)) result)
1531            (declare (fixnum index))
1532            (setf (aref result index) (aref sequence index))))
1533         (new-index ,begin)
1534         (number-zapped 0)
1535         (this-element))
1536        ((or (= index (the fixnum ,finish))
1537             (= number-zapped count))
1538         (do ((index index (,bump index))
1539              (new-index new-index (,bump new-index)))
1540             ((= index (the fixnum ,right)) (%shrink-vector result new-index))
1541           (declare (fixnum index new-index))
1542           (setf (aref result new-index) (aref sequence index))))
1543      (declare (fixnum index new-index number-zapped))
1544      (setq this-element (aref sequence index))
1545      (cond (,pred (incf number-zapped))
1546            (t (setf (aref result new-index) this-element)
1547               (setq new-index (,bump new-index))))))
1548
1549 (sb!xc:defmacro mumble-remove (pred)
1550   `(mumble-remove-macro 1+ 0 start end length ,pred))
1551
1552 (sb!xc:defmacro mumble-remove-from-end (pred)
1553   `(let ((sequence (copy-seq sequence)))
1554      (mumble-delete-from-end ,pred)))
1555
1556 (sb!xc:defmacro normal-mumble-remove ()
1557   `(mumble-remove
1558     (if test-not
1559         (not (funcall test-not item (apply-key key this-element)))
1560         (funcall test item (apply-key key this-element)))))
1561
1562 (sb!xc:defmacro normal-mumble-remove-from-end ()
1563   `(mumble-remove-from-end
1564     (if test-not
1565         (not (funcall test-not item (apply-key key this-element)))
1566         (funcall test item (apply-key key this-element)))))
1567
1568 (sb!xc:defmacro if-mumble-remove ()
1569   `(mumble-remove (funcall predicate (apply-key key this-element))))
1570
1571 (sb!xc:defmacro if-mumble-remove-from-end ()
1572   `(mumble-remove-from-end (funcall predicate (apply-key key this-element))))
1573
1574 (sb!xc:defmacro if-not-mumble-remove ()
1575   `(mumble-remove (not (funcall predicate (apply-key key this-element)))))
1576
1577 (sb!xc:defmacro if-not-mumble-remove-from-end ()
1578   `(mumble-remove-from-end
1579     (not (funcall predicate (apply-key key this-element)))))
1580
1581 ;;; LIST-REMOVE-MACRO does not include (removes) each element that satisfies
1582 ;;; the predicate.
1583 (sb!xc:defmacro list-remove-macro (pred reverse?)
1584   `(let* ((sequence ,(if reverse?
1585                          '(reverse (the list sequence))
1586                          'sequence))
1587           (%start ,(if reverse? '(- length end) 'start))
1588           (%end ,(if reverse? '(- length start) 'end))
1589           (splice (list nil))
1590           (results (do ((index 0 (1+ index))
1591                         (before-start splice))
1592                        ((= index (the fixnum %start)) before-start)
1593                      (declare (fixnum index))
1594                      (setq splice
1595                            (cdr (rplacd splice (list (pop sequence))))))))
1596      (do ((index %start (1+ index))
1597           (this-element)
1598           (number-zapped 0))
1599          ((or (= index (the fixnum %end)) (= number-zapped count))
1600           (do ((index index (1+ index)))
1601               ((null sequence)
1602                ,(if reverse?
1603                     '(nreverse (the list (cdr results)))
1604                     '(cdr results)))
1605             (declare (fixnum index))
1606             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1607        (declare (fixnum index number-zapped))
1608        (setq this-element (pop sequence))
1609        (if ,pred
1610            (setq number-zapped (1+ number-zapped))
1611            (setq splice (cdr (rplacd splice (list this-element))))))))
1612
1613 (sb!xc:defmacro list-remove (pred)
1614   `(list-remove-macro ,pred nil))
1615
1616 (sb!xc:defmacro list-remove-from-end (pred)
1617   `(list-remove-macro ,pred t))
1618
1619 (sb!xc:defmacro normal-list-remove ()
1620   `(list-remove
1621     (if test-not
1622         (not (funcall test-not item (apply-key key this-element)))
1623         (funcall test item (apply-key key this-element)))))
1624
1625 (sb!xc:defmacro normal-list-remove-from-end ()
1626   `(list-remove-from-end
1627     (if test-not
1628         (not (funcall test-not item (apply-key key this-element)))
1629         (funcall test item (apply-key key this-element)))))
1630
1631 (sb!xc:defmacro if-list-remove ()
1632   `(list-remove
1633     (funcall predicate (apply-key key this-element))))
1634
1635 (sb!xc:defmacro if-list-remove-from-end ()
1636   `(list-remove-from-end
1637     (funcall predicate (apply-key key this-element))))
1638
1639 (sb!xc:defmacro if-not-list-remove ()
1640   `(list-remove
1641     (not (funcall predicate (apply-key key this-element)))))
1642
1643 (sb!xc:defmacro if-not-list-remove-from-end ()
1644   `(list-remove-from-end
1645     (not (funcall predicate (apply-key key this-element)))))
1646
1647 ) ; EVAL-WHEN
1648
1649 (define-sequence-traverser remove
1650     (item sequence &rest args &key from-end test test-not start
1651      end count key)
1652   #!+sb-doc
1653   "Return a copy of SEQUENCE with elements satisfying the test (default is
1654    EQL) with ITEM removed."
1655   (declare (fixnum start))
1656   (declare (truly-dynamic-extent args))
1657   (let ((end (or end length)))
1658     (declare (type index end))
1659     (seq-dispatch sequence
1660       (if from-end
1661           (normal-list-remove-from-end)
1662           (normal-list-remove))
1663       (if from-end
1664           (normal-mumble-remove-from-end)
1665           (normal-mumble-remove))
1666       (apply #'sb!sequence:remove item sequence args))))
1667
1668 (define-sequence-traverser remove-if
1669     (predicate sequence &rest args &key from-end start end count key)
1670   #!+sb-doc
1671   "Return a copy of sequence with elements satisfying PREDICATE removed."
1672   (declare (fixnum start))
1673   (declare (truly-dynamic-extent args))
1674   (let ((end (or end length)))
1675     (declare (type index end))
1676     (seq-dispatch sequence
1677       (if from-end
1678           (if-list-remove-from-end)
1679           (if-list-remove))
1680       (if from-end
1681           (if-mumble-remove-from-end)
1682           (if-mumble-remove))
1683       (apply #'sb!sequence:remove-if predicate sequence args))))
1684
1685 (define-sequence-traverser remove-if-not
1686     (predicate sequence &rest args &key from-end start end count key)
1687   #!+sb-doc
1688   "Return a copy of sequence with elements not satisfying PREDICATE removed."
1689   (declare (fixnum start))
1690   (declare (truly-dynamic-extent args))
1691   (let ((end (or end length)))
1692     (declare (type index end))
1693     (seq-dispatch sequence
1694       (if from-end
1695           (if-not-list-remove-from-end)
1696           (if-not-list-remove))
1697       (if from-end
1698           (if-not-mumble-remove-from-end)
1699           (if-not-mumble-remove))
1700       (apply #'sb!sequence:remove-if-not predicate sequence args))))
1701 \f
1702 ;;;; REMOVE-DUPLICATES
1703
1704 ;;; Remove duplicates from a list. If from-end, remove the later duplicates,
1705 ;;; not the earlier ones. Thus if we check from-end we don't copy an item
1706 ;;; if we look into the already copied structure (from after :start) and see
1707 ;;; the item. If we check from beginning we check into the rest of the
1708 ;;; original list up to the :end marker (this we have to do by running a
1709 ;;; do loop down the list that far and using our test.
1710 (defun list-remove-duplicates* (list test test-not start end key from-end)
1711   (declare (fixnum start))
1712   (let* ((result (list ())) ; Put a marker on the beginning to splice with.
1713          (splice result)
1714          (current list)
1715          (end (or end (length list)))
1716          (hash (and (> (- end start) 20)
1717                     test
1718                     (not key)
1719                     (not test-not)
1720                     (or (eql test #'eql)
1721                         (eql test #'eq)
1722                         (eql test #'equal)
1723                         (eql test #'equalp))
1724                     (make-hash-table :test test :size (- end start)))))
1725     (do ((index 0 (1+ index)))
1726         ((= index start))
1727       (declare (fixnum index))
1728       (setq splice (cdr (rplacd splice (list (car current)))))
1729       (setq current (cdr current)))
1730     (if hash
1731         (do ((index start (1+ index)))
1732             ((or (and end (= index (the fixnum end)))
1733                  (atom current)))
1734           (declare (fixnum index))
1735           ;; The hash table contains links from values that are
1736           ;; already in result to the cons cell *preceding* theirs
1737           ;; in the list.  That is, for each value v in the list,
1738           ;; v and (cadr (gethash v hash)) are equal under TEST.
1739           (let ((prev (gethash (car current) hash)))
1740             (cond
1741              ((not prev)
1742               (setf (gethash (car current) hash) splice)
1743               (setq splice (cdr (rplacd splice (list (car current))))))
1744              ((not from-end)
1745               (let* ((old (cdr prev))
1746                      (next (cdr old)))
1747                 (if next
1748                   (let ((next-val (car next)))
1749                     ;; (assert (eq (gethash next-val hash) old))
1750                     (setf (cdr prev) next
1751                           (gethash next-val hash) prev
1752                           (gethash (car current) hash) splice
1753                           splice (cdr (rplacd splice (list (car current))))))
1754                   (setf (car old) (car current)))))))
1755           (setq current (cdr current)))
1756       (do ((index start (1+ index)))
1757           ((or (and end (= index (the fixnum end)))
1758                (atom current)))
1759         (declare (fixnum index))
1760         (if (or (and from-end
1761                      (not (if test-not
1762                               (member (apply-key key (car current))
1763                                       (nthcdr (1+ start) result)
1764                                       :test-not test-not
1765                                       :key key)
1766                             (member (apply-key key (car current))
1767                                     (nthcdr (1+ start) result)
1768                                     :test test
1769                                     :key key))))
1770                 (and (not from-end)
1771                      (not (do ((it (apply-key key (car current)))
1772                                (l (cdr current) (cdr l))
1773                                (i (1+ index) (1+ i)))
1774                               ((or (atom l) (and end (= i (the fixnum end))))
1775                                ())
1776                             (declare (fixnum i))
1777                             (if (if test-not
1778                                     (not (funcall test-not
1779                                                   it
1780                                                   (apply-key key (car l))))
1781                                   (funcall test it (apply-key key (car l))))
1782                                 (return t))))))
1783             (setq splice (cdr (rplacd splice (list (car current))))))
1784         (setq current (cdr current))))
1785     (do ()
1786         ((atom current))
1787       (setq splice (cdr (rplacd splice (list (car current)))))
1788       (setq current (cdr current)))
1789     (cdr result)))
1790
1791 (defun vector-remove-duplicates* (vector test test-not start end key from-end
1792                                          &optional (length (length vector)))
1793   (declare (vector vector) (fixnum start length))
1794   (when (null end) (setf end (length vector)))
1795   (let ((result (%make-sequence-like vector length))
1796         (index 0)
1797         (jndex start))
1798     (declare (fixnum index jndex))
1799     (do ()
1800         ((= index start))
1801       (setf (aref result index) (aref vector index))
1802       (setq index (1+ index)))
1803     (do ((elt))
1804         ((= index end))
1805       (setq elt (aref vector index))
1806       (unless (or (and from-end
1807                        (if test-not
1808                            (position (apply-key key elt) result
1809                                      :start start :end jndex
1810                                      :test-not test-not :key key)
1811                            (position (apply-key key elt) result
1812                                      :start start :end jndex
1813                                      :test test :key key)))
1814                   (and (not from-end)
1815                        (if test-not
1816                            (position (apply-key key elt) vector
1817                                      :start (1+ index) :end end
1818                                      :test-not test-not :key key)
1819                            (position (apply-key key elt) vector
1820                                      :start (1+ index) :end end
1821                                      :test test :key key))))
1822         (setf (aref result jndex) elt)
1823         (setq jndex (1+ jndex)))
1824       (setq index (1+ index)))
1825     (do ()
1826         ((= index length))
1827       (setf (aref result jndex) (aref vector index))
1828       (setq index (1+ index))
1829       (setq jndex (1+ jndex)))
1830     (%shrink-vector result jndex)))
1831
1832 (define-sequence-traverser remove-duplicates
1833     (sequence &rest args &key test test-not start end from-end key)
1834   #!+sb-doc
1835   "The elements of SEQUENCE are compared pairwise, and if any two match,
1836    the one occurring earlier is discarded, unless FROM-END is true, in
1837    which case the one later in the sequence is discarded. The resulting
1838    sequence is returned.
1839
1840    The :TEST-NOT argument is deprecated."
1841   (declare (fixnum start))
1842   (declare (truly-dynamic-extent args))
1843   (seq-dispatch sequence
1844     (if sequence
1845         (list-remove-duplicates* sequence test test-not
1846                                  start end key from-end))
1847     (vector-remove-duplicates* sequence test test-not start end key from-end)
1848     (apply #'sb!sequence:remove-duplicates sequence args)))
1849 \f
1850 ;;;; DELETE-DUPLICATES
1851
1852 (defun list-delete-duplicates* (list test test-not key from-end start end)
1853   (declare (fixnum start))
1854   (let ((handle (cons nil list)))
1855     (do ((current (nthcdr start list) (cdr current))
1856          (previous (nthcdr start handle))
1857          (index start (1+ index)))
1858         ((or (and end (= index (the fixnum end))) (null current))
1859          (cdr handle))
1860       (declare (fixnum index))
1861       (if (do ((x (if from-end
1862                       (nthcdr (1+ start) handle)
1863                       (cdr current))
1864                   (cdr x))
1865                (i (1+ index) (1+ i)))
1866               ((or (null x)
1867                    (and (not from-end) end (= i (the fixnum end)))
1868                    (eq x current))
1869                nil)
1870             (declare (fixnum i))
1871             (if (if test-not
1872                     (not (funcall test-not
1873                                   (apply-key key (car current))
1874                                   (apply-key key (car x))))
1875                     (funcall test
1876                              (apply-key key (car current))
1877                              (apply-key key (car x))))
1878                 (return t)))
1879           (rplacd previous (cdr current))
1880           (setq previous (cdr previous))))))
1881
1882 (defun vector-delete-duplicates* (vector test test-not key from-end start end
1883                                          &optional (length (length vector)))
1884   (declare (vector vector) (fixnum start length))
1885   (when (null end) (setf end (length vector)))
1886   (do ((index start (1+ index))
1887        (jndex start))
1888       ((= index end)
1889        (do ((index index (1+ index))            ; copy the rest of the vector
1890             (jndex jndex (1+ jndex)))
1891            ((= index length)
1892             (shrink-vector vector jndex))
1893          (setf (aref vector jndex) (aref vector index))))
1894     (declare (fixnum index jndex))
1895     (setf (aref vector jndex) (aref vector index))
1896     (unless (if test-not
1897                 (position (apply-key key (aref vector index)) vector :key key
1898                           :start (if from-end start (1+ index))
1899                           :end (if from-end jndex end)
1900                           :test-not test-not)
1901                 (position (apply-key key (aref vector index)) vector :key key
1902                           :start (if from-end start (1+ index))
1903                           :end (if from-end jndex end)
1904                           :test test))
1905       (setq jndex (1+ jndex)))))
1906
1907 (define-sequence-traverser delete-duplicates
1908     (sequence &rest args &key test test-not start end from-end key)
1909   #!+sb-doc
1910   "The elements of SEQUENCE are examined, and if any two match, one is
1911    discarded. The resulting sequence, which may be formed by destroying the
1912    given sequence, is returned.
1913
1914    The :TEST-NOT argument is deprecated."
1915   (declare (truly-dynamic-extent args))
1916   (seq-dispatch sequence
1917     (if sequence
1918         (list-delete-duplicates* sequence test test-not
1919                                  key from-end start end))
1920     (vector-delete-duplicates* sequence test test-not key from-end start end)
1921     (apply #'sb!sequence:delete-duplicates sequence args)))
1922 \f
1923 ;;;; SUBSTITUTE
1924
1925 (defun list-substitute* (pred new list start end count key test test-not old)
1926   (declare (fixnum start end count))
1927   (let* ((result (list nil))
1928          elt
1929          (splice result)
1930          (list list))      ; Get a local list for a stepper.
1931     (do ((index 0 (1+ index)))
1932         ((= index start))
1933       (declare (fixnum index))
1934       (setq splice (cdr (rplacd splice (list (car list)))))
1935       (setq list (cdr list)))
1936     (do ((index start (1+ index)))
1937         ((or (= index end) (null list) (= count 0)))
1938       (declare (fixnum index))
1939       (setq elt (car list))
1940       (setq splice
1941             (cdr (rplacd splice
1942                          (list
1943                           (cond
1944                            ((case pred
1945                                    (normal
1946                                     (if test-not
1947                                         (not
1948                                          (funcall test-not old (apply-key key elt)))
1949                                         (funcall test old (apply-key key elt))))
1950                                    (if (funcall test (apply-key key elt)))
1951                                    (if-not (not (funcall test (apply-key key elt)))))
1952                             (decf count)
1953                             new)
1954                                 (t elt))))))
1955       (setq list (cdr list)))
1956     (do ()
1957         ((null list))
1958       (setq splice (cdr (rplacd splice (list (car list)))))
1959       (setq list (cdr list)))
1960     (cdr result)))
1961
1962 ;;; Replace old with new in sequence moving from left to right by incrementer
1963 ;;; on each pass through the loop. Called by all three substitute functions.
1964 (defun vector-substitute* (pred new sequence incrementer left right length
1965                            start end count key test test-not old)
1966   (declare (fixnum start count end incrementer right))
1967   (let ((result (%make-sequence-like sequence length))
1968         (index left))
1969     (declare (fixnum index))
1970     (do ()
1971         ((= index start))
1972       (setf (aref result index) (aref sequence index))
1973       (setq index (+ index incrementer)))
1974     (do ((elt))
1975         ((or (= index end) (= count 0)))
1976       (setq elt (aref sequence index))
1977       (setf (aref result index)
1978             (cond ((case pred
1979                           (normal
1980                             (if test-not
1981                                 (not (funcall test-not old (apply-key key elt)))
1982                                 (funcall test old (apply-key key elt))))
1983                           (if (funcall test (apply-key key elt)))
1984                           (if-not (not (funcall test (apply-key key elt)))))
1985                    (setq count (1- count))
1986                    new)
1987                   (t elt)))
1988       (setq index (+ index incrementer)))
1989     (do ()
1990         ((= index right))
1991       (setf (aref result index) (aref sequence index))
1992       (setq index (+ index incrementer)))
1993     result))
1994
1995 (eval-when (:compile-toplevel :execute)
1996
1997 (sb!xc:defmacro subst-dispatch (pred)
1998   `(seq-dispatch sequence
1999      (if from-end
2000          (nreverse (list-substitute* ,pred
2001                                      new
2002                                      (reverse sequence)
2003                                      (- (the fixnum length)
2004                                         (the fixnum end))
2005                                      (- (the fixnum length)
2006                                         (the fixnum start))
2007                                      count key test test-not old))
2008          (list-substitute* ,pred
2009                            new sequence start end count key test test-not
2010                            old))
2011     (if from-end
2012         (vector-substitute* ,pred new sequence -1 (1- (the fixnum length))
2013                             -1 length (1- (the fixnum end))
2014                             (1- (the fixnum start))
2015                             count key test test-not old)
2016         (vector-substitute* ,pred new sequence 1 0 length length
2017                             start end count key test test-not old))
2018     ;; FIXME: wow, this is an odd way to implement the dispatch.  PRED
2019     ;; here is (QUOTE [NORMAL|IF|IF-NOT]).  Not only is this pretty
2020     ;; pointless, but also LIST-SUBSTITUTE* and VECTOR-SUBSTITUTE*
2021     ;; dispatch once per element on PRED's run-time identity.
2022     ,(ecase (cadr pred)
2023        ((normal) `(apply #'sb!sequence:substitute new old sequence args))
2024        ((if) `(apply #'sb!sequence:substitute-if new predicate sequence args))
2025        ((if-not) `(apply #'sb!sequence:substitute-if-not new predicate sequence args)))))
2026 ) ; EVAL-WHEN
2027
2028 (define-sequence-traverser substitute
2029     (new old sequence &rest args &key from-end test test-not
2030          start count end key)
2031   #!+sb-doc
2032   "Return a sequence of the same kind as SEQUENCE with the same elements,
2033   except that all elements equal to OLD are replaced with NEW."
2034   (declare (fixnum start))
2035   (declare (truly-dynamic-extent args))
2036   (let ((end (or end length)))
2037     (declare (type index end))
2038     (subst-dispatch 'normal)))
2039 \f
2040 ;;;; SUBSTITUTE-IF, SUBSTITUTE-IF-NOT
2041
2042 (define-sequence-traverser substitute-if
2043     (new predicate sequence &rest args &key from-end start end count key)
2044   #!+sb-doc
2045   "Return a sequence of the same kind as SEQUENCE with the same elements
2046   except that all elements satisfying the PRED are replaced with NEW."
2047   (declare (truly-dynamic-extent args))
2048   (declare (fixnum start))
2049   (let ((end (or end length))
2050         (test predicate)
2051         (test-not nil)
2052         old)
2053     (declare (type index length end))
2054     (subst-dispatch 'if)))
2055
2056 (define-sequence-traverser substitute-if-not
2057     (new predicate sequence &rest args &key from-end start end count key)
2058   #!+sb-doc
2059   "Return a sequence of the same kind as SEQUENCE with the same elements
2060   except that all elements not satisfying the PRED are replaced with NEW."
2061   (declare (truly-dynamic-extent args))
2062   (declare (fixnum start))
2063   (let ((end (or end length))
2064         (test predicate)
2065         (test-not nil)
2066         old)
2067     (declare (type index length end))
2068     (subst-dispatch 'if-not)))
2069 \f
2070 ;;;; NSUBSTITUTE
2071
2072 (define-sequence-traverser nsubstitute
2073     (new old sequence &rest args &key from-end test test-not
2074          end count key start)
2075   #!+sb-doc
2076   "Return a sequence of the same kind as SEQUENCE with the same elements
2077   except that all elements equal to OLD are replaced with NEW. SEQUENCE
2078   may be destructively modified."
2079   (declare (fixnum start))
2080   (declare (truly-dynamic-extent args))
2081   (let ((end (or end length)))
2082     (seq-dispatch sequence
2083       (if from-end
2084           (let ((length (length sequence)))
2085             (nreverse (nlist-substitute*
2086                        new old (nreverse (the list sequence))
2087                        test test-not (- length end) (- length start)
2088                        count key)))
2089           (nlist-substitute* new old sequence
2090                              test test-not start end count key))
2091       (if from-end
2092           (nvector-substitute* new old sequence -1
2093                                test test-not (1- end) (1- start) count key)
2094           (nvector-substitute* new old sequence 1
2095                                test test-not start end count key))
2096       (apply #'sb!sequence:nsubstitute new old sequence args))))
2097
2098 (defun nlist-substitute* (new old sequence test test-not start end count key)
2099   (declare (fixnum start count end))
2100   (do ((list (nthcdr start sequence) (cdr list))
2101        (index start (1+ index)))
2102       ((or (= index end) (null list) (= count 0)) sequence)
2103     (declare (fixnum index))
2104     (when (if test-not
2105               (not (funcall test-not old (apply-key key (car list))))
2106               (funcall test old (apply-key key (car list))))
2107       (rplaca list new)
2108       (setq count (1- count)))))
2109
2110 (defun nvector-substitute* (new old sequence incrementer
2111                             test test-not start end count key)
2112   (declare (fixnum start incrementer count end))
2113   (do ((index start (+ index incrementer)))
2114       ((or (= index end) (= count 0)) sequence)
2115     (declare (fixnum index))
2116     (when (if test-not
2117               (not (funcall test-not
2118                             old
2119                             (apply-key key (aref sequence index))))
2120               (funcall test old (apply-key key (aref sequence index))))
2121       (setf (aref sequence index) new)
2122       (setq count (1- count)))))
2123 \f
2124 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
2125
2126 (define-sequence-traverser nsubstitute-if
2127     (new predicate sequence &rest args &key from-end start end count key)
2128   #!+sb-doc
2129   "Return a sequence of the same kind as SEQUENCE with the same elements
2130    except that all elements satisfying PREDICATE are replaced with NEW.
2131    SEQUENCE may be destructively modified."
2132   (declare (fixnum start))
2133   (declare (truly-dynamic-extent args))
2134   (let ((end (or end length)))
2135     (declare (fixnum end))
2136     (seq-dispatch sequence
2137       (if from-end
2138           (let ((length (length sequence)))
2139             (nreverse (nlist-substitute-if*
2140                        new predicate (nreverse (the list sequence))
2141                        (- length end) (- length start) count key)))
2142           (nlist-substitute-if* new predicate sequence
2143                                 start end count key))
2144       (if from-end
2145           (nvector-substitute-if* new predicate sequence -1
2146                                   (1- end) (1- start) count key)
2147           (nvector-substitute-if* new predicate sequence 1
2148                                   start end count key))
2149       (apply #'sb!sequence:nsubstitute-if new predicate sequence args))))
2150
2151 (defun nlist-substitute-if* (new test sequence start end count key)
2152   (declare (fixnum end))
2153   (do ((list (nthcdr start sequence) (cdr list))
2154        (index start (1+ index)))
2155       ((or (= index end) (null list) (= count 0)) sequence)
2156     (when (funcall test (apply-key key (car list)))
2157       (rplaca list new)
2158       (setq count (1- count)))))
2159
2160 (defun nvector-substitute-if* (new test sequence incrementer
2161                                start end count key)
2162   (do ((index start (+ index incrementer)))
2163       ((or (= index end) (= count 0)) sequence)
2164     (when (funcall test (apply-key key (aref sequence index)))
2165       (setf (aref sequence index) new)
2166       (setq count (1- count)))))
2167
2168 (define-sequence-traverser nsubstitute-if-not
2169     (new predicate sequence &rest args &key from-end start end count key)
2170   #!+sb-doc
2171   "Return a sequence of the same kind as SEQUENCE with the same elements
2172    except that all elements not satisfying PREDICATE are replaced with NEW.
2173    SEQUENCE may be destructively modified."
2174   (declare (fixnum start))
2175   (declare (truly-dynamic-extent args))
2176   (let ((end (or end length)))
2177     (declare (fixnum end))
2178     (seq-dispatch sequence
2179       (if from-end
2180           (let ((length (length sequence)))
2181             (nreverse (nlist-substitute-if-not*
2182                        new predicate (nreverse (the list sequence))
2183                        (- length end) (- length start) count key)))
2184           (nlist-substitute-if-not* new predicate sequence
2185                                     start end count key))
2186       (if from-end
2187           (nvector-substitute-if-not* new predicate sequence -1
2188                                       (1- end) (1- start) count key)
2189           (nvector-substitute-if-not* new predicate sequence 1
2190                                       start end count key))
2191       (apply #'sb!sequence:nsubstitute-if-not new predicate sequence args))))
2192
2193 (defun nlist-substitute-if-not* (new test sequence start end count key)
2194   (declare (fixnum end))
2195   (do ((list (nthcdr start sequence) (cdr list))
2196        (index start (1+ index)))
2197       ((or (= index end) (null list) (= count 0)) sequence)
2198     (when (not (funcall test (apply-key key (car list))))
2199       (rplaca list new)
2200       (decf count))))
2201
2202 (defun nvector-substitute-if-not* (new test sequence incrementer
2203                                    start end count key)
2204   (do ((index start (+ index incrementer)))
2205       ((or (= index end) (= count 0)) sequence)
2206     (when (not (funcall test (apply-key key (aref sequence index))))
2207       (setf (aref sequence index) new)
2208       (decf count))))
2209 \f
2210 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
2211
2212 (defun effective-find-position-test (test test-not)
2213   (effective-find-position-test test test-not))
2214 (defun effective-find-position-key (key)
2215   (effective-find-position-key key))
2216
2217 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
2218 (macrolet (;; shared logic for defining %FIND-POSITION and
2219            ;; %FIND-POSITION-IF in terms of various inlineable cases
2220            ;; of the expression defined in FROB and VECTOR*-FROB
2221            (frobs (&optional bit-frob)
2222              `(seq-dispatch sequence-arg
2223                (frob sequence-arg from-end)
2224                (with-array-data ((sequence sequence-arg :offset-var offset)
2225                                  (start start)
2226                                  (end end)
2227                                  :check-fill-pointer t)
2228                  (multiple-value-bind (f p)
2229                      (macrolet ((frob2 () `(if from-end
2230                                                (frob sequence t)
2231                                                (frob sequence nil))))
2232                        (typecase sequence
2233                          #!+sb-unicode
2234                          ((simple-array character (*)) (frob2))
2235                          ((simple-array base-char (*)) (frob2))
2236                          ,@(when bit-frob
2237                              `((simple-bit-vector
2238                                 (if (and (typep item 'bit)
2239                                          (eq #'identity key)
2240                                          (or (eq #'eq test)
2241                                              (eq #'eql test)
2242                                              (eq #'equal test)))
2243                                     (let ((p (%bit-position item sequence
2244                                                             from-end start end)))
2245                                       (if p
2246                                           (values item p)
2247                                           (values nil nil)))
2248                                     (vector*-frob sequence)))))
2249                          (t
2250                           (vector*-frob sequence))))
2251                    (declare (type (or index null) p))
2252                    (values f (and p (the index (- p offset)))))))))
2253   (defun %find-position (item sequence-arg from-end start end key test)
2254     (macrolet ((frob (sequence from-end)
2255                  `(%find-position item ,sequence
2256                                   ,from-end start end key test))
2257                (vector*-frob (sequence)
2258                  `(%find-position-vector-macro item ,sequence
2259                                                from-end start end key test)))
2260       (frobs t)))
2261   (defun %find-position-if (predicate sequence-arg from-end start end key)
2262     (macrolet ((frob (sequence from-end)
2263                  `(%find-position-if predicate ,sequence
2264                                      ,from-end start end key))
2265                (vector*-frob (sequence)
2266                  `(%find-position-if-vector-macro predicate ,sequence
2267                                                   from-end start end key)))
2268       (frobs)))
2269   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
2270     (macrolet ((frob (sequence from-end)
2271                  `(%find-position-if-not predicate ,sequence
2272                                          ,from-end start end key))
2273                (vector*-frob (sequence)
2274                  `(%find-position-if-not-vector-macro predicate ,sequence
2275                                                   from-end start end key)))
2276       (frobs))))
2277
2278 (defun find
2279     (item sequence &rest args &key from-end (start 0) end key test test-not)
2280   (declare (truly-dynamic-extent args))
2281   (seq-dispatch sequence
2282     (nth-value 0 (%find-position
2283                   item sequence from-end start end
2284                   (effective-find-position-key key)
2285                   (effective-find-position-test test test-not)))
2286     (nth-value 0 (%find-position
2287                   item sequence from-end start end
2288                   (effective-find-position-key key)
2289                   (effective-find-position-test test test-not)))
2290     (apply #'sb!sequence:find item sequence args)))
2291 (defun position
2292     (item sequence &rest args &key from-end (start 0) end key test test-not)
2293   (declare (truly-dynamic-extent args))
2294   (seq-dispatch sequence
2295     (nth-value 1 (%find-position
2296                   item sequence from-end start end
2297                   (effective-find-position-key key)
2298                   (effective-find-position-test test test-not)))
2299     (nth-value 1 (%find-position
2300                   item sequence from-end start end
2301                   (effective-find-position-key key)
2302                   (effective-find-position-test test test-not)))
2303     (apply #'sb!sequence:position item sequence args)))
2304
2305 (defun find-if (predicate sequence &rest args &key from-end (start 0) end key)
2306   (declare (truly-dynamic-extent args))
2307   (seq-dispatch sequence
2308     (nth-value 0 (%find-position-if
2309                   (%coerce-callable-to-fun predicate)
2310                   sequence from-end start end
2311                   (effective-find-position-key key)))
2312     (nth-value 0 (%find-position-if
2313                   (%coerce-callable-to-fun predicate)
2314                   sequence from-end start end
2315                   (effective-find-position-key key)))
2316     (apply #'sb!sequence:find-if predicate sequence args)))
2317 (defun position-if
2318     (predicate sequence &rest args &key from-end (start 0) end key)
2319   (declare (truly-dynamic-extent args))
2320   (seq-dispatch sequence
2321     (nth-value 1 (%find-position-if
2322                   (%coerce-callable-to-fun predicate)
2323                   sequence from-end start end
2324                   (effective-find-position-key key)))
2325     (nth-value 1 (%find-position-if
2326                   (%coerce-callable-to-fun predicate)
2327                   sequence from-end start end
2328                   (effective-find-position-key key)))
2329     (apply #'sb!sequence:position-if predicate sequence args)))
2330
2331 (defun find-if-not
2332     (predicate sequence &rest args &key from-end (start 0) end key)
2333   (declare (truly-dynamic-extent args))
2334   (seq-dispatch sequence
2335     (nth-value 0 (%find-position-if-not
2336                   (%coerce-callable-to-fun predicate)
2337                   sequence from-end start end
2338                   (effective-find-position-key key)))
2339     (nth-value 0 (%find-position-if-not
2340                   (%coerce-callable-to-fun predicate)
2341                   sequence from-end start end
2342                   (effective-find-position-key key)))
2343     (apply #'sb!sequence:find-if-not predicate sequence args)))
2344 (defun position-if-not
2345     (predicate sequence &rest args &key from-end (start 0) end key)
2346   (declare (truly-dynamic-extent args))
2347   (seq-dispatch sequence
2348     (nth-value 1 (%find-position-if-not
2349                   (%coerce-callable-to-fun predicate)
2350                   sequence from-end start end
2351                   (effective-find-position-key key)))
2352     (nth-value 1 (%find-position-if-not
2353                   (%coerce-callable-to-fun predicate)
2354                   sequence from-end start end
2355                   (effective-find-position-key key)))
2356     (apply #'sb!sequence:position-if-not predicate sequence args)))
2357 \f
2358 ;;;; COUNT-IF, COUNT-IF-NOT, and COUNT
2359
2360 (eval-when (:compile-toplevel :execute)
2361
2362 (sb!xc:defmacro vector-count-if (notp from-end-p predicate sequence)
2363   (let ((next-index (if from-end-p '(1- index) '(1+ index)))
2364         (pred `(funcall ,predicate (apply-key key (aref ,sequence index)))))
2365     `(let ((%start ,(if from-end-p '(1- end) 'start))
2366            (%end ,(if from-end-p '(1- start) 'end)))
2367       (do ((index %start ,next-index)
2368            (count 0))
2369           ((= index (the fixnum %end)) count)
2370         (declare (fixnum index count))
2371         (,(if notp 'unless 'when) ,pred
2372           (setq count (1+ count)))))))
2373
2374 (sb!xc:defmacro list-count-if (notp from-end-p predicate sequence)
2375   (let ((pred `(funcall ,predicate (apply-key key (pop sequence)))))
2376     `(let ((%start ,(if from-end-p '(- length end) 'start))
2377            (%end ,(if from-end-p '(- length start) 'end))
2378            (sequence ,(if from-end-p '(reverse sequence) 'sequence)))
2379       (do ((sequence (nthcdr %start ,sequence))
2380            (index %start (1+ index))
2381            (count 0))
2382           ((or (= index (the fixnum %end)) (null sequence)) count)
2383         (declare (fixnum index count))
2384         (,(if notp 'unless 'when) ,pred
2385           (setq count (1+ count)))))))
2386
2387
2388 ) ; EVAL-WHEN
2389
2390 (define-sequence-traverser count-if
2391     (pred sequence &rest args &key from-end start end key)
2392   #!+sb-doc
2393   "Return the number of elements in SEQUENCE satisfying PRED(el)."
2394   (declare (fixnum start))
2395   (declare (truly-dynamic-extent args))
2396   (let ((end (or end length))
2397         (pred (%coerce-callable-to-fun pred)))
2398     (declare (type index end))
2399     (seq-dispatch sequence
2400       (if from-end
2401           (list-count-if nil t pred sequence)
2402           (list-count-if nil nil pred sequence))
2403       (if from-end
2404           (vector-count-if nil t pred sequence)
2405           (vector-count-if nil nil pred sequence))
2406       (apply #'sb!sequence:count-if pred sequence args))))
2407
2408 (define-sequence-traverser count-if-not
2409     (pred sequence &rest args &key from-end start end key)
2410   #!+sb-doc
2411   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2412   (declare (fixnum start))
2413   (declare (truly-dynamic-extent args))
2414   (let ((end (or end length))
2415         (pred (%coerce-callable-to-fun pred)))
2416     (declare (type index end))
2417     (seq-dispatch sequence
2418       (if from-end
2419           (list-count-if t t pred sequence)
2420           (list-count-if t nil pred sequence))
2421       (if from-end
2422           (vector-count-if t t pred sequence)
2423           (vector-count-if t nil pred sequence))
2424       (apply #'sb!sequence:count-if-not pred sequence args))))
2425
2426 (define-sequence-traverser count
2427     (item sequence &rest args &key from-end start end
2428           key (test #'eql test-p) (test-not nil test-not-p))
2429   #!+sb-doc
2430   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2431    which defaults to EQL."
2432   (declare (fixnum start))
2433   (declare (truly-dynamic-extent args))
2434   (when (and test-p test-not-p)
2435     ;; ANSI Common Lisp has left the behavior in this situation unspecified.
2436     ;; (CLHS 17.2.1)
2437     (error ":TEST and :TEST-NOT are both present."))
2438   (let ((end (or end length)))
2439     (declare (type index end))
2440     (let ((%test (if test-not-p
2441                      (lambda (x)
2442                        (not (funcall test-not item x)))
2443                      (lambda (x)
2444                        (funcall test item x)))))
2445       (seq-dispatch sequence
2446         (if from-end
2447             (list-count-if nil t %test sequence)
2448             (list-count-if nil nil %test sequence))
2449         (if from-end
2450             (vector-count-if nil t %test sequence)
2451             (vector-count-if nil nil %test sequence))
2452         (apply #'sb!sequence:count item sequence args)))))
2453 \f
2454 ;;;; MISMATCH
2455
2456 (eval-when (:compile-toplevel :execute)
2457
2458 (sb!xc:defmacro match-vars (&rest body)
2459   `(let ((inc (if from-end -1 1))
2460          (start1 (if from-end (1- (the fixnum end1)) start1))
2461          (start2 (if from-end (1- (the fixnum end2)) start2))
2462          (end1 (if from-end (1- (the fixnum start1)) end1))
2463          (end2 (if from-end (1- (the fixnum start2)) end2)))
2464      (declare (fixnum inc start1 start2 end1 end2))
2465      ,@body))
2466
2467 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2468   (declare (ignore end)) ;; ### Should END be used below?
2469   `(let ((,sequence (if from-end
2470                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2471                                 (reverse (the list ,sequence)))
2472                         (nthcdr ,start ,sequence))))
2473      (declare (type list ,sequence))
2474      ,@body))
2475
2476 ) ; EVAL-WHEN
2477
2478 (eval-when (:compile-toplevel :execute)
2479
2480 (sb!xc:defmacro if-mismatch (elt1 elt2)
2481   `(cond ((= (the fixnum index1) (the fixnum end1))
2482           (return (if (= (the fixnum index2) (the fixnum end2))
2483                       nil
2484                       (if from-end
2485                           (1+ (the fixnum index1))
2486                           (the fixnum index1)))))
2487          ((= (the fixnum index2) (the fixnum end2))
2488           (return (if from-end (1+ (the fixnum index1)) index1)))
2489          (test-not
2490           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2491               (return (if from-end (1+ (the fixnum index1)) index1))))
2492          (t (if (not (funcall test (apply-key key ,elt1)
2493                               (apply-key key ,elt2)))
2494                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2495
2496 (sb!xc:defmacro mumble-mumble-mismatch ()
2497   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2498         (index2 start2 (+ index2 (the fixnum inc))))
2499        (())
2500      (declare (fixnum index1 index2))
2501      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2502
2503 (sb!xc:defmacro mumble-list-mismatch ()
2504   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2505         (index2 start2 (+ index2 (the fixnum inc))))
2506        (())
2507      (declare (fixnum index1 index2))
2508      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2509 \f
2510 (sb!xc:defmacro list-mumble-mismatch ()
2511   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2512         (index2 start2 (+ index2 (the fixnum inc))))
2513        (())
2514      (declare (fixnum index1 index2))
2515      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2516
2517 (sb!xc:defmacro list-list-mismatch ()
2518   `(do ((sequence1 sequence1)
2519         (sequence2 sequence2)
2520         (index1 start1 (+ index1 (the fixnum inc)))
2521         (index2 start2 (+ index2 (the fixnum inc))))
2522        (())
2523      (declare (fixnum index1 index2))
2524      (if-mismatch (pop sequence1) (pop sequence2))))
2525
2526 ) ; EVAL-WHEN
2527
2528 (define-sequence-traverser mismatch
2529     (sequence1 sequence2 &rest args &key from-end test test-not
2530      start1 end1 start2 end2 key)
2531   #!+sb-doc
2532   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2533    element-wise. If they are of equal length and match in every element, the
2534    result is NIL. Otherwise, the result is a non-negative integer, the index
2535    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2536    if one is shorter than and a matching prefix of the other, the index within
2537    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2538    :FROM-END argument is given, then one plus the index of the rightmost
2539    position in which the sequences differ is returned."
2540   (declare (fixnum start1 start2))
2541   (declare (truly-dynamic-extent args))
2542   (let* ((end1 (or end1 length1))
2543          (end2 (or end2 length2)))
2544     (declare (type index end1 end2))
2545     (match-vars
2546      (seq-dispatch sequence1
2547        (seq-dispatch sequence2
2548          (matchify-list (sequence1 start1 length1 end1)
2549            (matchify-list (sequence2 start2 length2 end2)
2550              (list-list-mismatch)))
2551          (matchify-list (sequence1 start1 length1 end1)
2552            (list-mumble-mismatch))
2553          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2554        (seq-dispatch sequence2
2555          (matchify-list (sequence2 start2 length2 end2)
2556            (mumble-list-mismatch))
2557          (mumble-mumble-mismatch)
2558          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2559        (apply #'sb!sequence:mismatch sequence1 sequence2 args)))))
2560 \f
2561 ;;; search comparison functions
2562
2563 (eval-when (:compile-toplevel :execute)
2564
2565 ;;; Compare two elements and return if they don't match.
2566 (sb!xc:defmacro compare-elements (elt1 elt2)
2567   `(if test-not
2568        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2569            (return nil)
2570            t)
2571        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2572            (return nil)
2573            t)))
2574
2575 (sb!xc:defmacro search-compare-list-list (main sub)
2576   `(do ((main ,main (cdr main))
2577         (jndex start1 (1+ jndex))
2578         (sub (nthcdr start1 ,sub) (cdr sub)))
2579        ((or (endp main) (endp sub) (<= end1 jndex))
2580         t)
2581      (declare (type (integer 0) jndex))
2582      (compare-elements (car sub) (car main))))
2583
2584 (sb!xc:defmacro search-compare-list-vector (main sub)
2585   `(do ((main ,main (cdr main))
2586         (index start1 (1+ index)))
2587        ((or (endp main) (= index end1)) t)
2588      (compare-elements (aref ,sub index) (car main))))
2589
2590 (sb!xc:defmacro search-compare-vector-list (main sub index)
2591   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2592         (jndex start1 (1+ jndex))
2593         (index ,index (1+ index)))
2594        ((or (<= end1 jndex) (endp sub)) t)
2595      (declare (type (integer 0) jndex))
2596      (compare-elements (car sub) (aref ,main index))))
2597
2598 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2599   `(do ((index ,index (1+ index))
2600         (sub-index start1 (1+ sub-index)))
2601        ((= sub-index end1) t)
2602      (compare-elements (aref ,sub sub-index) (aref ,main index))))
2603
2604 (sb!xc:defmacro search-compare (main-type main sub index)
2605   (if (eq main-type 'list)
2606       `(seq-dispatch ,sub
2607          (search-compare-list-list ,main ,sub)
2608          (search-compare-list-vector ,main ,sub)
2609          ;; KLUDGE: just hack it together so that it works
2610          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))
2611       `(seq-dispatch ,sub
2612          (search-compare-vector-list ,main ,sub ,index)
2613          (search-compare-vector-vector ,main ,sub ,index)
2614          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))))
2615
2616 ) ; EVAL-WHEN
2617 \f
2618 ;;;; SEARCH
2619
2620 (eval-when (:compile-toplevel :execute)
2621
2622 (sb!xc:defmacro list-search (main sub)
2623   `(do ((main (nthcdr start2 ,main) (cdr main))
2624         (index2 start2 (1+ index2))
2625         (terminus (- end2 (the (integer 0) (- end1 start1))))
2626         (last-match ()))
2627        ((> index2 terminus) last-match)
2628      (declare (type (integer 0) index2))
2629      (if (search-compare list main ,sub index2)
2630          (if from-end
2631              (setq last-match index2)
2632              (return index2)))))
2633
2634 (sb!xc:defmacro vector-search (main sub)
2635   `(do ((index2 start2 (1+ index2))
2636         (terminus (- end2 (the (integer 0) (- end1 start1))))
2637         (last-match ()))
2638        ((> index2 terminus) last-match)
2639      (declare (type (integer 0) index2))
2640      (if (search-compare vector ,main ,sub index2)
2641          (if from-end
2642              (setq last-match index2)
2643              (return index2)))))
2644
2645 ) ; EVAL-WHEN
2646
2647 (define-sequence-traverser search
2648     (sequence1 sequence2 &rest args &key
2649      from-end test test-not start1 end1 start2 end2 key)
2650   (declare (fixnum start1 start2))
2651   (declare (truly-dynamic-extent args))
2652   (let ((end1 (or end1 length1))
2653         (end2 (or end2 length2)))
2654     (seq-dispatch sequence2
2655       (list-search sequence2 sequence1)
2656       (vector-search sequence2 sequence1)
2657       (apply #'sb!sequence:search sequence1 sequence2 args))))
2658
2659 ;;; FIXME: this was originally in array.lisp; it might be better to
2660 ;;; put it back there, and make DOSEQUENCE and SEQ-DISPATCH be in
2661 ;;; a new early-seq.lisp file.
2662 (defun fill-data-vector (vector dimensions initial-contents)
2663   (let ((index 0))
2664     (labels ((frob (axis dims contents)
2665                (cond ((null dims)
2666                       (setf (aref vector index) contents)
2667                       (incf index))
2668                      (t
2669                       (unless (typep contents 'sequence)
2670                         (error "malformed :INITIAL-CONTENTS: ~S is not a ~
2671                                 sequence, but ~W more layer~:P needed."
2672                                contents
2673                                (- (length dimensions) axis)))
2674                       (unless (= (length contents) (car dims))
2675                         (error "malformed :INITIAL-CONTENTS: Dimension of ~
2676                                 axis ~W is ~W, but ~S is ~W long."
2677                                axis (car dims) contents (length contents)))
2678                       (sb!sequence:dosequence (content contents)
2679                         (frob (1+ axis) (cdr dims) content))))))
2680       (frob 0 dimensions initial-contents))))