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