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