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