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