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