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