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