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