0.8.16.25:
[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 (the fixnum ,end)) value)
1083      (declare (fixnum index))
1084      (setq value (funcall ,function value
1085                           (apply-key ,key (,ref ,sequence index))))))
1086
1087 (sb!xc:defmacro mumble-reduce-from-end (function
1088                                         sequence
1089                                         key
1090                                         start
1091                                         end
1092                                         initial-value
1093                                         ref)
1094   `(do ((index (1- ,end) (1- index))
1095         (value ,initial-value)
1096         (terminus (1- ,start)))
1097        ((= index terminus) value)
1098      (declare (fixnum index terminus))
1099      (setq value (funcall ,function
1100                           (apply-key ,key (,ref ,sequence index))
1101                           value))))
1102
1103 (sb!xc:defmacro list-reduce (function
1104                              sequence
1105                              key
1106                              start
1107                              end
1108                              initial-value
1109                              ivp)
1110   `(let ((sequence (nthcdr ,start ,sequence)))
1111      (do ((count (if ,ivp ,start (1+ (the fixnum ,start)))
1112                  (1+ count))
1113           (sequence (if ,ivp sequence (cdr sequence))
1114                     (cdr sequence))
1115           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1116                  (funcall ,function value (apply-key ,key (car sequence)))))
1117          ((= count (the fixnum ,end)) value)
1118        (declare (fixnum count)))))
1119
1120 (sb!xc:defmacro list-reduce-from-end (function
1121                                       sequence
1122                                       key
1123                                       start
1124                                       end
1125                                       initial-value
1126                                       ivp)
1127   `(let ((sequence (nthcdr (- (the fixnum (length ,sequence))
1128                               (the fixnum ,end))
1129                            (reverse ,sequence))))
1130      (do ((count (if ,ivp ,start (1+ (the fixnum ,start)))
1131                  (1+ count))
1132           (sequence (if ,ivp sequence (cdr sequence))
1133                     (cdr sequence))
1134           (value (if ,ivp ,initial-value (apply-key ,key (car sequence)))
1135                  (funcall ,function (apply-key ,key (car sequence)) value)))
1136          ((= count (the fixnum ,end)) value)
1137        (declare (fixnum count)))))
1138
1139 ) ; EVAL-WHEN
1140
1141 (define-sequence-traverser reduce
1142     (function sequence &key key from-end start end (initial-value nil ivp))
1143   (declare (type index start))
1144   (let ((start start)
1145         (end (or end length)))
1146     (declare (type index start end))
1147     (cond ((= end start)
1148            (if ivp initial-value (funcall function)))
1149           ((listp sequence)
1150            (if from-end
1151                (list-reduce-from-end function sequence key start end
1152                                      initial-value ivp)
1153                (list-reduce function sequence key start end
1154                             initial-value ivp)))
1155           (from-end
1156            (when (not ivp)
1157              (setq end (1- (the fixnum end)))
1158              (setq initial-value (apply-key key (aref sequence end))))
1159            (mumble-reduce-from-end function sequence key start end
1160                                    initial-value aref))
1161           (t
1162            (when (not ivp)
1163              (setq initial-value (apply-key key (aref sequence start)))
1164              (setq start (1+ start)))
1165            (mumble-reduce function sequence key start end
1166                           initial-value aref)))))
1167 \f
1168 ;;;; DELETE
1169
1170 (eval-when (:compile-toplevel :execute)
1171
1172 (sb!xc:defmacro mumble-delete (pred)
1173   `(do ((index start (1+ index))
1174         (jndex start)
1175         (number-zapped 0))
1176        ((or (= index (the fixnum end)) (= number-zapped count))
1177         (do ((index index (1+ index))           ; Copy the rest of the vector.
1178              (jndex jndex (1+ jndex)))
1179             ((= index (the fixnum length))
1180              (shrink-vector sequence jndex))
1181           (declare (fixnum index jndex))
1182           (setf (aref sequence jndex) (aref sequence index))))
1183      (declare (fixnum index jndex number-zapped))
1184      (setf (aref sequence jndex) (aref sequence index))
1185      (if ,pred
1186          (incf number-zapped)
1187          (incf jndex))))
1188
1189 (sb!xc:defmacro mumble-delete-from-end (pred)
1190   `(do ((index (1- (the fixnum end)) (1- index)) ; Find the losers.
1191         (number-zapped 0)
1192         (losers ())
1193         this-element
1194         (terminus (1- start)))
1195        ((or (= index terminus) (= number-zapped count))
1196         (do ((losers losers)                     ; Delete the losers.
1197              (index start (1+ index))
1198              (jndex start))
1199             ((or (null losers) (= index (the fixnum end)))
1200              (do ((index index (1+ index))       ; Copy the rest of the vector.
1201                   (jndex jndex (1+ jndex)))
1202                  ((= index (the fixnum length))
1203                   (shrink-vector sequence jndex))
1204                (declare (fixnum index jndex))
1205                (setf (aref sequence jndex) (aref sequence index))))
1206           (declare (fixnum index jndex))
1207           (setf (aref sequence jndex) (aref sequence index))
1208           (if (= index (the fixnum (car losers)))
1209               (pop losers)
1210               (incf jndex))))
1211      (declare (fixnum index number-zapped terminus))
1212      (setq this-element (aref sequence index))
1213      (when ,pred
1214        (incf number-zapped)
1215        (push index losers))))
1216
1217 (sb!xc:defmacro normal-mumble-delete ()
1218   `(mumble-delete
1219     (if test-not
1220         (not (funcall test-not item (apply-key key (aref sequence index))))
1221         (funcall test item (apply-key key (aref sequence index))))))
1222
1223 (sb!xc:defmacro normal-mumble-delete-from-end ()
1224   `(mumble-delete-from-end
1225     (if test-not
1226         (not (funcall test-not item (apply-key key this-element)))
1227         (funcall test item (apply-key key this-element)))))
1228
1229 (sb!xc:defmacro list-delete (pred)
1230   `(let ((handle (cons nil sequence)))
1231      (do ((current (nthcdr start sequence) (cdr current))
1232           (previous (nthcdr start handle))
1233           (index start (1+ index))
1234           (number-zapped 0))
1235          ((or (= index (the fixnum end)) (= number-zapped count))
1236           (cdr handle))
1237        (declare (fixnum index number-zapped))
1238        (cond (,pred
1239               (rplacd previous (cdr current))
1240               (incf number-zapped))
1241              (t
1242               (setq previous (cdr previous)))))))
1243
1244 (sb!xc:defmacro list-delete-from-end (pred)
1245   `(let* ((reverse (nreverse (the list sequence)))
1246           (handle (cons nil reverse)))
1247      (do ((current (nthcdr (- (the fixnum length) (the fixnum end)) reverse)
1248                    (cdr current))
1249           (previous (nthcdr (- (the fixnum length) (the fixnum end)) handle))
1250           (index start (1+ index))
1251           (number-zapped 0))
1252          ((or (= index (the fixnum end)) (= number-zapped count))
1253           (nreverse (cdr handle)))
1254        (declare (fixnum index number-zapped))
1255        (cond (,pred
1256               (rplacd previous (cdr current))
1257               (incf number-zapped))
1258              (t
1259               (setq previous (cdr previous)))))))
1260
1261 (sb!xc:defmacro normal-list-delete ()
1262   '(list-delete
1263     (if test-not
1264         (not (funcall test-not item (apply-key key (car current))))
1265         (funcall test item (apply-key key (car current))))))
1266
1267 (sb!xc:defmacro normal-list-delete-from-end ()
1268   '(list-delete-from-end
1269     (if test-not
1270         (not (funcall test-not item (apply-key key (car current))))
1271         (funcall test item (apply-key key (car current))))))
1272
1273 ) ; EVAL-WHEN
1274
1275 (define-sequence-traverser delete
1276     (item sequence &key from-end test test-not start
1277           end count key)
1278   #!+sb-doc
1279   "Return a sequence formed by destructively removing the specified ITEM from
1280   the given SEQUENCE."
1281   (declare (fixnum start))
1282   (let ((end (or end length)))
1283     (declare (type index end))
1284     (seq-dispatch sequence
1285                   (if from-end
1286                       (normal-list-delete-from-end)
1287                       (normal-list-delete))
1288                   (if from-end
1289                       (normal-mumble-delete-from-end)
1290                       (normal-mumble-delete)))))
1291
1292 (eval-when (:compile-toplevel :execute)
1293
1294 (sb!xc:defmacro if-mumble-delete ()
1295   `(mumble-delete
1296     (funcall predicate (apply-key key (aref sequence index)))))
1297
1298 (sb!xc:defmacro if-mumble-delete-from-end ()
1299   `(mumble-delete-from-end
1300     (funcall predicate (apply-key key this-element))))
1301
1302 (sb!xc:defmacro if-list-delete ()
1303   '(list-delete
1304     (funcall predicate (apply-key key (car current)))))
1305
1306 (sb!xc:defmacro if-list-delete-from-end ()
1307   '(list-delete-from-end
1308     (funcall predicate (apply-key key (car current)))))
1309
1310 ) ; EVAL-WHEN
1311
1312 (define-sequence-traverser delete-if
1313     (predicate sequence &key from-end start key end count)
1314   #!+sb-doc
1315   "Return a sequence formed by destructively removing the elements satisfying
1316   the specified PREDICATE from the given SEQUENCE."
1317   (declare (fixnum start))
1318   (let ((end (or end length)))
1319     (declare (type index end))
1320     (seq-dispatch sequence
1321                   (if from-end
1322                       (if-list-delete-from-end)
1323                       (if-list-delete))
1324                   (if from-end
1325                       (if-mumble-delete-from-end)
1326                       (if-mumble-delete)))))
1327
1328 (eval-when (:compile-toplevel :execute)
1329
1330 (sb!xc:defmacro if-not-mumble-delete ()
1331   `(mumble-delete
1332     (not (funcall predicate (apply-key key (aref sequence index))))))
1333
1334 (sb!xc:defmacro if-not-mumble-delete-from-end ()
1335   `(mumble-delete-from-end
1336     (not (funcall predicate (apply-key key this-element)))))
1337
1338 (sb!xc:defmacro if-not-list-delete ()
1339   '(list-delete
1340     (not (funcall predicate (apply-key key (car current))))))
1341
1342 (sb!xc:defmacro if-not-list-delete-from-end ()
1343   '(list-delete-from-end
1344     (not (funcall predicate (apply-key key (car current))))))
1345
1346 ) ; EVAL-WHEN
1347
1348 (define-sequence-traverser delete-if-not
1349     (predicate sequence &key from-end start end key count)
1350   #!+sb-doc
1351   "Return a sequence formed by destructively removing the elements not
1352   satisfying the specified PREDICATE from the given SEQUENCE."
1353   (declare (fixnum start))
1354   (let ((end (or end length)))
1355     (declare (type index end))
1356     (seq-dispatch sequence
1357                   (if from-end
1358                       (if-not-list-delete-from-end)
1359                       (if-not-list-delete))
1360                   (if from-end
1361                       (if-not-mumble-delete-from-end)
1362                       (if-not-mumble-delete)))))
1363 \f
1364 ;;;; REMOVE
1365
1366 (eval-when (:compile-toplevel :execute)
1367
1368 ;;; MUMBLE-REMOVE-MACRO does not include (removes) each element that
1369 ;;; satisfies the predicate.
1370 (sb!xc:defmacro mumble-remove-macro (bump left begin finish right pred)
1371   `(do ((index ,begin (,bump index))
1372         (result
1373          (do ((index ,left (,bump index))
1374               (result (make-sequence-like sequence length)))
1375              ((= index (the fixnum ,begin)) result)
1376            (declare (fixnum index))
1377            (setf (aref result index) (aref sequence index))))
1378         (new-index ,begin)
1379         (number-zapped 0)
1380         (this-element))
1381        ((or (= index (the fixnum ,finish))
1382             (= number-zapped count))
1383         (do ((index index (,bump index))
1384              (new-index new-index (,bump new-index)))
1385             ((= index (the fixnum ,right)) (shrink-vector result new-index))
1386           (declare (fixnum index new-index))
1387           (setf (aref result new-index) (aref sequence index))))
1388      (declare (fixnum index new-index number-zapped))
1389      (setq this-element (aref sequence index))
1390      (cond (,pred (incf number-zapped))
1391            (t (setf (aref result new-index) this-element)
1392               (setq new-index (,bump new-index))))))
1393
1394 (sb!xc:defmacro mumble-remove (pred)
1395   `(mumble-remove-macro 1+ 0 start end length ,pred))
1396
1397 (sb!xc:defmacro mumble-remove-from-end (pred)
1398   `(let ((sequence (copy-seq sequence)))
1399      (mumble-delete-from-end ,pred)))
1400
1401 (sb!xc:defmacro normal-mumble-remove ()
1402   `(mumble-remove
1403     (if test-not
1404         (not (funcall test-not item (apply-key key this-element)))
1405         (funcall test item (apply-key key this-element)))))
1406
1407 (sb!xc:defmacro normal-mumble-remove-from-end ()
1408   `(mumble-remove-from-end
1409     (if test-not
1410         (not (funcall test-not item (apply-key key this-element)))
1411         (funcall test item (apply-key key this-element)))))
1412
1413 (sb!xc:defmacro if-mumble-remove ()
1414   `(mumble-remove (funcall predicate (apply-key key this-element))))
1415
1416 (sb!xc:defmacro if-mumble-remove-from-end ()
1417   `(mumble-remove-from-end (funcall predicate (apply-key key this-element))))
1418
1419 (sb!xc:defmacro if-not-mumble-remove ()
1420   `(mumble-remove (not (funcall predicate (apply-key key this-element)))))
1421
1422 (sb!xc:defmacro if-not-mumble-remove-from-end ()
1423   `(mumble-remove-from-end
1424     (not (funcall predicate (apply-key key this-element)))))
1425
1426 ;;; LIST-REMOVE-MACRO does not include (removes) each element that satisfies
1427 ;;; the predicate.
1428 (sb!xc:defmacro list-remove-macro (pred reverse?)
1429   `(let* ((sequence ,(if reverse?
1430                          '(reverse (the list sequence))
1431                          'sequence))
1432           (%start ,(if reverse? '(- length end) 'start))
1433           (%end ,(if reverse? '(- length start) 'end))
1434           (splice (list nil))
1435           (results (do ((index 0 (1+ index))
1436                         (before-start splice))
1437                        ((= index (the fixnum %start)) before-start)
1438                      (declare (fixnum index))
1439                      (setq splice
1440                            (cdr (rplacd splice (list (pop sequence))))))))
1441      (do ((index %start (1+ index))
1442           (this-element)
1443           (number-zapped 0))
1444          ((or (= index (the fixnum %end)) (= number-zapped count))
1445           (do ((index index (1+ index)))
1446               ((null sequence)
1447                ,(if reverse?
1448                     '(nreverse (the list (cdr results)))
1449                     '(cdr results)))
1450             (declare (fixnum index))
1451             (setq splice (cdr (rplacd splice (list (pop sequence)))))))
1452        (declare (fixnum index number-zapped))
1453        (setq this-element (pop sequence))
1454        (if ,pred
1455            (setq number-zapped (1+ number-zapped))
1456            (setq splice (cdr (rplacd splice (list this-element))))))))
1457
1458 (sb!xc:defmacro list-remove (pred)
1459   `(list-remove-macro ,pred nil))
1460
1461 (sb!xc:defmacro list-remove-from-end (pred)
1462   `(list-remove-macro ,pred t))
1463
1464 (sb!xc:defmacro normal-list-remove ()
1465   `(list-remove
1466     (if test-not
1467         (not (funcall test-not item (apply-key key this-element)))
1468         (funcall test item (apply-key key this-element)))))
1469
1470 (sb!xc:defmacro normal-list-remove-from-end ()
1471   `(list-remove-from-end
1472     (if test-not
1473         (not (funcall test-not item (apply-key key this-element)))
1474         (funcall test item (apply-key key this-element)))))
1475
1476 (sb!xc:defmacro if-list-remove ()
1477   `(list-remove
1478     (funcall predicate (apply-key key this-element))))
1479
1480 (sb!xc:defmacro if-list-remove-from-end ()
1481   `(list-remove-from-end
1482     (funcall predicate (apply-key key this-element))))
1483
1484 (sb!xc:defmacro if-not-list-remove ()
1485   `(list-remove
1486     (not (funcall predicate (apply-key key this-element)))))
1487
1488 (sb!xc:defmacro if-not-list-remove-from-end ()
1489   `(list-remove-from-end
1490     (not (funcall predicate (apply-key key this-element)))))
1491
1492 ) ; EVAL-WHEN
1493
1494 (define-sequence-traverser remove
1495     (item sequence &key from-end test test-not start
1496           end count key)
1497   #!+sb-doc
1498   "Return a copy of SEQUENCE with elements satisfying the test (default is
1499    EQL) with ITEM removed."
1500   (declare (fixnum start))
1501   (let ((end (or end length)))
1502     (declare (type index end))
1503     (seq-dispatch sequence
1504                   (if from-end
1505                       (normal-list-remove-from-end)
1506                       (normal-list-remove))
1507                   (if from-end
1508                       (normal-mumble-remove-from-end)
1509                       (normal-mumble-remove)))))
1510
1511 (define-sequence-traverser remove-if
1512     (predicate sequence &key from-end start end count key)
1513   #!+sb-doc
1514   "Return a copy of sequence with elements such that predicate(element)
1515    is non-null removed"
1516   (declare (fixnum start))
1517   (let ((end (or end length)))
1518     (declare (type index end))
1519     (seq-dispatch sequence
1520                   (if from-end
1521                       (if-list-remove-from-end)
1522                       (if-list-remove))
1523                   (if from-end
1524                       (if-mumble-remove-from-end)
1525                       (if-mumble-remove)))))
1526
1527 (define-sequence-traverser remove-if-not
1528     (predicate sequence &key from-end start end count key)
1529   #!+sb-doc
1530   "Return a copy of sequence with elements such that predicate(element)
1531    is null removed"
1532   (declare (fixnum start))
1533   (let ((end (or end length)))
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 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 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     (declare (fixnum end))
1920     (if (listp sequence)
1921         (if from-end
1922             (let ((length (length sequence)))
1923               (nreverse (nlist-substitute-if*
1924                          new pred (nreverse (the list sequence))
1925                          (- length end) (- length start) count key)))
1926             (nlist-substitute-if* new pred sequence
1927                                   start end count key))
1928         (if from-end
1929             (nvector-substitute-if* new pred sequence -1
1930                                     (1- end) (1- start) count key)
1931             (nvector-substitute-if* new pred sequence 1
1932                                     start end count key)))))
1933
1934 (defun nlist-substitute-if* (new test sequence start end count key)
1935   (declare (fixnum end))
1936   (do ((list (nthcdr start sequence) (cdr list))
1937        (index start (1+ index)))
1938       ((or (= index end) (null list) (= count 0)) sequence)
1939     (when (funcall test (apply-key key (car list)))
1940       (rplaca list new)
1941       (setq count (1- count)))))
1942
1943 (defun nvector-substitute-if* (new test sequence incrementer
1944                                start end count key)
1945   (do ((index start (+ index incrementer)))
1946       ((or (= index end) (= count 0)) sequence)
1947     (when (funcall test (apply-key key (aref sequence index)))
1948       (setf (aref sequence index) new)
1949       (setq count (1- count)))))
1950
1951 (define-sequence-traverser nsubstitute-if-not
1952     (new pred sequence &key from-end start end count key)
1953   #!+sb-doc
1954   "Return a sequence of the same kind as SEQUENCE with the same elements
1955    except that all elements not satisfying the TEST are replaced with NEW.
1956    SEQUENCE may be destructively modified. See manual for details."
1957   (declare (fixnum start))
1958   (let ((end (or end length)))
1959     (declare (fixnum end))
1960     (if (listp sequence)
1961         (if from-end
1962             (let ((length (length sequence)))
1963               (nreverse (nlist-substitute-if-not*
1964                          new pred (nreverse (the list sequence))
1965                          (- length end) (- length start) count key)))
1966             (nlist-substitute-if-not* new pred sequence
1967                                       start end count key))
1968         (if from-end
1969             (nvector-substitute-if-not* new pred sequence -1
1970                                         (1- end) (1- start) count key)
1971             (nvector-substitute-if-not* new pred sequence 1
1972                                         start end count key)))))
1973
1974 (defun nlist-substitute-if-not* (new test sequence start end count key)
1975   (declare (fixnum end))
1976   (do ((list (nthcdr start sequence) (cdr list))
1977        (index start (1+ index)))
1978       ((or (= index end) (null list) (= count 0)) sequence)
1979     (when (not (funcall test (apply-key key (car list))))
1980       (rplaca list new)
1981       (decf count))))
1982
1983 (defun nvector-substitute-if-not* (new test sequence incrementer
1984                                    start end count key)
1985   (do ((index start (+ index incrementer)))
1986       ((or (= index end) (= count 0)) sequence)
1987     (when (not (funcall test (apply-key key (aref sequence index))))
1988       (setf (aref sequence index) new)
1989       (decf count))))
1990 \f
1991 ;;;; FIND, POSITION, and their -IF and -IF-NOT variants
1992
1993 (defun effective-find-position-test (test test-not)
1994   (effective-find-position-test test test-not))
1995 (defun effective-find-position-key (key)
1996   (effective-find-position-key key))
1997
1998 ;;; shared guts of out-of-line FIND, POSITION, FIND-IF, and POSITION-IF
1999 (macrolet (;; shared logic for defining %FIND-POSITION and
2000            ;; %FIND-POSITION-IF in terms of various inlineable cases
2001            ;; of the expression defined in FROB and VECTOR*-FROB
2002            (frobs ()
2003              `(etypecase sequence-arg
2004                 (list (frob sequence-arg from-end))
2005                 (vector
2006                  (with-array-data ((sequence sequence-arg :offset-var offset)
2007                                    (start start)
2008                                    (end (%check-vector-sequence-bounds
2009                                          sequence-arg start end)))
2010                    (multiple-value-bind (f p)
2011                        (macrolet ((frob2 () '(if from-end
2012                                                  (frob sequence t)
2013                                                  (frob sequence nil))))
2014                          (typecase sequence
2015                            (simple-vector (frob2))
2016                            (simple-base-string (frob2))
2017                            (t (vector*-frob sequence))))
2018                      (declare (type (or index null) p))
2019                      (values f (and p (the index (- p offset))))))))))
2020   (defun %find-position (item sequence-arg from-end start end key test)
2021     (macrolet ((frob (sequence from-end)
2022                  `(%find-position item ,sequence
2023                                   ,from-end start end key test))
2024                (vector*-frob (sequence)
2025                  `(%find-position-vector-macro item ,sequence
2026                                                from-end start end key test)))
2027       (frobs)))
2028   (defun %find-position-if (predicate sequence-arg from-end start end key)
2029     (macrolet ((frob (sequence from-end)
2030                  `(%find-position-if predicate ,sequence
2031                                      ,from-end start end key))
2032                (vector*-frob (sequence)
2033                  `(%find-position-if-vector-macro predicate ,sequence
2034                                                   from-end start end key)))
2035       (frobs)))
2036   (defun %find-position-if-not (predicate sequence-arg from-end start end key)
2037     (macrolet ((frob (sequence from-end)
2038                  `(%find-position-if-not predicate ,sequence
2039                                          ,from-end start end key))
2040                (vector*-frob (sequence)
2041                  `(%find-position-if-not-vector-macro predicate ,sequence
2042                                                   from-end start end key)))
2043       (frobs))))
2044
2045 ;;; the user interface to FIND and POSITION: just interpreter stubs,
2046 ;;; nowadays.
2047 (defun find (item sequence &key from-end (start 0) end key test test-not)
2048   ;; FIXME: this can't be the way to go, surely?
2049   (find item sequence :from-end from-end :start start :end end :key key
2050         :test test :test-not test-not))
2051 (defun position (item sequence &key from-end (start 0) end key test test-not)
2052   (position item sequence :from-end from-end :start start :end end :key key
2053             :test test :test-not test-not))
2054
2055 ;;; the user interface to FIND-IF and POSITION-IF, entirely analogous
2056 ;;; to the interface to FIND and POSITION
2057 (defun find-if (predicate sequence &key from-end (start 0) end key)
2058   (find-if predicate sequence :from-end from-end :start start
2059            :end end :key key))
2060 (defun position-if (predicate sequence &key from-end (start 0) end key)
2061   (position-if predicate sequence :from-end from-end :start start
2062                :end end :key key))
2063
2064 (defun find-if-not (predicate sequence &key from-end (start 0) end key)
2065   (find-if-not predicate sequence :from-end from-end :start start
2066            :end end :key key))
2067 (defun position-if-not (predicate sequence &key from-end (start 0) end key)
2068   (position-if-not predicate sequence :from-end from-end :start start
2069                :end end :key key))
2070 \f
2071 ;;;; COUNT-IF, COUNT-IF-NOT, and COUNT
2072
2073 (eval-when (:compile-toplevel :execute)
2074
2075 (sb!xc:defmacro vector-count-if (notp from-end-p predicate sequence)
2076   (let ((next-index (if from-end-p '(1- index) '(1+ index)))
2077         (pred `(funcall ,predicate (apply-key key (aref ,sequence index)))))
2078     `(let ((%start ,(if from-end-p '(1- end) 'start))
2079            (%end ,(if from-end-p '(1- start) 'end)))
2080       (do ((index %start ,next-index)
2081            (count 0))
2082           ((= index (the fixnum %end)) count)
2083         (declare (fixnum index count))
2084         (,(if notp 'unless 'when) ,pred
2085           (setq count (1+ count)))))))
2086
2087 (sb!xc:defmacro list-count-if (notp from-end-p predicate sequence)
2088   (let ((pred `(funcall ,predicate (apply-key key (pop sequence)))))
2089     `(let ((%start ,(if from-end-p '(- length end) 'start))
2090            (%end ,(if from-end-p '(- length start) 'end))
2091            (sequence ,(if from-end-p '(reverse sequence) 'sequence)))
2092       (do ((sequence (nthcdr %start ,sequence))
2093            (index %start (1+ index))
2094            (count 0))
2095           ((or (= index (the fixnum %end)) (null sequence)) count)
2096         (declare (fixnum index count))
2097         (,(if notp 'unless 'when) ,pred
2098           (setq count (1+ count)))))))
2099
2100
2101 ) ; EVAL-WHEN
2102
2103 (define-sequence-traverser count-if (pred sequence &key from-end start end key)
2104   #!+sb-doc
2105   "Return the number of elements in SEQUENCE satisfying PRED(el)."
2106   (declare (fixnum start))
2107   (let ((end (or end length)))
2108     (declare (type index end))
2109     (seq-dispatch sequence
2110                   (if from-end
2111                       (list-count-if nil t pred sequence)
2112                       (list-count-if nil nil pred sequence))
2113                   (if from-end
2114                       (vector-count-if nil t pred sequence)
2115                       (vector-count-if nil nil pred sequence)))))
2116
2117 (define-sequence-traverser count-if-not
2118     (pred sequence &key from-end start end key)
2119   #!+sb-doc
2120   "Return the number of elements in SEQUENCE not satisfying TEST(el)."
2121   (declare (fixnum start))
2122   (let ((end (or end length)))
2123     (declare (type index end))
2124     (seq-dispatch sequence
2125                   (if from-end
2126                       (list-count-if t t pred sequence)
2127                       (list-count-if t nil pred sequence))
2128                   (if from-end
2129                       (vector-count-if t t pred sequence)
2130                       (vector-count-if t nil pred sequence)))))
2131
2132 (define-sequence-traverser count
2133     (item sequence &key from-end start end
2134           key (test #'eql test-p) (test-not nil test-not-p))
2135   #!+sb-doc
2136   "Return the number of elements in SEQUENCE satisfying a test with ITEM,
2137    which defaults to EQL."
2138   (declare (fixnum start))
2139   (when (and test-p test-not-p)
2140     ;; ANSI Common Lisp has left the behavior in this situation unspecified.
2141     ;; (CLHS 17.2.1)
2142     (error ":TEST and :TEST-NOT are both present."))
2143   (let ((end (or end length)))
2144     (declare (type index end))
2145     (let ((%test (if test-not-p
2146                      (lambda (x)
2147                        (not (funcall test-not item x)))
2148                      (lambda (x)
2149                        (funcall test item x)))))
2150       (seq-dispatch sequence
2151                     (if from-end
2152                         (list-count-if nil t %test sequence)
2153                         (list-count-if nil nil %test sequence))
2154                     (if from-end
2155                         (vector-count-if nil t %test sequence)
2156                         (vector-count-if nil nil %test sequence))))))
2157
2158
2159 \f
2160 ;;;; MISMATCH
2161
2162 (eval-when (:compile-toplevel :execute)
2163
2164 (sb!xc:defmacro match-vars (&rest body)
2165   `(let ((inc (if from-end -1 1))
2166          (start1 (if from-end (1- (the fixnum end1)) start1))
2167          (start2 (if from-end (1- (the fixnum end2)) start2))
2168          (end1 (if from-end (1- (the fixnum start1)) end1))
2169          (end2 (if from-end (1- (the fixnum start2)) end2)))
2170      (declare (fixnum inc start1 start2 end1 end2))
2171      ,@body))
2172
2173 (sb!xc:defmacro matchify-list ((sequence start length end) &body body)
2174   (declare (ignore end)) ;; ### Should END be used below?
2175   `(let ((,sequence (if from-end
2176                         (nthcdr (- (the fixnum ,length) (the fixnum ,start) 1)
2177                                 (reverse (the list ,sequence)))
2178                         (nthcdr ,start ,sequence))))
2179      (declare (type list ,sequence))
2180      ,@body))
2181
2182 ) ; EVAL-WHEN
2183
2184 (eval-when (:compile-toplevel :execute)
2185
2186 (sb!xc:defmacro if-mismatch (elt1 elt2)
2187   `(cond ((= (the fixnum index1) (the fixnum end1))
2188           (return (if (= (the fixnum index2) (the fixnum end2))
2189                       nil
2190                       (if from-end
2191                           (1+ (the fixnum index1))
2192                           (the fixnum index1)))))
2193          ((= (the fixnum index2) (the fixnum end2))
2194           (return (if from-end (1+ (the fixnum index1)) index1)))
2195          (test-not
2196           (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2197               (return (if from-end (1+ (the fixnum index1)) index1))))
2198          (t (if (not (funcall test (apply-key key ,elt1)
2199                               (apply-key key ,elt2)))
2200                 (return (if from-end (1+ (the fixnum index1)) index1))))))
2201
2202 (sb!xc:defmacro mumble-mumble-mismatch ()
2203   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2204         (index2 start2 (+ index2 (the fixnum inc))))
2205        (())
2206      (declare (fixnum index1 index2))
2207      (if-mismatch (aref sequence1 index1) (aref sequence2 index2))))
2208
2209 (sb!xc:defmacro mumble-list-mismatch ()
2210   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2211         (index2 start2 (+ index2 (the fixnum inc))))
2212        (())
2213      (declare (fixnum index1 index2))
2214      (if-mismatch (aref sequence1 index1) (pop sequence2))))
2215 \f
2216 (sb!xc:defmacro list-mumble-mismatch ()
2217   `(do ((index1 start1 (+ index1 (the fixnum inc)))
2218         (index2 start2 (+ index2 (the fixnum inc))))
2219        (())
2220      (declare (fixnum index1 index2))
2221      (if-mismatch (pop sequence1) (aref sequence2 index2))))
2222
2223 (sb!xc:defmacro list-list-mismatch ()
2224   `(do ((sequence1 sequence1)
2225         (sequence2 sequence2)
2226         (index1 start1 (+ index1 (the fixnum inc)))
2227         (index2 start2 (+ index2 (the fixnum inc))))
2228        (())
2229      (declare (fixnum index1 index2))
2230      (if-mismatch (pop sequence1) (pop sequence2))))
2231
2232 ) ; EVAL-WHEN
2233
2234 (define-sequence-traverser mismatch
2235     (sequence1 sequence2
2236                &key from-end test test-not
2237                start1 end1 start2 end2 key)
2238   #!+sb-doc
2239   "The specified subsequences of SEQUENCE1 and SEQUENCE2 are compared
2240    element-wise. If they are of equal length and match in every element, the
2241    result is NIL. Otherwise, the result is a non-negative integer, the index
2242    within SEQUENCE1 of the leftmost position at which they fail to match; or,
2243    if one is shorter than and a matching prefix of the other, the index within
2244    SEQUENCE1 beyond the last position tested is returned. If a non-NIL
2245    :FROM-END argument is given, then one plus the index of the rightmost
2246    position in which the sequences differ is returned."
2247   (declare (fixnum start1 start2))
2248   (let* ((end1 (or end1 length1))
2249          (end2 (or end2 length2)))
2250     (declare (type index end1 end2))
2251     (match-vars
2252      (seq-dispatch sequence1
2253        (matchify-list (sequence1 start1 length1 end1)
2254          (seq-dispatch sequence2
2255            (matchify-list (sequence2 start2 length2 end2)
2256              (list-list-mismatch))
2257            (list-mumble-mismatch)))
2258        (seq-dispatch sequence2
2259          (matchify-list (sequence2 start2 length2 end2)
2260            (mumble-list-mismatch))
2261          (mumble-mumble-mismatch))))))
2262 \f
2263 ;;; search comparison functions
2264
2265 (eval-when (:compile-toplevel :execute)
2266
2267 ;;; Compare two elements and return if they don't match.
2268 (sb!xc:defmacro compare-elements (elt1 elt2)
2269   `(if test-not
2270        (if (funcall test-not (apply-key key ,elt1) (apply-key key ,elt2))
2271            (return nil)
2272            t)
2273        (if (not (funcall test (apply-key key ,elt1) (apply-key key ,elt2)))
2274            (return nil)
2275            t)))
2276
2277 (sb!xc:defmacro search-compare-list-list (main sub)
2278   `(do ((main ,main (cdr main))
2279         (jndex start1 (1+ jndex))
2280         (sub (nthcdr start1 ,sub) (cdr sub)))
2281        ((or (endp main) (endp sub) (<= end1 jndex))
2282         t)
2283      (declare (type (integer 0) jndex))
2284      (compare-elements (car sub) (car main))))
2285
2286 (sb!xc:defmacro search-compare-list-vector (main sub)
2287   `(do ((main ,main (cdr main))
2288         (index start1 (1+ index)))
2289        ((or (endp main) (= index end1)) t)
2290      (compare-elements (aref ,sub index) (car main))))
2291
2292 (sb!xc:defmacro search-compare-vector-list (main sub index)
2293   `(do ((sub (nthcdr start1 ,sub) (cdr sub))
2294         (jndex start1 (1+ jndex))
2295         (index ,index (1+ index)))
2296        ((or (<= end1 jndex) (endp sub)) t)
2297      (declare (type (integer 0) jndex))
2298      (compare-elements (car sub) (aref ,main index))))
2299
2300 (sb!xc:defmacro search-compare-vector-vector (main sub index)
2301   `(do ((index ,index (1+ index))
2302         (sub-index start1 (1+ sub-index)))
2303        ((= sub-index end1) t)
2304      (compare-elements (aref ,sub sub-index) (aref ,main index))))
2305
2306 (sb!xc:defmacro search-compare (main-type main sub index)
2307   (if (eq main-type 'list)
2308       `(seq-dispatch ,sub
2309                      (search-compare-list-list ,main ,sub)
2310                      (search-compare-list-vector ,main ,sub))
2311       `(seq-dispatch ,sub
2312                      (search-compare-vector-list ,main ,sub ,index)
2313                      (search-compare-vector-vector ,main ,sub ,index))))
2314
2315 ) ; EVAL-WHEN
2316 \f
2317 ;;;; SEARCH
2318
2319 (eval-when (:compile-toplevel :execute)
2320
2321 (sb!xc:defmacro list-search (main sub)
2322   `(do ((main (nthcdr start2 ,main) (cdr main))
2323         (index2 start2 (1+ index2))
2324         (terminus (- end2 (the (integer 0) (- end1 start1))))
2325         (last-match ()))
2326        ((> index2 terminus) last-match)
2327      (declare (type (integer 0) index2))
2328      (if (search-compare list main ,sub index2)
2329          (if from-end
2330              (setq last-match index2)
2331              (return index2)))))
2332
2333 (sb!xc:defmacro vector-search (main sub)
2334   `(do ((index2 start2 (1+ index2))
2335         (terminus (- end2 (the (integer 0) (- end1 start1))))
2336         (last-match ()))
2337        ((> index2 terminus) last-match)
2338      (declare (type (integer 0) index2))
2339      (if (search-compare vector ,main ,sub index2)
2340          (if from-end
2341              (setq last-match index2)
2342              (return index2)))))
2343
2344 ) ; EVAL-WHEN
2345
2346 (define-sequence-traverser search
2347     (sequence1 sequence2
2348                &key from-end test test-not
2349                start1 end1 start2 end2 key)
2350   (declare (fixnum start1 start2))
2351   (let ((end1 (or end1 length1))
2352         (end2 (or end2 length2)))
2353     (seq-dispatch sequence2
2354                   (list-search sequence2 sequence1)
2355                   (vector-search sequence2 sequence1))))