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