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