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