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