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