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