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