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