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