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