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