1.0.37.37: fix CONCATENATE FIXME
[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                 (let* ((lengths (mapcar #'length sequences))
882                        (result (make-array (the integer (apply #'+ lengths))
883                                            :element-type ',element-type))
884                        (start 0))
885                   (declare (index start))
886                   (dolist (seq sequences)
887                     (string-dispatch
888                         ((simple-array character (*))
889                          (simple-array base-char (*))
890                          t)
891                         seq
892                       (replace result seq :start1 start))
893                     (incf start (the index (pop lengths))))
894                   result))))
895   (def %concatenate-to-string character)
896   (def %concatenate-to-base-string base-char))
897 \f
898 ;;;; MAP and MAP-INTO
899
900 ;;; helper functions to handle arity-1 subcases of MAP
901 (declaim (ftype (function (function sequence) list) %map-list-arity-1))
902 (declaim (ftype (function (function sequence) simple-vector)
903                 %map-simple-vector-arity-1))
904 (defun %map-to-list-arity-1 (fun sequence)
905   (let ((reversed-result nil)
906         (really-fun (%coerce-callable-to-fun fun)))
907     (sb!sequence:dosequence (element sequence)
908       (push (funcall really-fun element)
909             reversed-result))
910     (nreverse reversed-result)))
911 (defun %map-to-simple-vector-arity-1 (fun sequence)
912   (let ((result (make-array (length sequence)))
913         (index 0)
914         (really-fun (%coerce-callable-to-fun fun)))
915     (declare (type index index))
916     (sb!sequence:dosequence (element sequence)
917       (setf (aref result index)
918             (funcall really-fun element))
919       (incf index))
920     result))
921 (defun %map-for-effect-arity-1 (fun sequence)
922   (let ((really-fun (%coerce-callable-to-fun fun)))
923     (sb!sequence:dosequence (element sequence)
924       (funcall really-fun element)))
925   nil)
926
927 (declaim (maybe-inline %map-for-effect))
928 (defun %map-for-effect (fun sequences)
929   (declare (type function fun) (type list sequences))
930   (let ((%sequences sequences)
931         (%iters (mapcar (lambda (s)
932                           (seq-dispatch s
933                             s
934                             0
935                             (multiple-value-list
936                              (sb!sequence:make-sequence-iterator s))))
937                         sequences))
938         (%apply-args (make-list (length sequences))))
939     ;; this is almost efficient (except in the general case where we
940     ;; trampoline to MAKE-SEQUENCE-ITERATOR; if we had DX allocation
941     ;; of MAKE-LIST, the whole of %MAP would be cons-free.
942     (declare (type list %sequences %iters %apply-args))
943     (loop
944      (do ((in-sequences  %sequences  (cdr in-sequences))
945           (in-iters      %iters      (cdr in-iters))
946           (in-apply-args %apply-args (cdr in-apply-args)))
947          ((null in-sequences) (apply fun %apply-args))
948        (let ((i (car in-iters)))
949          (declare (type (or list index) i))
950          (cond
951            ((listp (car in-sequences))
952             (if (null i)
953                 (return-from %map-for-effect nil)
954                 (setf (car in-apply-args) (car i)
955                       (car in-iters) (cdr i))))
956            ((typep i 'index)
957             (let ((v (the vector (car in-sequences))))
958               (if (>= i (length v))
959                   (return-from %map-for-effect nil)
960                   (setf (car in-apply-args) (aref v i)
961                         (car in-iters) (1+ i)))))
962            (t
963             (destructuring-bind (state limit from-end step endp elt &rest ignore)
964                 i
965               (declare (type function step endp elt)
966                        (ignore ignore))
967               (let ((s (car in-sequences)))
968                 (if (funcall endp s state limit from-end)
969                     (return-from %map-for-effect nil)
970                     (progn
971                       (setf (car in-apply-args) (funcall elt s state))
972                       (setf (caar in-iters) (funcall step s state from-end)))))))))))))
973 (defun %map-to-list (fun sequences)
974   (declare (type function fun)
975            (type list sequences))
976   (let ((result nil))
977     (flet ((f (&rest args)
978              (declare (truly-dynamic-extent args))
979              (push (apply fun args) result)))
980       (declare (truly-dynamic-extent #'f))
981       (%map-for-effect #'f sequences))
982     (nreverse result)))
983 (defun %map-to-vector (output-type-spec fun sequences)
984   (declare (type function fun)
985            (type list sequences))
986   (let ((min-len 0))
987     (flet ((f (&rest args)
988              (declare (truly-dynamic-extent args))
989              (declare (ignore args))
990              (incf min-len)))
991       (declare (truly-dynamic-extent #'f))
992       (%map-for-effect #'f sequences))
993     (let ((result (make-sequence output-type-spec min-len))
994           (i 0))
995       (declare (type (simple-array * (*)) result))
996       (flet ((f (&rest args)
997                (declare (truly-dynamic-extent args))
998                (setf (aref result i) (apply fun args))
999                (incf i)))
1000         (declare (truly-dynamic-extent #'f))
1001         (%map-for-effect #'f sequences))
1002       result)))
1003 (defun %map-to-sequence (result-type fun sequences)
1004   (declare (type function fun)
1005            (type list sequences))
1006   (let ((min-len 0))
1007     (flet ((f (&rest args)
1008              (declare (truly-dynamic-extent args))
1009              (declare (ignore args))
1010              (incf min-len)))
1011       (declare (truly-dynamic-extent #'f))
1012       (%map-for-effect #'f sequences))
1013     (let ((result (make-sequence result-type min-len)))
1014       (multiple-value-bind (state limit from-end step endp elt setelt)
1015           (sb!sequence:make-sequence-iterator result)
1016         (declare (ignore limit endp elt))
1017         (flet ((f (&rest args)
1018                  (declare (truly-dynamic-extent args))
1019                  (funcall setelt (apply fun args) result state)
1020                  (setq state (funcall step result state from-end))))
1021           (declare (truly-dynamic-extent #'f))
1022           (%map-for-effect #'f sequences)))
1023       result)))
1024
1025 ;;; %MAP is just MAP without the final just-to-be-sure check that
1026 ;;; length of the output sequence matches any length specified
1027 ;;; in RESULT-TYPE.
1028 (defun %map (result-type function first-sequence &rest more-sequences)
1029   (let ((really-fun (%coerce-callable-to-fun function))
1030         (type (specifier-type result-type)))
1031     ;; Handle one-argument MAP NIL specially, using ETYPECASE to turn
1032     ;; it into something which can be DEFTRANSFORMed away. (It's
1033     ;; fairly important to handle this case efficiently, since
1034     ;; quantifiers like SOME are transformed into this case, and since
1035     ;; there's no consing overhead to dwarf our inefficiency.)
1036     (if (and (null more-sequences)
1037              (null result-type))
1038         (%map-for-effect-arity-1 really-fun first-sequence)
1039         ;; Otherwise, use the industrial-strength full-generality
1040         ;; approach, consing O(N-ARGS) temporary storage (which can have
1041         ;; DYNAMIC-EXTENT), then using O(N-ARGS * RESULT-LENGTH) time.
1042         (let ((sequences (cons first-sequence more-sequences)))
1043           (cond
1044             ((eq type *empty-type*) (%map-for-effect really-fun sequences))
1045             ((csubtypep type (specifier-type 'list))
1046              (%map-to-list really-fun sequences))
1047             ((csubtypep type (specifier-type 'vector))
1048              (%map-to-vector result-type really-fun sequences))
1049             ((and (csubtypep type (specifier-type 'sequence))
1050                   (find-class result-type nil))
1051              (%map-to-sequence result-type really-fun sequences))
1052             (t
1053              (bad-sequence-type-error result-type)))))))
1054
1055 (defun map (result-type function first-sequence &rest more-sequences)
1056   (apply #'%map
1057          result-type
1058          function
1059          first-sequence
1060          more-sequences))
1061
1062 ;;; KLUDGE: MAP has been rewritten substantially since the fork from
1063 ;;; CMU CL in order to give reasonable performance, but this
1064 ;;; implementation of MAP-INTO still has the same problems as the old
1065 ;;; MAP code. Ideally, MAP-INTO should be rewritten to be efficient in
1066 ;;; the same way that the corresponding cases of MAP have been
1067 ;;; rewritten. Instead of doing it now, though, it's easier to wait
1068 ;;; until we have DYNAMIC-EXTENT, at which time it should become
1069 ;;; extremely easy to define a reasonably efficient MAP-INTO in terms
1070 ;;; of (MAP NIL ..). -- WHN 20000920
1071 (defun map-into (result-sequence function &rest sequences)
1072   (let* ((fp-result
1073           (and (arrayp result-sequence)
1074                (array-has-fill-pointer-p result-sequence)))
1075          (len (apply #'min
1076                      (if fp-result
1077                          (array-dimension result-sequence 0)
1078                          (length result-sequence))
1079                      (mapcar #'length sequences))))
1080
1081     (when fp-result
1082       (setf (fill-pointer result-sequence) len))
1083
1084     (let ((really-fun (%coerce-callable-to-fun function)))
1085       (dotimes (index len)
1086         (setf (elt result-sequence index)
1087               (apply really-fun
1088                      (mapcar (lambda (seq) (elt seq index))
1089                              sequences))))))
1090   result-sequence)
1091 \f
1092 ;;;; quantifiers
1093
1094 ;;; We borrow the logic from (MAP NIL ..) to handle iteration over
1095 ;;; arbitrary sequence arguments, both in the full call case and in
1096 ;;; the open code case.
1097 (macrolet ((defquantifier (name found-test found-result
1098                                 &key doc (unfound-result (not found-result)))
1099              `(progn
1100                 ;; KLUDGE: It would be really nice if we could simply
1101                 ;; do something like this
1102                 ;;  (declaim (inline ,name))
1103                 ;;  (defun ,name (pred first-seq &rest more-seqs)
1104                 ;;    ,doc
1105                 ;;    (flet ((map-me (&rest rest)
1106                 ;;             (let ((pred-value (apply pred rest)))
1107                 ;;               (,found-test pred-value
1108                 ;;                 (return-from ,name
1109                 ;;                   ,found-result)))))
1110                 ;;      (declare (inline map-me))
1111                 ;;      (apply #'map nil #'map-me first-seq more-seqs)
1112                 ;;      ,unfound-result))
1113                 ;; but Python doesn't seem to be smart enough about
1114                 ;; inlining and APPLY to recognize that it can use
1115                 ;; the DEFTRANSFORM for MAP in the resulting inline
1116                 ;; expansion. I don't have any appetite for deep
1117                 ;; compiler hacking right now, so I'll just work
1118                 ;; around the apparent problem by using a compiler
1119                 ;; macro instead. -- WHN 20000410
1120                 (defun ,name (pred first-seq &rest more-seqs)
1121                   #!+sb-doc ,doc
1122                   (flet ((map-me (&rest rest)
1123                            (let ((pred-value (apply pred rest)))
1124                              (,found-test pred-value
1125                                           (return-from ,name
1126                                             ,found-result)))))
1127                     (declare (inline map-me))
1128                     (apply #'map nil #'map-me first-seq more-seqs)
1129                     ,unfound-result))
1130                 ;; KLUDGE: It would be more obviously correct -- but
1131                 ;; also significantly messier -- for PRED-VALUE to be
1132                 ;; a gensym. However, a private symbol really does
1133                 ;; seem to be good enough; and anyway the really
1134                 ;; obviously correct solution is to make Python smart
1135                 ;; enough that we can use an inline function instead
1136                 ;; of a compiler macro (as above). -- WHN 20000410
1137                 ;;
1138                 ;; FIXME: The DEFINE-COMPILER-MACRO here can be
1139                 ;; important for performance, and it'd be good to have
1140                 ;; it be visible throughout the compilation of all the
1141                 ;; target SBCL code. That could be done by defining
1142                 ;; SB-XC:DEFINE-COMPILER-MACRO and using it here,
1143                 ;; moving this DEFQUANTIFIER stuff (and perhaps other
1144                 ;; inline definitions in seq.lisp as well) into a new
1145                 ;; seq.lisp, and moving remaining target-only stuff
1146                 ;; from the old seq.lisp into target-seq.lisp.
1147                 (define-compiler-macro ,name (pred first-seq &rest more-seqs)
1148                   (let ((elements (make-gensym-list (1+ (length more-seqs))))
1149                         (blockname (gensym "BLOCK")))
1150                     (once-only ((pred pred))
1151                       `(block ,blockname
1152                          (map nil
1153                               (lambda (,@elements)
1154                                 (let ((pred-value (funcall ,pred ,@elements)))
1155                                   (,',found-test pred-value
1156                                     (return-from ,blockname
1157                                       ,',found-result))))
1158                               ,first-seq
1159                               ,@more-seqs)
1160                          ,',unfound-result)))))))
1161   (defquantifier some when pred-value :unfound-result nil :doc
1162   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1163    possibly to those with index 1, and so on. Return the first
1164    non-NIL value encountered, or NIL if the end of any sequence is reached.")
1165   (defquantifier every unless nil :doc
1166   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1167    possibly to those with index 1, and so on. Return NIL as soon
1168    as any invocation of PREDICATE returns NIL, or T if every invocation
1169    is non-NIL.")
1170   (defquantifier notany when nil :doc
1171   "Apply PREDICATE to the 0-indexed elements of the sequences, then
1172    possibly to those with index 1, and so on. Return NIL as soon
1173    as any invocation of PREDICATE returns a non-NIL value, or T if the end
1174    of any sequence is reached.")
1175   (defquantifier notevery unless t :doc
1176   "Apply PREDICATE to 0-indexed elements of the sequences, then
1177    possibly to those with index 1, and so on. Return T as soon
1178    as any invocation of PREDICATE returns NIL, or NIL if every invocation
1179    is non-NIL."))
1180 \f
1181 ;;;; REDUCE
1182
1183 (eval-when (:compile-toplevel :execute)
1184
1185 (sb!xc:defmacro mumble-reduce (function
1186                                sequence
1187                                key
1188                                start
1189                                end
1190                                initial-value
1191                                ref)
1192   `(do ((index ,start (1+ index))
1193         (value ,initial-value))
1194        ((>= index ,end) value)
1195      (setq value (funcall ,function value
1196                           (apply-key ,key (,ref ,sequence index))))))
1197
1198 (sb!xc:defmacro mumble-reduce-from-end (function
1199                                         sequence
1200                                         key
1201                                         start
1202                                         end
1203                                         initial-value
1204                                         ref)
1205   `(do ((index (1- ,end) (1- index))
1206         (value ,initial-value)
1207         (terminus (1- ,start)))
1208        ((<= index terminus) value)
1209      (setq value (funcall ,function
1210                           (apply-key ,key (,ref ,sequence index))
1211                           value))))
1212
1213 (sb!xc:defmacro list-reduce (function
1214                              sequence
1215                              key
1216                              start
1217                              end
1218                              initial-value
1219                              ivp)
1220   `(let ((sequence (nthcdr ,start ,sequence)))
1221      (do ((count (if ,ivp ,start (1+ ,start))
1222                  (1+ count))
1223           (sequence (if ,ivp sequence (cdr sequence))
1224                     (cdr sequence))
1225           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1226                  (funcall ,function value (apply-key ,key (car sequence)))))
1227          ((>= count ,end) value))))
1228
1229 (sb!xc:defmacro list-reduce-from-end (function
1230                                       sequence
1231                                       key
1232                                       start
1233                                       end
1234                                       initial-value
1235                                       ivp)
1236   `(let ((sequence (nthcdr (- (length ,sequence) ,end)
1237                            (reverse ,sequence))))
1238      (do ((count (if ,ivp ,start (1+ ,start))
1239                  (1+ count))
1240           (sequence (if ,ivp sequence (cdr sequence))
1241                     (cdr sequence))
1242           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1243                  (funcall ,function (apply-key ,key (car sequence)) value)))
1244          ((>= count ,end) value))))
1245
1246 ) ; EVAL-WHEN
1247
1248 (define-sequence-traverser reduce (function sequence &rest args &key key
1249                                    from-end start end (initial-value nil ivp))
1250   (declare (type index start))
1251   (declare (truly-dynamic-extent args))
1252   (let ((start start)
1253         (end (or end length)))
1254     (declare (type index start end))
1255     (seq-dispatch sequence
1256       (if (= end start)
1257           (if ivp initial-value (funcall function))
1258           (if from-end
1259               (list-reduce-from-end function sequence key start end
1260                                     initial-value ivp)
1261               (list-reduce function sequence key start end
1262                            initial-value ivp)))
1263       (if (= end start)
1264           (if ivp initial-value (funcall function))
1265           (if from-end
1266               (progn
1267                 (when (not ivp)
1268                   (setq end (1- (the fixnum end)))
1269                   (setq initial-value (apply-key key (aref sequence end))))
1270                 (mumble-reduce-from-end function sequence key start end
1271                                         initial-value aref))
1272               (progn
1273                 (when (not ivp)
1274                   (setq initial-value (apply-key key (aref sequence start)))
1275                   (setq start (1+ start)))
1276                 (mumble-reduce function sequence key start end
1277                                initial-value aref))))
1278       (apply #'sb!sequence:reduce function sequence args))))
1279 \f
1280 ;;;; DELETE
1281
1282 (eval-when (:compile-toplevel :execute)
1283
1284 (sb!xc:defmacro mumble-delete (pred)
1285   `(do ((index start (1+ index))
1286         (jndex start)
1287         (number-zapped 0))
1288        ((or (= index (the fixnum end)) (= number-zapped count))
1289         (do ((index index (1+ index))           ; Copy the rest of the vector.
1290              (jndex jndex (1+ jndex)))
1291             ((= index (the fixnum length))
1292              (shrink-vector sequence jndex))
1293           (declare (fixnum index jndex))
1294           (setf (aref sequence jndex) (aref sequence index))))
1295      (declare (fixnum index jndex number-zapped))
1296      (setf (aref sequence jndex) (aref sequence index))
1297      (if ,pred
1298          (incf number-zapped)
1299          (incf jndex))))
1300
1301 (sb!xc:defmacro mumble-delete-from-end (pred)
1302   `(do ((index (1- (the fixnum end)) (1- index)) ; Find the losers.
1303         (number-zapped 0)
1304         (losers ())
1305         this-element
1306         (terminus (1- start)))
1307        ((or (= index terminus) (= number-zapped count))
1308         (do ((losers losers)                     ; Delete the losers.
1309              (index start (1+ index))
1310              (jndex start))
1311             ((or (null losers) (= index (the fixnum end)))
1312              (do ((index index (1+ index))       ; Copy the rest of the vector.
1313                   (jndex jndex (1+ jndex)))
1314                  ((= index (the fixnum length))
1315                   (shrink-vector sequence jndex))
1316                (declare (fixnum index jndex))
1317                (setf (aref sequence jndex) (aref sequence index))))
1318           (declare (fixnum index jndex))
1319           (setf (aref sequence jndex) (aref sequence index))
1320           (if (= index (the fixnum (car losers)))
1321               (pop losers)
1322               (incf jndex))))
1323      (declare (fixnum index number-zapped terminus))
1324      (setq this-element (aref sequence index))
1325      (when ,pred
1326        (incf number-zapped)
1327        (push index losers))))
1328
1329 (sb!xc:defmacro normal-mumble-delete ()
1330   `(mumble-delete
1331     (if test-not
1332         (not (funcall test-not item (apply-key key (aref sequence index))))
1333         (funcall test item (apply-key key (aref sequence index))))))
1334
1335 (sb!xc:defmacro normal-mumble-delete-from-end ()
1336   `(mumble-delete-from-end
1337     (if test-not
1338         (not (funcall test-not item (apply-key key this-element)))
1339         (funcall test item (apply-key key this-element)))))
1340
1341 (sb!xc:defmacro list-delete (pred)
1342   `(let ((handle (cons nil sequence)))
1343      (do ((current (nthcdr start sequence) (cdr current))
1344           (previous (nthcdr start handle))
1345           (index start (1+ index))
1346           (number-zapped 0))
1347          ((or (= index (the fixnum end)) (= number-zapped count))
1348           (cdr handle))
1349        (declare (fixnum index number-zapped))
1350        (cond (,pred
1351               (rplacd previous (cdr current))
1352               (incf number-zapped))
1353              (t
1354               (setq previous (cdr previous)))))))
1355
1356 (sb!xc:defmacro list-delete-from-end (pred)
1357   `(let* ((reverse (nreverse (the list sequence)))
1358           (handle (cons nil reverse)))
1359      (do ((current (nthcdr (- (the fixnum length) (the fixnum end)) reverse)
1360                    (cdr current))
1361           (previous (nthcdr (- (the fixnum length) (the fixnum end)) handle))
1362           (index start (1+ index))
1363           (number-zapped 0))
1364          ((or (= index (the fixnum end)) (= number-zapped count))
1365           (nreverse (cdr handle)))
1366        (declare (fixnum index number-zapped))
1367        (cond (,pred
1368               (rplacd previous (cdr current))
1369               (incf number-zapped))
1370              (t
1371               (setq previous (cdr previous)))))))
1372
1373 (sb!xc:defmacro normal-list-delete ()
1374   '(list-delete
1375     (if test-not
1376         (not (funcall test-not item (apply-key key (car current))))
1377         (funcall test item (apply-key key (car current))))))
1378
1379 (sb!xc:defmacro normal-list-delete-from-end ()
1380   '(list-delete-from-end
1381     (if test-not
1382         (not (funcall test-not item (apply-key key (car current))))
1383         (funcall test item (apply-key key (car current))))))
1384
1385 ) ; EVAL-WHEN
1386
1387 (define-sequence-traverser delete
1388     (item sequence &rest args &key from-end test test-not start
1389      end count key)
1390   #!+sb-doc
1391   "Return a sequence formed by destructively removing the specified ITEM from
1392   the given SEQUENCE."
1393   (declare (fixnum start))
1394   (declare (truly-dynamic-extent args))
1395   (let ((end (or end length)))
1396     (declare (type index end))
1397     (seq-dispatch sequence
1398       (if from-end
1399           (normal-list-delete-from-end)
1400           (normal-list-delete))
1401       (if from-end
1402           (normal-mumble-delete-from-end)
1403           (normal-mumble-delete))
1404       (apply #'sb!sequence:delete item sequence args))))
1405
1406 (eval-when (:compile-toplevel :execute)
1407
1408 (sb!xc:defmacro if-mumble-delete ()
1409   `(mumble-delete
1410     (funcall predicate (apply-key key (aref sequence index)))))
1411
1412 (sb!xc:defmacro if-mumble-delete-from-end ()
1413   `(mumble-delete-from-end
1414     (funcall predicate (apply-key key this-element))))
1415
1416 (sb!xc:defmacro if-list-delete ()
1417   '(list-delete
1418     (funcall predicate (apply-key key (car current)))))
1419
1420 (sb!xc:defmacro if-list-delete-from-end ()
1421   '(list-delete-from-end
1422     (funcall predicate (apply-key key (car current)))))
1423
1424 ) ; EVAL-WHEN
1425
1426 (define-sequence-traverser delete-if
1427     (predicate sequence &rest args &key from-end start key end count)
1428   #!+sb-doc
1429   "Return a sequence formed by destructively removing the elements satisfying
1430   the specified PREDICATE from the given SEQUENCE."
1431   (declare (fixnum start))
1432   (declare (truly-dynamic-extent args))
1433   (let ((end (or end length)))
1434     (declare (type index end))
1435     (seq-dispatch sequence
1436       (if from-end
1437           (if-list-delete-from-end)
1438           (if-list-delete))
1439       (if from-end
1440           (if-mumble-delete-from-end)
1441           (if-mumble-delete))
1442       (apply #'sb!sequence:delete-if predicate sequence args))))
1443
1444 (eval-when (:compile-toplevel :execute)
1445
1446 (sb!xc:defmacro if-not-mumble-delete ()
1447   `(mumble-delete
1448     (not (funcall predicate (apply-key key (aref sequence index))))))
1449
1450 (sb!xc:defmacro if-not-mumble-delete-from-end ()
1451   `(mumble-delete-from-end
1452     (not (funcall predicate (apply-key key this-element)))))
1453
1454 (sb!xc:defmacro if-not-list-delete ()
1455   '(list-delete
1456     (not (funcall predicate (apply-key key (car current))))))
1457
1458 (sb!xc:defmacro if-not-list-delete-from-end ()
1459   '(list-delete-from-end
1460     (not (funcall predicate (apply-key key (car current))))))
1461
1462 ) ; EVAL-WHEN
1463
1464 (define-sequence-traverser delete-if-not
1465     (predicate sequence &rest args &key from-end start end key count)
1466   #!+sb-doc
1467   "Return a sequence formed by destructively removing the elements not
1468   satisfying the specified PREDICATE from the given SEQUENCE."
1469   (declare (fixnum start))
1470   (declare (truly-dynamic-extent args))
1471   (let ((end (or end length)))
1472     (declare (type index end))
1473     (seq-dispatch sequence
1474       (if from-end
1475           (if-not-list-delete-from-end)
1476           (if-not-list-delete))
1477       (if from-end
1478           (if-not-mumble-delete-from-end)
1479           (if-not-mumble-delete))
1480       (apply #'sb!sequence:delete-if-not predicate sequence args))))
1481 \f
1482 ;;;; REMOVE
1483
1484 (eval-when (:compile-toplevel :execute)
1485
1486 ;;; MUMBLE-REMOVE-MACRO does not include (removes) each element that
1487 ;;; satisfies the predicate.
1488 (sb!xc:defmacro mumble-remove-macro (bump left begin finish right pred)
1489   `(do ((index ,begin (,bump index))
1490         (result
1491          (do ((index ,left (,bump index))
1492               (result (%make-sequence-like sequence length)))
1493              ((= index (the fixnum ,begin)) result)
1494            (declare (fixnum index))
1495            (setf (aref result index) (aref sequence index))))
1496         (new-index ,begin)
1497         (number-zapped 0)
1498         (this-element))
1499        ((or (= index (the fixnum ,finish))
1500             (= number-zapped count))
1501         (do ((index index (,bump index))
1502              (new-index new-index (,bump new-index)))
1503             ((= index (the fixnum ,right)) (%shrink-vector result new-index))
1504           (declare (fixnum index new-index))
1505           (setf (aref result new-index) (aref sequence index))))
1506      (declare (fixnum index new-index number-zapped))
1507      (setq this-element (aref sequence index))
1508      (cond (,pred (incf number-zapped))
1509            (t (setf (aref result new-index) this-element)
1510               (setq new-index (,bump new-index))))))
1511
1512 (sb!xc:defmacro mumble-remove (pred)
1513   `(mumble-remove-macro 1+ 0 start end length ,pred))
1514
1515 (sb!xc:defmacro mumble-remove-from-end (pred)
1516   `(let ((sequence (copy-seq sequence)))
1517      (mumble-delete-from-end ,pred)))
1518
1519 (sb!xc:defmacro normal-mumble-remove ()
1520   `(mumble-remove
1521     (if test-not
1522         (not (funcall test-not item (apply-key key this-element)))
1523         (funcall test item (apply-key key this-element)))))
1524
1525 (sb!xc:defmacro normal-mumble-remove-from-end ()
1526   `(mumble-remove-from-end
1527     (if test-not
1528         (not (funcall test-not item (apply-key key this-element)))
1529         (funcall test item (apply-key key this-element)))))
1530
1531 (sb!xc:defmacro if-mumble-remove ()
1532   `(mumble-remove (funcall predicate (apply-key key this-element))))
1533
1534 (sb!xc:defmacro if-mumble-remove-from-end ()
1535   `(mumble-remove-from-end (funcall predicate (apply-key key this-element))))
1536
1537 (sb!xc:defmacro if-not-mumble-remove ()
1538   `(mumble-remove (not (funcall predicate (apply-key key this-element)))))
1539
1540 (sb!xc:defmacro if-not-mumble-remove-from-end ()
1541   `(mumble-remove-from-end
1542     (not (funcall predicate (apply-key key this-element)))))
1543
1544 ;;; LIST-REMOVE-MACRO does not include (removes) each element that satisfies
1545 ;;; the predicate.
1546 (sb!xc:defmacro list-remove-macro (pred reverse?)
1547   `(let* ((sequence ,(if reverse?
1548                          '(reverse (the list sequence))
1549                          'sequence))
1550           (%start ,(if reverse? '(- length end) 'start))
1551           (%end ,(if reverse? '(- length start) 'end))
1552           (splice (list nil))
1553           (results (do ((index 0 (1+ index))
1554                         (before-start splice))
1555                        ((= index (the fixnum %start)) before-start)
1556                      (declare (fixnum index))
1557                      (setq splice
1558                            (cdr (rplacd splice (list (pop sequence))))))))
1559      (do ((index %start (1+ index))
1560           (this-element)
1561           (number-zapped 0))
1562          ((or (= index (the fixnum %end)) (= number-zapped count))
1563           (do ((index index (1+ index)))
1564               ((null sequence)
1565                ,(if reverse?
1566                     '(nreverse (the list (cdr results)))
1567                     '(cdr results)))
1568             (declare (fixnum index))
1569             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1570        (declare (fixnum index number-zapped))
1571        (setq this-element (pop sequence))
1572        (if ,pred
1573            (setq number-zapped (1+ number-zapped))
1574            (setq splice (cdr (rplacd splice (list this-element))))))))
1575
1576 (sb!xc:defmacro list-remove (pred)
1577   `(list-remove-macro ,pred nil))
1578
1579 (sb!xc:defmacro list-remove-from-end (pred)
1580   `(list-remove-macro ,pred t))
1581
1582 (sb!xc:defmacro normal-list-remove ()
1583   `(list-remove
1584     (if test-not
1585         (not (funcall test-not item (apply-key key this-element)))
1586         (funcall test item (apply-key key this-element)))))
1587
1588 (sb!xc:defmacro normal-list-remove-from-end ()
1589   `(list-remove-from-end
1590     (if test-not
1591         (not (funcall test-not item (apply-key key this-element)))
1592         (funcall test item (apply-key key this-element)))))
1593
1594 (sb!xc:defmacro if-list-remove ()
1595   `(list-remove
1596     (funcall predicate (apply-key key this-element))))
1597
1598 (sb!xc:defmacro if-list-remove-from-end ()
1599   `(list-remove-from-end
1600     (funcall predicate (apply-key key this-element))))
1601
1602 (sb!xc:defmacro if-not-list-remove ()
1603   `(list-remove
1604     (not (funcall predicate (apply-key key this-element)))))
1605
1606 (sb!xc:defmacro if-not-list-remove-from-end ()
1607   `(list-remove-from-end
1608     (not (funcall predicate (apply-key key this-element)))))
1609
1610 ) ; EVAL-WHEN
1611
1612 (define-sequence-traverser remove
1613     (item sequence &rest args &key from-end test test-not start
1614      end count key)
1615   #!+sb-doc
1616   "Return a copy of SEQUENCE with elements satisfying the test (default is
1617    EQL) with ITEM removed."
1618   (declare (fixnum start))
1619   (declare (truly-dynamic-extent args))
1620   (let ((end (or end length)))
1621     (declare (type index end))
1622     (seq-dispatch sequence
1623       (if from-end
1624           (normal-list-remove-from-end)
1625           (normal-list-remove))
1626       (if from-end
1627           (normal-mumble-remove-from-end)
1628           (normal-mumble-remove))
1629       (apply #'sb!sequence:remove item sequence args))))
1630
1631 (define-sequence-traverser remove-if
1632     (predicate sequence &rest args &key from-end start end count key)
1633   #!+sb-doc
1634   "Return a copy of sequence with elements satisfying PREDICATE removed."
1635   (declare (fixnum start))
1636   (declare (truly-dynamic-extent args))
1637   (let ((end (or end length)))
1638     (declare (type index end))
1639     (seq-dispatch sequence
1640       (if from-end
1641           (if-list-remove-from-end)
1642           (if-list-remove))
1643       (if from-end
1644           (if-mumble-remove-from-end)
1645           (if-mumble-remove))
1646       (apply #'sb!sequence:remove-if predicate sequence args))))
1647
1648 (define-sequence-traverser remove-if-not
1649     (predicate sequence &rest args &key from-end start end count key)
1650   #!+sb-doc
1651   "Return a copy of sequence with elements not satisfying PREDICATE removed."
1652   (declare (fixnum start))
1653   (declare (truly-dynamic-extent args))
1654   (let ((end (or end length)))
1655     (declare (type index end))
1656     (seq-dispatch sequence
1657       (if from-end
1658           (if-not-list-remove-from-end)
1659           (if-not-list-remove))
1660       (if from-end
1661           (if-not-mumble-remove-from-end)
1662           (if-not-mumble-remove))
1663       (apply #'sb!sequence:remove-if-not predicate sequence args))))
1664 \f
1665 ;;;; REMOVE-DUPLICATES
1666
1667 ;;; Remove duplicates from a list. If from-end, remove the later duplicates,
1668 ;;; not the earlier ones. Thus if we check from-end we don't copy an item
1669 ;;; if we look into the already copied structure (from after :start) and see
1670 ;;; the item. If we check from beginning we check into the rest of the
1671 ;;; original list up to the :end marker (this we have to do by running a
1672 ;;; do loop down the list that far and using our test.
1673 (defun list-remove-duplicates* (list test test-not start end key from-end)
1674   (declare (fixnum start))
1675   (let* ((result (list ())) ; Put a marker on the beginning to splice with.
1676          (splice result)
1677          (current list)
1678          (end (or end (length list)))
1679          (hash (and (> (- end start) 20)
1680                     test
1681                     (not key)
1682                     (not test-not)
1683                     (or (eql test #'eql)
1684                         (eql test #'eq)
1685                         (eql test #'equal)
1686                         (eql test #'equalp))
1687                     (make-hash-table :test test :size (- end start)))))
1688     (do ((index 0 (1+ index)))
1689         ((= index start))
1690       (declare (fixnum index))
1691       (setq splice (cdr (rplacd splice (list (car current)))))
1692       (setq current (cdr current)))
1693     (if hash
1694         (do ((index start (1+ index)))
1695             ((or (and end (= index (the fixnum end)))
1696                  (atom current)))
1697           (declare (fixnum index))
1698           ;; The hash table contains links from values that are
1699           ;; already in result to the cons cell *preceding* theirs
1700           ;; in the list.  That is, for each value v in the list,
1701           ;; v and (cadr (gethash v hash)) are equal under TEST.
1702           (let ((prev (gethash (car current) hash)))
1703             (cond
1704              ((not prev)
1705               (setf (gethash (car current) hash) splice)
1706               (setq splice (cdr (rplacd splice (list (car current))))))
1707              ((not from-end)
1708               (let* ((old (cdr prev))
1709                      (next (cdr old)))
1710                 (if next
1711                   (let ((next-val (car next)))
1712                     ;; (assert (eq (gethash next-val hash) old))
1713                     (setf (cdr prev) next
1714                           (gethash next-val hash) prev
1715                           (gethash (car current) hash) splice
1716                           splice (cdr (rplacd splice (list (car current))))))
1717                   (setf (car old) (car current)))))))
1718           (setq current (cdr current)))
1719       (do ((index start (1+ index)))
1720           ((or (and end (= index (the fixnum end)))
1721                (atom current)))
1722         (declare (fixnum index))
1723         (if (or (and from-end
1724                      (not (if test-not
1725                               (member (apply-key key (car current))
1726                                       (nthcdr (1+ start) result)
1727                                       :test-not test-not
1728                                       :key key)
1729                             (member (apply-key key (car current))
1730                                     (nthcdr (1+ start) result)
1731                                     :test test
1732                                     :key key))))
1733                 (and (not from-end)
1734                      (not (do ((it (apply-key key (car current)))
1735                                (l (cdr current) (cdr l))
1736                                (i (1+ index) (1+ i)))
1737                               ((or (atom l) (and end (= i (the fixnum end))))
1738                                ())
1739                             (declare (fixnum i))
1740                             (if (if test-not
1741                                     (not (funcall test-not
1742                                                   it
1743                                                   (apply-key key (car l))))
1744                                   (funcall test it (apply-key key (car l))))
1745                                 (return t))))))
1746             (setq splice (cdr (rplacd splice (list (car current))))))
1747         (setq current (cdr current))))
1748     (do ()
1749         ((atom current))
1750       (setq splice (cdr (rplacd splice (list (car current)))))
1751       (setq current (cdr current)))
1752     (cdr result)))
1753
1754 (defun vector-remove-duplicates* (vector test test-not start end key from-end
1755                                          &optional (length (length vector)))
1756   (declare (vector vector) (fixnum start length))
1757   (when (null end) (setf end (length vector)))
1758   (let ((result (%make-sequence-like vector length))
1759         (index 0)
1760         (jndex start))
1761     (declare (fixnum index jndex))
1762     (do ()
1763         ((= index start))
1764       (setf (aref result index) (aref vector index))
1765       (setq index (1+ index)))
1766     (do ((elt))
1767         ((= index end))
1768       (setq elt (aref vector index))
1769       (unless (or (and from-end
1770                        (if test-not
1771                            (position (apply-key key elt) result
1772                                      :start start :end jndex
1773                                      :test-not test-not :key key)
1774                            (position (apply-key key elt) result
1775                                      :start start :end jndex
1776                                      :test test :key key)))
1777                   (and (not from-end)
1778                        (if test-not
1779                            (position (apply-key key elt) vector
1780                                      :start (1+ index) :end end
1781                                      :test-not test-not :key key)
1782                            (position (apply-key key elt) vector
1783                                      :start (1+ index) :end end
1784                                      :test test :key key))))
1785         (setf (aref result jndex) elt)
1786         (setq jndex (1+ jndex)))
1787       (setq index (1+ index)))
1788     (do ()
1789         ((= index length))
1790       (setf (aref result jndex) (aref vector index))
1791       (setq index (1+ index))
1792       (setq jndex (1+ jndex)))
1793     (%shrink-vector result jndex)))
1794
1795 (define-sequence-traverser remove-duplicates
1796     (sequence &rest args &key test test-not start end from-end key)
1797   #!+sb-doc
1798   "The elements of SEQUENCE are compared pairwise, and if any two match,
1799    the one occurring earlier is discarded, unless FROM-END is true, in
1800    which case the one later in the sequence is discarded. The resulting
1801    sequence is returned.
1802
1803    The :TEST-NOT argument is deprecated."
1804   (declare (fixnum start))
1805   (declare (truly-dynamic-extent args))
1806   (seq-dispatch sequence
1807     (if sequence
1808         (list-remove-duplicates* sequence test test-not
1809                                  start end key from-end))
1810     (vector-remove-duplicates* sequence test test-not start end key from-end)
1811     (apply #'sb!sequence:remove-duplicates sequence args)))
1812 \f
1813 ;;;; DELETE-DUPLICATES
1814
1815 (defun list-delete-duplicates* (list test test-not key from-end start end)
1816   (declare (fixnum start))
1817   (let ((handle (cons nil list)))
1818     (do ((current (nthcdr start list) (cdr current))
1819          (previous (nthcdr start handle))
1820          (index start (1+ index)))
1821         ((or (and end (= index (the fixnum end))) (null current))
1822          (cdr handle))
1823       (declare (fixnum index))
1824       (if (do ((x (if from-end
1825                       (nthcdr (1+ start) handle)
1826                       (cdr current))
1827                   (cdr x))
1828                (i (1+ index) (1+ i)))
1829               ((or (null x)
1830                    (and (not from-end) end (= i (the fixnum end)))
1831                    (eq x current))
1832                nil)
1833             (declare (fixnum i))
1834             (if (if test-not
1835                     (not (funcall test-not
1836                                   (apply-key key (car current))
1837                                   (apply-key key (car x))))
1838                     (funcall test
1839                              (apply-key key (car current))
1840                              (apply-key key (car x))))
1841                 (return t)))
1842           (rplacd previous (cdr current))
1843           (setq previous (cdr previous))))))
1844
1845 (defun vector-delete-duplicates* (vector test test-not key from-end start end
1846                                          &optional (length (length vector)))
1847   (declare (vector vector) (fixnum start length))
1848   (when (null end) (setf end (length vector)))
1849   (do ((index start (1+ index))
1850        (jndex start))
1851       ((= index end)
1852        (do ((index index (1+ index))            ; copy the rest of the vector
1853             (jndex jndex (1+ jndex)))
1854            ((= index length)
1855             (shrink-vector vector jndex))
1856          (setf (aref vector jndex) (aref vector index))))
1857     (declare (fixnum index jndex))
1858     (setf (aref vector jndex) (aref vector index))
1859     (unless (if test-not
1860                 (position (apply-key key (aref vector index)) vector :key key
1861                           :start (if from-end start (1+ index))
1862                           :end (if from-end jndex end)
1863                           :test-not test-not)
1864                 (position (apply-key key (aref vector index)) vector :key key
1865                           :start (if from-end start (1+ index))
1866                           :end (if from-end jndex end)
1867                           :test test))
1868       (setq jndex (1+ jndex)))))
1869
1870 (define-sequence-traverser delete-duplicates
1871     (sequence &rest args &key test test-not start end from-end key)
1872   #!+sb-doc
1873   "The elements of SEQUENCE are examined, and if any two match, one is
1874    discarded. The resulting sequence, which may be formed by destroying the
1875    given sequence, is returned.
1876
1877    The :TEST-NOT argument is deprecated."
1878   (declare (truly-dynamic-extent args))
1879   (seq-dispatch sequence
1880     (if sequence
1881         (list-delete-duplicates* sequence test test-not
1882                                  key from-end start end))
1883     (vector-delete-duplicates* sequence test test-not key from-end start end)
1884     (apply #'sb!sequence:delete-duplicates sequence args)))
1885 \f
1886 ;;;; SUBSTITUTE
1887
1888 (defun list-substitute* (pred new list start end count key test test-not old)
1889   (declare (fixnum start end count))
1890   (let* ((result (list nil))
1891          elt
1892          (splice result)
1893          (list list))      ; Get a local list for a stepper.
1894     (do ((index 0 (1+ index)))
1895         ((= index start))
1896       (declare (fixnum index))
1897       (setq splice (cdr (rplacd splice (list (car list)))))
1898       (setq list (cdr list)))
1899     (do ((index start (1+ index)))
1900         ((or (= index end) (null list) (= count 0)))
1901       (declare (fixnum index))
1902       (setq elt (car list))
1903       (setq splice
1904             (cdr (rplacd splice
1905                          (list
1906                           (cond
1907                            ((case pred
1908                                    (normal
1909                                     (if test-not
1910                                         (not
1911                                          (funcall test-not old (apply-key key elt)))
1912                                         (funcall test old (apply-key key elt))))
1913                                    (if (funcall test (apply-key key elt)))
1914                                    (if-not (not (funcall test (apply-key key elt)))))
1915                             (decf count)
1916                             new)
1917                                 (t elt))))))
1918       (setq list (cdr list)))
1919     (do ()
1920         ((null list))
1921       (setq splice (cdr (rplacd splice (list (car list)))))
1922       (setq list (cdr list)))
1923     (cdr result)))
1924
1925 ;;; Replace old with new in sequence moving from left to right by incrementer
1926 ;;; on each pass through the loop. Called by all three substitute functions.
1927 (defun vector-substitute* (pred new sequence incrementer left right length
1928                            start end count key test test-not old)
1929   (declare (fixnum start count end incrementer right))
1930   (let ((result (%make-sequence-like sequence length))
1931         (index left))
1932     (declare (fixnum index))
1933     (do ()
1934         ((= index start))
1935       (setf (aref result index) (aref sequence index))
1936       (setq index (+ index incrementer)))
1937     (do ((elt))
1938         ((or (= index end) (= count 0)))
1939       (setq elt (aref sequence index))
1940       (setf (aref result index)
1941             (cond ((case pred
1942                           (normal
1943                             (if test-not
1944                                 (not (funcall test-not old (apply-key key elt)))
1945                                 (funcall test old (apply-key key elt))))
1946                           (if (funcall test (apply-key key elt)))
1947                           (if-not (not (funcall test (apply-key key elt)))))
1948                    (setq count (1- count))
1949                    new)
1950                   (t elt)))
1951       (setq index (+ index incrementer)))
1952     (do ()
1953         ((= index right))
1954       (setf (aref result index) (aref sequence index))
1955       (setq index (+ index incrementer)))
1956     result))
1957
1958 (eval-when (:compile-toplevel :execute)
1959
1960 (sb!xc:defmacro subst-dispatch (pred)
1961   `(seq-dispatch sequence
1962      (if from-end
1963          (nreverse (list-substitute* ,pred
1964                                      new
1965                                      (reverse sequence)
1966                                      (- (the fixnum length)
1967                                         (the fixnum end))
1968                                      (- (the fixnum length)
1969                                         (the fixnum start))
1970                                      count key test test-not old))
1971          (list-substitute* ,pred
1972                            new sequence start end count key test test-not
1973                            old))
1974     (if from-end
1975         (vector-substitute* ,pred new sequence -1 (1- (the fixnum length))
1976                             -1 length (1- (the fixnum end))
1977                             (1- (the fixnum start))
1978                             count key test test-not old)
1979         (vector-substitute* ,pred new sequence 1 0 length length
1980                             start end count key test test-not old))
1981     ;; FIXME: wow, this is an odd way to implement the dispatch.  PRED
1982     ;; here is (QUOTE [NORMAL|IF|IF-NOT]).  Not only is this pretty
1983     ;; pointless, but also LIST-SUBSTITUTE* and VECTOR-SUBSTITUTE*
1984     ;; dispatch once per element on PRED's run-time identity.
1985     ,(ecase (cadr pred)
1986        ((normal) `(apply #'sb!sequence:substitute new old sequence args))
1987        ((if) `(apply #'sb!sequence:substitute-if new predicate sequence args))
1988        ((if-not) `(apply #'sb!sequence:substitute-if-not new predicate sequence args)))))
1989 ) ; EVAL-WHEN
1990
1991 (define-sequence-traverser substitute
1992     (new old sequence &rest args &key from-end test test-not
1993          start count end key)
1994   #!+sb-doc
1995   "Return a sequence of the same kind as SEQUENCE with the same elements,
1996   except that all elements equal to OLD are replaced with NEW."
1997   (declare (fixnum start))
1998   (declare (truly-dynamic-extent args))
1999   (let ((end (or end length)))
2000     (declare (type index end))
2001     (subst-dispatch 'normal)))
2002 \f
2003 ;;;; SUBSTITUTE-IF, SUBSTITUTE-IF-NOT
2004
2005 (define-sequence-traverser substitute-if
2006     (new predicate sequence &rest args &key from-end start end count key)
2007   #!+sb-doc
2008   "Return a sequence of the same kind as SEQUENCE with the same elements
2009   except that all elements satisfying the PRED are replaced with NEW."
2010   (declare (truly-dynamic-extent args))
2011   (declare (fixnum start))
2012   (let ((end (or end length))
2013         (test predicate)
2014         (test-not nil)
2015         old)
2016     (declare (type index length end))
2017     (subst-dispatch 'if)))
2018
2019 (define-sequence-traverser substitute-if-not
2020     (new predicate sequence &rest args &key from-end start end count key)
2021   #!+sb-doc
2022   "Return a sequence of the same kind as SEQUENCE with the same elements
2023   except that all elements not satisfying the PRED are replaced with NEW."
2024   (declare (truly-dynamic-extent args))
2025   (declare (fixnum start))
2026   (let ((end (or end length))
2027         (test predicate)
2028         (test-not nil)
2029         old)
2030     (declare (type index length end))
2031     (subst-dispatch 'if-not)))
2032 \f
2033 ;;;; NSUBSTITUTE
2034
2035 (define-sequence-traverser nsubstitute
2036     (new old sequence &rest args &key from-end test test-not
2037          end count key start)
2038   #!+sb-doc
2039   "Return a sequence of the same kind as SEQUENCE with the same elements
2040   except that all elements equal to OLD are replaced with NEW. SEQUENCE
2041   may be destructively modified."
2042   (declare (fixnum start))
2043   (declare (truly-dynamic-extent args))
2044   (let ((end (or end length)))
2045     (seq-dispatch sequence
2046       (if from-end
2047           (let ((length (length sequence)))
2048             (nreverse (nlist-substitute*
2049                        new old (nreverse (the list sequence))
2050                        test test-not (- length end) (- length start)
2051                        count key)))
2052           (nlist-substitute* new old sequence
2053                              test test-not start end count key))
2054       (if from-end
2055           (nvector-substitute* new old sequence -1
2056                                test test-not (1- end) (1- start) count key)
2057           (nvector-substitute* new old sequence 1
2058                                test test-not start end count key))
2059       (apply #'sb!sequence:nsubstitute new old sequence args))))
2060
2061 (defun nlist-substitute* (new old sequence test test-not start end count key)
2062   (declare (fixnum start count end))
2063   (do ((list (nthcdr start sequence) (cdr list))
2064        (index start (1+ index)))
2065       ((or (= index end) (null list) (= count 0)) sequence)
2066     (declare (fixnum index))
2067     (when (if test-not
2068               (not (funcall test-not old (apply-key key (car list))))
2069               (funcall test old (apply-key key (car list))))
2070       (rplaca list new)
2071       (setq count (1- count)))))
2072
2073 (defun nvector-substitute* (new old sequence incrementer
2074                             test test-not start end count key)
2075   (declare (fixnum start incrementer count end))
2076   (do ((index start (+ index incrementer)))
2077       ((or (= index end) (= count 0)) sequence)
2078     (declare (fixnum index))
2079     (when (if test-not
2080               (not (funcall test-not
2081                             old
2082                             (apply-key key (aref sequence index))))
2083               (funcall test old (apply-key key (aref sequence index))))
2084       (setf (aref sequence index) new)
2085       (setq count (1- count)))))
2086 \f
2087 ;;;; NSUBSTITUTE-IF, NSUBSTITUTE-IF-NOT
2088
2089 (define-sequence-traverser nsubstitute-if
2090     (new predicate sequence &rest args &key from-end start end count key)
2091   #!+sb-doc
2092   "Return a sequence of the same kind as SEQUENCE with the same elements
2093    except that all elements satisfying PREDICATE are replaced with NEW.
2094    SEQUENCE may be destructively modified."
2095   (declare (fixnum start))
2096   (declare (truly-dynamic-extent args))
2097   (let ((end (or end length)))
2098     (declare (fixnum end))
2099     (seq-dispatch sequence
2100       (if from-end
2101           (let ((length (length sequence)))
2102             (nreverse (nlist-substitute-if*
2103                        new predicate (nreverse (the list sequence))
2104                        (- length end) (- length start) count key)))
2105           (nlist-substitute-if* new predicate sequence
2106                                 start end count key))
2107       (if from-end
2108           (nvector-substitute-if* new predicate sequence -1
2109                                   (1- end) (1- start) count key)
2110           (nvector-substitute-if* new predicate sequence 1
2111                                   start end count key))
2112       (apply #'sb!sequence:nsubstitute-if new predicate sequence args))))
2113
2114 (defun nlist-substitute-if* (new test sequence start end count key)
2115   (declare (fixnum end))
2116   (do ((list (nthcdr start sequence) (cdr list))
2117        (index start (1+ index)))
2118       ((or (= index end) (null list) (= count 0)) sequence)
2119     (when (funcall test (apply-key key (car list)))
2120       (rplaca list new)
2121       (setq count (1- count)))))
2122
2123 (defun nvector-substitute-if* (new test sequence incrementer
2124                                start end count key)
2125   (do ((index start (+ index incrementer)))
2126       ((or (= index end) (= count 0)) sequence)
2127     (when (funcall test (apply-key key (aref sequence index)))
2128       (setf (aref sequence index) new)
2129       (setq count (1- count)))))
2130
2131 (define-sequence-traverser nsubstitute-if-not
2132     (new predicate sequence &rest args &key from-end start end count key)
2133   #!+sb-doc
2134   "Return a sequence of the same kind as SEQUENCE with the same elements
2135    except that all elements not satisfying PREDICATE are replaced with NEW.
2136    SEQUENCE may be destructively modified."
2137   (declare (fixnum start))
2138   (declare (truly-dynamic-extent args))
2139   (let ((end (or end length)))
2140     (declare (fixnum end))
2141     (seq-dispatch sequence
2142       (if from-end
2143           (let ((length (length sequence)))
2144             (nreverse (nlist-substitute-if-not*
2145                        new predicate (nreverse (the list sequence))
2146                        (- length end) (- length start) count key)))
2147           (nlist-substitute-if-not* new predicate sequence
2148                                     start end count key))
2149       (if from-end
2150           (nvector-substitute-if-not* new predicate sequence -1
2151                                       (1- end) (1- start) count key)
2152           (nvector-substitute-if-not* new predicate sequence 1
2153                                       start end count key))
2154       (apply #'sb!sequence:nsubstitute-if-not new predicate sequence args))))
2155
2156 (defun nlist-substitute-if-not* (new test sequence start end count key)
2157   (declare (fixnum end))
2158   (do ((list (nthcdr start sequence) (cdr list))
2159        (index start (1+ index)))
2160       ((or (= index end) (null list) (= count 0)) sequence)
2161     (when (not (funcall test (apply-key key (car list))))
2162       (rplaca list new)
2163       (decf count))))
2164
2165 (defun nvector-substitute-if-not* (new test sequence incrementer
2166                                    start end count key)
2167   (do ((index start (+ index incrementer)))
2168       ((or (= index end) (= count 0)) sequence)
2169     (when (not (funcall test (apply-key key (aref sequence index))))
2170       (setf (aref sequence index) new)
2171       (decf count))))
2172 \f
2173 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
2174
2175 (defun effective-find-position-test (test test-not)
2176   (effective-find-position-test test test-not))
2177 (defun effective-find-position-key (key)
2178   (effective-find-position-key key))
2179
2180 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
2181 (macrolet (;; shared logic for defining %FIND-POSITION and
2182            ;; %FIND-POSITION-IF in terms of various inlineable cases
2183            ;; of the expression defined in FROB and VECTOR*-FROB
2184            (frobs ()
2185              `(seq-dispatch sequence-arg
2186                (frob sequence-arg from-end)
2187                (with-array-data ((sequence sequence-arg :offset-var offset)
2188                                  (start start)
2189                                  (end end)
2190                                  :check-fill-pointer t)
2191                  (multiple-value-bind (f p)
2192                      (macrolet ((frob2 () '(if from-end
2193                                             (frob sequence t)
2194                                             (frob sequence nil))))
2195                        (typecase sequence
2196                          #!+sb-unicode
2197                          ((simple-array character (*)) (frob2))
2198                          ((simple-array base-char (*)) (frob2))
2199                          (t (vector*-frob sequence))))
2200                    (declare (type (or index null) p))
2201                    (values f (and p (the index (- p offset)))))))))
2202   (defun %find-position (item sequence-arg from-end start end key test)
2203     (macrolet ((frob (sequence from-end)
2204                  `(%find-position item ,sequence
2205                                   ,from-end start end key test))
2206                (vector*-frob (sequence)
2207                  `(%find-position-vector-macro item ,sequence
2208                                                from-end start end key test)))
2209       (frobs)))
2210   (defun %find-position-if (predicate sequence-arg from-end start end key)
2211     (macrolet ((frob (sequence from-end)
2212                  `(%find-position-if predicate ,sequence
2213                                      ,from-end start end key))
2214                (vector*-frob (sequence)
2215                  `(%find-position-if-vector-macro predicate ,sequence
2216                                                   from-end start end key)))
2217       (frobs)))
2218   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
2219     (macrolet ((frob (sequence from-end)
2220                  `(%find-position-if-not predicate ,sequence
2221                                          ,from-end start end key))
2222                (vector*-frob (sequence)
2223                  `(%find-position-if-not-vector-macro predicate ,sequence
2224                                                   from-end start end key)))
2225       (frobs))))
2226
2227 (defun find
2228     (item sequence &rest args &key from-end (start 0) end key test test-not)
2229   (declare (truly-dynamic-extent args))
2230   (seq-dispatch sequence
2231     (nth-value 0 (%find-position
2232                   item sequence from-end start end
2233                   (effective-find-position-key key)
2234                   (effective-find-position-test test test-not)))
2235     (nth-value 0 (%find-position
2236                   item sequence from-end start end
2237                   (effective-find-position-key key)
2238                   (effective-find-position-test test test-not)))
2239     (apply #'sb!sequence:find item sequence args)))
2240 (defun position
2241     (item sequence &rest args &key from-end (start 0) end key test test-not)
2242   (declare (truly-dynamic-extent args))
2243   (seq-dispatch sequence
2244     (nth-value 1 (%find-position
2245                   item sequence from-end start end
2246                   (effective-find-position-key key)
2247                   (effective-find-position-test test test-not)))
2248     (nth-value 1 (%find-position
2249                   item sequence from-end start end
2250                   (effective-find-position-key key)
2251                   (effective-find-position-test test test-not)))
2252     (apply #'sb!sequence:position item sequence args)))
2253
2254 (defun find-if (predicate sequence &rest args &key from-end (start 0) end key)
2255   (declare (truly-dynamic-extent args))
2256   (seq-dispatch sequence
2257     (nth-value 0 (%find-position-if
2258                   (%coerce-callable-to-fun predicate)
2259                   sequence from-end start end
2260                   (effective-find-position-key key)))
2261     (nth-value 0 (%find-position-if
2262                   (%coerce-callable-to-fun predicate)
2263                   sequence from-end start end
2264                   (effective-find-position-key key)))
2265     (apply #'sb!sequence:find-if predicate sequence args)))
2266 (defun position-if
2267     (predicate sequence &rest args &key from-end (start 0) end key)
2268   (declare (truly-dynamic-extent args))
2269   (seq-dispatch sequence
2270     (nth-value 1 (%find-position-if
2271                   (%coerce-callable-to-fun predicate)
2272                   sequence from-end start end
2273                   (effective-find-position-key key)))
2274     (nth-value 1 (%find-position-if
2275                   (%coerce-callable-to-fun predicate)
2276                   sequence from-end start end
2277                   (effective-find-position-key key)))
2278     (apply #'sb!sequence:position-if predicate sequence args)))
2279
2280 (defun find-if-not
2281     (predicate sequence &rest args &key from-end (start 0) end key)
2282   (declare (truly-dynamic-extent args))
2283   (seq-dispatch sequence
2284     (nth-value 0 (%find-position-if-not
2285                   (%coerce-callable-to-fun predicate)
2286                   sequence from-end start end
2287                   (effective-find-position-key key)))
2288     (nth-value 0 (%find-position-if-not
2289                   (%coerce-callable-to-fun predicate)
2290                   sequence from-end start end
2291                   (effective-find-position-key key)))
2292     (apply #'sb!sequence:find-if-not predicate sequence args)))
2293 (defun position-if-not
2294     (predicate sequence &rest args &key from-end (start 0) end key)
2295   (declare (truly-dynamic-extent args))
2296   (seq-dispatch sequence
2297     (nth-value 1 (%find-position-if-not
2298                   (%coerce-callable-to-fun predicate)
2299                   sequence from-end start end
2300                   (effective-find-position-key key)))
2301     (nth-value 1 (%find-position-if-not
2302                   (%coerce-callable-to-fun predicate)
2303                   sequence from-end start end
2304                   (effective-find-position-key key)))
2305     (apply #'sb!sequence:position-if-not predicate sequence args)))
2306 \f
2307 ;;;; COUNT-IF, COUNT-IF-NOT, and COUNT
2308
2309 (eval-when (:compile-toplevel :execute)
2310
2311 (sb!xc:defmacro vector-count-if (notp from-end-p predicate sequence)
2312   (let ((next-index (if from-end-p '(1- index) '(1+ index)))
2313         (pred `(funcall ,predicate (apply-key key (aref ,sequence index)))))
2314     `(let ((%start ,(if from-end-p '(1- end) 'start))
2315            (%end ,(if from-end-p '(1- start) 'end)))
2316       (do ((index %start ,next-index)
2317            (count 0))
2318           ((= index (the fixnum %end)) count)
2319         (declare (fixnum index count))
2320         (,(if notp 'unless 'when) ,pred
2321           (setq count (1+ count)))))))
2322
2323 (sb!xc:defmacro list-count-if (notp from-end-p predicate sequence)
2324   (let ((pred `(funcall ,predicate (apply-key key (pop sequence)))))
2325     `(let ((%start ,(if from-end-p '(- length end) 'start))
2326            (%end ,(if from-end-p '(- length start) 'end))
2327            (sequence ,(if from-end-p '(reverse sequence) 'sequence)))
2328       (do ((sequence (nthcdr %start ,sequence))
2329            (index %start (1+ index))
2330            (count 0))
2331           ((or (= index (the fixnum %end)) (null sequence)) count)
2332         (declare (fixnum index count))
2333         (,(if notp 'unless 'when) ,pred
2334           (setq count (1+ count)))))))
2335
2336
2337 ) ; EVAL-WHEN
2338
2339 (define-sequence-traverser count-if
2340     (pred sequence &rest args &key from-end start end key)
2341   #!+sb-doc
2342   "Return the number of elements in SEQUENCE satisfying PRED(el)."
2343   (declare (fixnum start))
2344   (declare (truly-dynamic-extent args))
2345   (let ((end (or end length))
2346         (pred (%coerce-callable-to-fun pred)))
2347     (declare (type index end))
2348     (seq-dispatch sequence
2349       (if from-end
2350           (list-count-if nil t pred sequence)
2351           (list-count-if nil nil pred sequence))
2352       (if from-end
2353           (vector-count-if nil t pred sequence)
2354           (vector-count-if nil nil pred sequence))
2355       (apply #'sb!sequence:count-if pred sequence args))))
2356
2357 (define-sequence-traverser count-if-not
2358     (pred sequence &rest args &key from-end start end key)
2359   #!+sb-doc
2360   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2361   (declare (fixnum start))
2362   (declare (truly-dynamic-extent args))
2363   (let ((end (or end length))
2364         (pred (%coerce-callable-to-fun pred)))
2365     (declare (type index end))
2366     (seq-dispatch sequence
2367       (if from-end
2368           (list-count-if t t pred sequence)
2369           (list-count-if t nil pred sequence))
2370       (if from-end
2371           (vector-count-if t t pred sequence)
2372           (vector-count-if t nil pred sequence))
2373       (apply #'sb!sequence:count-if-not pred sequence args))))
2374
2375 (define-sequence-traverser count
2376     (item sequence &rest args &key from-end start end
2377           key (test #'eql test-p) (test-not nil test-not-p))
2378   #!+sb-doc
2379   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2380    which defaults to EQL."
2381   (declare (fixnum start))
2382   (declare (truly-dynamic-extent args))
2383   (when (and test-p test-not-p)
2384     ;; ANSI Common Lisp has left the behavior in this situation unspecified.
2385     ;; (CLHS 17.2.1)
2386     (error ":TEST and :TEST-NOT are both present."))
2387   (let ((end (or end length)))
2388     (declare (type index end))
2389     (let ((%test (if test-not-p
2390                      (lambda (x)
2391                        (not (funcall test-not item x)))
2392                      (lambda (x)
2393                        (funcall test item x)))))
2394       (seq-dispatch sequence
2395         (if from-end
2396             (list-count-if nil t %test sequence)
2397             (list-count-if nil nil %test sequence))
2398         (if from-end
2399             (vector-count-if nil t %test sequence)
2400             (vector-count-if nil nil %test sequence))
2401         (apply #'sb!sequence:count item sequence args)))))
2402 \f
2403 ;;;; MISMATCH
2404
2405 (eval-when (:compile-toplevel :execute)
2406
2407 (sb!xc:defmacro match-vars (&rest body)
2408   `(let ((inc (if from-end -1 1))
2409          (start1 (if from-end (1- (the fixnum end1)) start1))
2410          (start2 (if from-end (1- (the fixnum end2)) start2))
2411          (end1 (if from-end (1- (the fixnum start1)) end1))
2412          (end2 (if from-end (1- (the fixnum start2)) end2)))
2413      (declare (fixnum inc start1 start2 end1 end2))
2414      ,@body))
2415
2416 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2417   (declare (ignore end)) ;; ### Should END be used below?
2418   `(let ((,sequence (if from-end
2419                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2420                                 (reverse (the list ,sequence)))
2421                         (nthcdr ,start ,sequence))))
2422      (declare (type list ,sequence))
2423      ,@body))
2424
2425 ) ; EVAL-WHEN
2426
2427 (eval-when (:compile-toplevel :execute)
2428
2429 (sb!xc:defmacro if-mismatch (elt1 elt2)
2430   `(cond ((= (the fixnum index1) (the fixnum end1))
2431           (return (if (= (the fixnum index2) (the fixnum end2))
2432                       nil
2433                       (if from-end
2434                           (1+ (the fixnum index1))
2435                           (the fixnum index1)))))
2436          ((= (the fixnum index2) (the fixnum end2))
2437           (return (if from-end (1+ (the fixnum index1)) index1)))
2438          (test-not
2439           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2440               (return (if from-end (1+ (the fixnum index1)) index1))))
2441          (t (if (not (funcall test (apply-key key ,elt1)
2442                               (apply-key key ,elt2)))
2443                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2444
2445 (sb!xc:defmacro mumble-mumble-mismatch ()
2446   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2447         (index2 start2 (+ index2 (the fixnum inc))))
2448        (())
2449      (declare (fixnum index1 index2))
2450      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2451
2452 (sb!xc:defmacro mumble-list-mismatch ()
2453   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2454         (index2 start2 (+ index2 (the fixnum inc))))
2455        (())
2456      (declare (fixnum index1 index2))
2457      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2458 \f
2459 (sb!xc:defmacro list-mumble-mismatch ()
2460   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2461         (index2 start2 (+ index2 (the fixnum inc))))
2462        (())
2463      (declare (fixnum index1 index2))
2464      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2465
2466 (sb!xc:defmacro list-list-mismatch ()
2467   `(do ((sequence1 sequence1)
2468         (sequence2 sequence2)
2469         (index1 start1 (+ index1 (the fixnum inc)))
2470         (index2 start2 (+ index2 (the fixnum inc))))
2471        (())
2472      (declare (fixnum index1 index2))
2473      (if-mismatch (pop sequence1) (pop sequence2))))
2474
2475 ) ; EVAL-WHEN
2476
2477 (define-sequence-traverser mismatch
2478     (sequence1 sequence2 &rest args &key from-end test test-not
2479      start1 end1 start2 end2 key)
2480   #!+sb-doc
2481   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2482    element-wise. If they are of equal length and match in every element, the
2483    result is NIL. Otherwise, the result is a non-negative integer, the index
2484    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2485    if one is shorter than and a matching prefix of the other, the index within
2486    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2487    :FROM-END argument is given, then one plus the index of the rightmost
2488    position in which the sequences differ is returned."
2489   (declare (fixnum start1 start2))
2490   (declare (truly-dynamic-extent args))
2491   (let* ((end1 (or end1 length1))
2492          (end2 (or end2 length2)))
2493     (declare (type index end1 end2))
2494     (match-vars
2495      (seq-dispatch sequence1
2496        (seq-dispatch sequence2
2497          (matchify-list (sequence1 start1 length1 end1)
2498            (matchify-list (sequence2 start2 length2 end2)
2499              (list-list-mismatch)))
2500          (matchify-list (sequence1 start1 length1 end1)
2501            (list-mumble-mismatch))
2502          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2503        (seq-dispatch sequence2
2504          (matchify-list (sequence2 start2 length2 end2)
2505            (mumble-list-mismatch))
2506          (mumble-mumble-mismatch)
2507          (apply #'sb!sequence:mismatch sequence1 sequence2 args))
2508        (apply #'sb!sequence:mismatch sequence1 sequence2 args)))))
2509 \f
2510 ;;; search comparison functions
2511
2512 (eval-when (:compile-toplevel :execute)
2513
2514 ;;; Compare two elements and return if they don't match.
2515 (sb!xc:defmacro compare-elements (elt1 elt2)
2516   `(if test-not
2517        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2518            (return nil)
2519            t)
2520        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2521            (return nil)
2522            t)))
2523
2524 (sb!xc:defmacro search-compare-list-list (main sub)
2525   `(do ((main ,main (cdr main))
2526         (jndex start1 (1+ jndex))
2527         (sub (nthcdr start1 ,sub) (cdr sub)))
2528        ((or (endp main) (endp sub) (<= end1 jndex))
2529         t)
2530      (declare (type (integer 0) jndex))
2531      (compare-elements (car sub) (car main))))
2532
2533 (sb!xc:defmacro search-compare-list-vector (main sub)
2534   `(do ((main ,main (cdr main))
2535         (index start1 (1+ index)))
2536        ((or (endp main) (= index end1)) t)
2537      (compare-elements (aref ,sub index) (car main))))
2538
2539 (sb!xc:defmacro search-compare-vector-list (main sub index)
2540   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2541         (jndex start1 (1+ jndex))
2542         (index ,index (1+ index)))
2543        ((or (<= end1 jndex) (endp sub)) t)
2544      (declare (type (integer 0) jndex))
2545      (compare-elements (car sub) (aref ,main index))))
2546
2547 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2548   `(do ((index ,index (1+ index))
2549         (sub-index start1 (1+ sub-index)))
2550        ((= sub-index end1) t)
2551      (compare-elements (aref ,sub sub-index) (aref ,main index))))
2552
2553 (sb!xc:defmacro search-compare (main-type main sub index)
2554   (if (eq main-type 'list)
2555       `(seq-dispatch ,sub
2556          (search-compare-list-list ,main ,sub)
2557          (search-compare-list-vector ,main ,sub)
2558          ;; KLUDGE: just hack it together so that it works
2559          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))
2560       `(seq-dispatch ,sub
2561          (search-compare-vector-list ,main ,sub ,index)
2562          (search-compare-vector-vector ,main ,sub ,index)
2563          (return-from search (apply #'sb!sequence:search sequence1 sequence2 args)))))
2564
2565 ) ; EVAL-WHEN
2566 \f
2567 ;;;; SEARCH
2568
2569 (eval-when (:compile-toplevel :execute)
2570
2571 (sb!xc:defmacro list-search (main sub)
2572   `(do ((main (nthcdr start2 ,main) (cdr main))
2573         (index2 start2 (1+ index2))
2574         (terminus (- end2 (the (integer 0) (- end1 start1))))
2575         (last-match ()))
2576        ((> index2 terminus) last-match)
2577      (declare (type (integer 0) index2))
2578      (if (search-compare list main ,sub index2)
2579          (if from-end
2580              (setq last-match index2)
2581              (return index2)))))
2582
2583 (sb!xc:defmacro vector-search (main sub)
2584   `(do ((index2 start2 (1+ index2))
2585         (terminus (- end2 (the (integer 0) (- end1 start1))))
2586         (last-match ()))
2587        ((> index2 terminus) last-match)
2588      (declare (type (integer 0) index2))
2589      (if (search-compare vector ,main ,sub index2)
2590          (if from-end
2591              (setq last-match index2)
2592              (return index2)))))
2593
2594 ) ; EVAL-WHEN
2595
2596 (define-sequence-traverser search
2597     (sequence1 sequence2 &rest args &key
2598      from-end test test-not start1 end1 start2 end2 key)
2599   (declare (fixnum start1 start2))
2600   (declare (truly-dynamic-extent args))
2601   (let ((end1 (or end1 length1))
2602         (end2 (or end2 length2)))
2603     (seq-dispatch sequence2
2604       (list-search sequence2 sequence1)
2605       (vector-search sequence2 sequence1)
2606       (apply #'sb!sequence:search sequence1 sequence2 args))))
2607
2608 ;;; FIXME: this was originally in array.lisp; it might be better to
2609 ;;; put it back there, and make DOSEQUENCE and SEQ-DISPATCH be in
2610 ;;; a new early-seq.lisp file.
2611 (defun fill-data-vector (vector dimensions initial-contents)
2612   (let ((index 0))
2613     (labels ((frob (axis dims contents)
2614                (cond ((null dims)
2615                       (setf (aref vector index) contents)
2616                       (incf index))
2617                      (t
2618                       (unless (typep contents 'sequence)
2619                         (error "malformed :INITIAL-CONTENTS: ~S is not a ~
2620                                 sequence, but ~W more layer~:P needed."
2621                                contents
2622                                (- (length dimensions) axis)))
2623                       (unless (= (length contents) (car dims))
2624                         (error "malformed :INITIAL-CONTENTS: Dimension of ~
2625                                 axis ~W is ~W, but ~S is ~W long."
2626                                axis (car dims) contents (length contents)))
2627                       (sb!sequence:dosequence (content contents)
2628                         (frob (1+ axis) (cdr dims) content))))))
2629       (frob 0 dimensions initial-contents))))