Debian Codegraph @

src/lsp/loop.lsp

raw
1 ;;;; -*- Mode: Lisp; Syntax: Common-Lisp; indent-tabs-mode: nil; Package: SYSTEM -*-
2 ;;;; vim: set filetype=lisp tabstop=8 shiftwidth=2 expandtab:
3
4 ;;;;
5 ;;;>
6 ;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
7 ;;;> All Rights Reserved.
8 ;;;>
9 ;;;> Permission to use, copy, modify and distribute this software and its
10 ;;;> documentation for any purpose and without fee is hereby granted,
11 ;;;> provided that the M.I.T. copyright notice appear in all copies and that
12 ;;;> both that copyright notice and this permission notice appear in
13 ;;;> supporting documentation. The names "M.I.T." and "Massachusetts
14 ;;;> Institute of Technology" may not be used in advertising or publicity
15 ;;;> pertaining to distribution of the software without specific, written
16 ;;;> prior permission. Notice must be given in supporting documentation that
17 ;;;> copying distribution is by permission of M.I.T. M.I.T. makes no
18 ;;;> representations about the suitability of this software for any purpose.
19 ;;;> It is provided "as is" without express or implied warranty.
20 ;;;>
21 ;;;> Massachusetts Institute of Technology
22 ;;;> 77 Massachusetts Avenue
23 ;;;> Cambridge, Massachusetts 02139
24 ;;;> United States of America
25 ;;;> +1-617-253-1000
26 ;;;>
27 ;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
28 ;;;> All Rights Reserved.
29 ;;;>
30 ;;;> Permission to use, copy, modify and distribute this software and its
31 ;;;> documentation for any purpose and without fee is hereby granted,
32 ;;;> provided that the Symbolics copyright notice appear in all copies and
33 ;;;> that both that copyright notice and this permission notice appear in
34 ;;;> supporting documentation. The name "Symbolics" may not be used in
35 ;;;> advertising or publicity pertaining to distribution of the software
36 ;;;> without specific, written prior permission. Notice must be given in
37 ;;;> supporting documentation that copying distribution is by permission of
38 ;;;> Symbolics. Symbolics makes no representations about the suitability of
39 ;;;> this software for any purpose. It is provided "as is" without express
40 ;;;> or implied warranty.
41 ;;;>
42 ;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
43 ;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
44 ;;;>
45 ;;;> Symbolics, Inc.
46 ;;;> 8 New England Executive Park, East
47 ;;;> Burlington, Massachusetts 01803
48 ;;;> United States of America
49 ;;;> +1-617-221-1000
50
51 ;; $aclHeader: loop.cl,v 1.5 91/12/04 01:13:48 cox acl4_1 $
52
53 ;;;; LOOP Iteration Macro
54
55 #+ecl
56 (in-package "SI")
57
58 ;;; The design of this LOOP is intended to permit, using mostly the same
59 ;;; kernel of code, up to three different "loop" macros:
60 ;;;
61 ;;; (1) The unextended, unextensible ANSI standard LOOP;
62 ;;;
63 ;;; (2) A clean "superset" extension of the ANSI LOOP which provides
64 ;;; functionality similar to that of the old LOOP, but "in the style of"
65 ;;; the ANSI LOOP. For instance, user-definable iteration paths, with a
66 ;;; somewhat cleaned-up interface.
67 ;;;
68 ;;; (3) Extensions provided in another file which can make this LOOP
69 ;;; kernel behave largely compatibly with the Genera-vintage LOOP macro,
70 ;;; with only a small addition of code (instead of two whole, separate,
71 ;;; LOOP macros).
72 ;;;
73 ;;; Each of the above three LOOP variations can coexist in the same LISP
74 ;;; environment.
75 ;;;
76
77
78 ;;;; Miscellaneous Environment Things
79
80 (defmacro loop-unsafe (&rest x)
81 `(locally (declare (ext:assume-right-type)) ,@x))
82
83
84 ;;;; List Collection Macrology
85
86
87 (defmacro with-loop-list-collection-head ((head-var tail-var &optional user-head-var)
88 &body body)
89 (let ((l (and user-head-var (list (list user-head-var nil)))))
90 `(let* ((,head-var (list nil)) (,tail-var ,head-var) ,@l)
91 ,@body)))
92
93
94 (defmacro loop-collect-rplacd (&environment env
95 (head-var tail-var &optional user-head-var) form)
96 (setq form (macroexpand form env))
97 (flet ((cdr-wrap (form n)
98 (declare (fixnum n))
99 (do () ((<= n 4) (setq form `(,(case n
100 (1 'cdr)
101 (2 'cddr)
102 (3 'cdddr)
103 (4 'cddddr))
104 ,form)))
105 (setq form `(cddddr ,form) n (- n 4)))))
106 (let ((tail-form form) (ncdrs nil))
107 ;;Determine if the form being constructed is a list of known length.
108 (when (consp form)
109 (cond ((eq (car form) 'list)
110 (setq ncdrs (1- (length (cdr form)))))
111 ((member (car form) '(list* cons))
112 (when (and (cddr form) (member (car (last form)) '(nil 'nil)))
113 (setq ncdrs (- (length (cdr form)) 2))))))
114 (let ((answer
115 (cond ((null ncdrs)
116 `(when (setf (cdr ,tail-var) ,tail-form)
117 (setq ,tail-var (last (cdr ,tail-var)))))
118 ((< ncdrs 0) (return-from loop-collect-rplacd nil))
119 ((= ncdrs 0)
120 ;; Here we have a choice of two idioms:
121 ;; (rplacd tail (setq tail tail-form))
122 ;; (setq tail (setf (cdr tail) tail-form)).
123 ;;Genera and most others I have seen do better with the former.
124 `(rplacd ,tail-var (setq ,tail-var ,tail-form)))
125 (t `(setq ,tail-var ,(cdr-wrap `(setf (cdr ,tail-var) ,tail-form)
126 ncdrs))))))
127 ;;If not using locatives or something similar to update the user's
128 ;; head variable, we've got to set it... It's harmless to repeatedly set it
129 ;; unconditionally, and probably faster than checking.
130 (when user-head-var
131 (setq answer
132 `(progn ,answer
133 (setq ,user-head-var (cdr ,head-var)))))
134 answer))))
135
136
137 (defmacro loop-collect-answer (head-var &optional user-head-var)
138 (or user-head-var
139 `(cdr ,head-var)))
140
141
142 ;;;; Maximization Technology
143
144
145 #|
146 The basic idea of all this minimax randomness here is that we have to
147 have constructed all uses of maximize and minimize to a particular
148 "destination" before we can decide how to code them. The goal is to not
149 have to have any kinds of flags, by knowing both that (1) the type is
150 something which we can provide an initial minimum or maximum value for
151 and (2) know that a MAXIMIZE and MINIMIZE are not being combined.
152
153 SO, we have a datastructure which we annotate with all sorts of things,
154 incrementally updating it as we generate loop body code, and then use
155 a wrapper and internal macros to do the coding when the loop has been
156 constructed.
157 |#
158
159
160 (defstruct (loop-minimax
161 #+ecl (:type vector)
162 (:constructor make-loop-minimax-internal)
163 #+nil (:copier nil)
164 #+nil (:predicate nil))
165 answer-variable
166 type
167 temp-variable
168 flag-variable
169 operations
170 infinity-data)
171
172
173 (defparameter *loop-minimax-type-infinities-alist*
174 ;; This is the sort of value this should take on for a Lisp that has
175 ;; "eminently usable" infinities. n.b. there are neither constants nor
176 ;; printed representations for infinities defined by CL.
177 ;; This grotesque read-from-string below is to help implementations
178 ;; which croak on the infinity character when it appears in a token, even
179 ;; conditionalized out.
180 #|
181 '((fixnum most-positive-fixnum most-negative-fixnum)
182 (short-float ext:single-float-positive-infinity ext:single-float-negative-infinity)
183 (single-float ext:single-float-positive-infinity ext:single-float-negative-infinity)
184 (double-float ext:double-float-positive-infinity ext:double-float-negative-infinity)
185 (long-float ext:long-float-positive-infinity ext:long-float-negative-infinity))
186 |#
187 ;; If we don't know, then we cannot provide "infinite" initial values for any of the
188 ;; types but FIXNUM:
189 '((fixnum most-positive-fixnum most-negative-fixnum))
190 )
191
192
193 (defun make-loop-minimax (answer-variable type)
194 (declare (si::c-local))
195 (let ((infinity-data (cdr (assoc type *loop-minimax-type-infinities-alist* :test #'subtypep))))
196 (make-loop-minimax-internal
197 :answer-variable answer-variable
198 :type type
199 :temp-variable (gensym "LOOP-MAXMIN-TEMP-")
200 :flag-variable (and (not infinity-data) (gensym "LOOP-MAXMIN-FLAG-"))
201 :operations nil
202 :infinity-data infinity-data)))
203
204
205 (defun loop-note-minimax-operation (operation minimax)
206 (declare (si::c-local))
207 (pushnew (truly-the symbol operation) (loop-minimax-operations minimax))
208 (when (and (cdr (loop-minimax-operations minimax))
209 (not (loop-minimax-flag-variable minimax)))
210 (setf (loop-minimax-flag-variable minimax) (gensym "LOOP-MAXMIN-FLAG-")))
211 operation)
212
213
214 (defmacro with-minimax-value (lm &body body)
215 (let ((init (loop-typed-init (loop-minimax-type lm)))
216 (which (car (loop-minimax-operations lm)))
217 (infinity-data (loop-minimax-infinity-data lm))
218 (answer-var (loop-minimax-answer-variable lm))
219 (temp-var (loop-minimax-temp-variable lm))
220 (flag-var (loop-minimax-flag-variable lm))
221 (type (loop-minimax-type lm)))
222 (if flag-var
223 `(let ((,answer-var ,init) (,temp-var ,init) (,flag-var nil))
224 (declare (type ,type ,answer-var ,temp-var))
225 ,@body)
226 `(let ((,answer-var ,(if (eq which 'min) (first infinity-data) (second infinity-data)))
227 (,temp-var ,init))
228 (declare (type ,type ,answer-var ,temp-var))
229 ,@body))))
230
231
232 (defmacro loop-accumulate-minimax-value (lm operation form)
233 (let* ((answer-var (loop-minimax-answer-variable lm))
234 (temp-var (loop-minimax-temp-variable lm))
235 (flag-var (loop-minimax-flag-variable lm))
236 (test `(,(ecase operation
237 (min '<)
238 (max '>))
239 ,temp-var ,answer-var)))
240 `(progn
241 (setq ,temp-var ,form)
242 (when ,(if flag-var `(or (not ,flag-var) ,test) test)
243 (setq ,@(and flag-var `(,flag-var t))
244 ,answer-var ,temp-var)))))
245
246
247
248 ;;;; Loop Keyword Tables
249
250
251 #|
252 LOOP keyword tables are hash tables string keys and a test of EQUAL.
253
254 The actual descriptive/dispatch structure used by LOOP is called a "loop
255 universe" contains a few tables and parameterizations. The basic idea is
256 that we can provide a non-extensible ANSI-compatible loop environment,
257 an extensible ANSI-superset loop environment, and (for such environments
258 as CLOE) one which is "sufficiently close" to the old Genera-vintage
259 LOOP for use by old user programs without requiring all of the old LOOP
260 code to be loaded.
261 |#
262
263
264 ;;;; Token Hackery
265
266
267 ;;;Compare two "tokens". The first is the frob out of *LOOP-SOURCE-CODE*,
268 ;;; the second a symbol to check against.
269 (defun loop-tequal (x1 x2)
270 (declare (si::c-local))
271 (and (symbolp x1) (string= x1 x2)))
272
273
274 (defun loop-tassoc (kwd alist)
275 (declare (si::c-local))
276 (and (symbolp kwd) (assoc kwd alist :test #'string=)))
277
278
279 (defun loop-tmember (kwd list)
280 (declare (si::c-local))
281 (and (symbolp kwd) (member kwd list :test #'string=)))
282
283
284 (defun loop-lookup-keyword (loop-token table)
285 (declare (si::c-local))
286 (and (symbolp loop-token)
287 (values (gethash (symbol-name loop-token) table))))
288
289
290 (defmacro loop-store-table-data (symbol table datum)
291 `(setf (gethash (symbol-name ,symbol) ,table) ,datum))
292
293
294 (defstruct (loop-universe
295 #+ecl (:type vector)
296 #-ecl (:print-function print-loop-universe)
297 #+nil (:copier nil)
298 #+nil (:predicate nil))
299 keywords ;hash table, value = (fn-name . extra-data).
300 iteration-keywords ;hash table, value = (fn-name . extra-data).
301 for-keywords ;hash table, value = (fn-name . extra-data).
302 path-keywords ;hash table, value = (fn-name . extra-data).
303 type-symbols ;hash table of type SYMBOLS, test EQ, value = CL type specifier.
304 type-keywords ;hash table of type STRINGS, test EQUAL, value = CL type spec.
305 ansi ;NIL, T, or :EXTENDED.
306 implicit-for-required ;see loop-hack-iteration
307 )
308
309
310 #-ecl
311 (defun print-loop-universe (u stream level)
312 (declare (ignore level))
313 (let ((str (case (loop-universe-ansi u)
314 ((nil) "Non-ANSI")
315 ((t) "ANSI")
316 (:extended "Extended-ANSI")
317 (t (loop-universe-ansi u)))))
318 (format stream "#<~S ~A>" (type-of u) str)))
319
320
321 ;;;This is the "current" loop context in use when we are expanding a
322 ;;;loop. It gets bound on each invocation of LOOP.
323 (defvar *loop-universe*)
324
325
326 (defun make-standard-loop-universe (&key keywords for-keywords iteration-keywords path-keywords
327 type-keywords type-symbols ansi)
328 (declare (si::c-local))
329 (flet ((maketable (entries)
330 (let* ((size (length entries))
331 (ht (make-hash-table :size (if (< size 10) 10 size) :test #'equal)))
332 (dolist (x entries) (setf (gethash (symbol-name (car x)) ht) (cadr x)))
333 ht)))
334 (make-loop-universe
335 :keywords (maketable keywords)
336 :for-keywords (maketable for-keywords)
337 :iteration-keywords (maketable iteration-keywords)
338 :path-keywords (maketable path-keywords)
339 :ansi ansi
340 :implicit-for-required (not (null ansi))
341 :type-keywords (maketable type-keywords)
342 :type-symbols (let* ((size (length type-symbols))
343 (ht (make-hash-table :size (if (< size 10) 10 size) :test #'eq)))
344 (dolist (x type-symbols)
345 (if (atom x) (setf (gethash x ht) x) (setf (gethash (car x) ht) (cadr x))))
346 ht))))
347
348
349 ;;;; Setq Hackery
350
351
352 (defparameter *loop-destructuring-hooks*
353 nil
354 "If not NIL, this must be a list of two things:
355 a LET-like macro, and a SETQ-like macro, which perform LOOP-style destructuring.")
356
357
358 (defun loop-make-psetq (frobs)
359 (declare (si::c-local))
360 (and frobs
361 (loop-make-desetq
362 (list (car frobs)
363 (if (null (cddr frobs)) (cadr frobs)
364 `(prog1 ,(cadr frobs)
365 ,(loop-make-psetq (cddr frobs))))))))
366
367
368 (defun loop-make-desetq (var-val-pairs)
369 (declare (si::c-local))
370 (if (null var-val-pairs)
371 nil
372 (cons (if *loop-destructuring-hooks*
373 (cadr *loop-destructuring-hooks*)
374 'loop-really-desetq)
375 var-val-pairs)))
376
377
378 (defparameter *loop-desetq-temporary*
379 (make-symbol "LOOP-DESETQ-TEMP"))
380
381
382 (defmacro loop-really-desetq (&environment env &rest var-val-pairs)
383 (labels ((find-non-null (var)
384 ;; see if there's any non-null thing here
385 ;; recurse if the list element is itself a list
386 (do ((tail var)) ((not (consp tail)) tail)
387 (when (find-non-null (pop tail)) (return t))))
388 (loop-desetq-internal (var val &optional temp)
389 ;; if the value is declared 'unsafe', then the assignemnt
390 ;; is also unsafe.
391 (when (and (consp val)
392 (eq (first val) 'LOOP-UNSAFE))
393 (let ((forms (rest val)))
394 (setf forms (if (rest forms) `(progn ,@forms) (first forms)))
395 (return-from loop-desetq-internal
396 `((LOOP-UNSAFE ,@(loop-desetq-internal var forms))))))
397 ;; returns a list of actions to be performed
398 (typecase var
399 (null
400 (when (consp val)
401 ;; don't lose possible side-effects
402 (if (eq (car val) 'prog1)
403 ;; these can come from psetq or desetq below.
404 ;; throw away the value, keep the side-effects.
405 ;;Special case is for handling an expanded POP.
406 (mapcan #'(lambda (x)
407 (and (consp x)
408 (or (not (eq (car x) 'car))
409 (not (symbolp (cadr x)))
410 (not (symbolp (setq x (macroexpand x env)))))
411 (cons x nil)))
412 (cdr val))
413 `(,val))))
414 (cons
415 (let* ((car (car var))
416 (cdr (cdr var))
417 (car-non-null (find-non-null car))
418 (cdr-non-null (find-non-null cdr)))
419 (when (or car-non-null cdr-non-null)
420 (if cdr-non-null
421 (let* ((temp-p temp)
422 (temp (or temp *loop-desetq-temporary*))
423 (body `(,@(loop-desetq-internal car `(car ,temp))
424 (setq ,temp (cdr ,temp))
425 ,@(loop-desetq-internal cdr temp temp))))
426 (if temp-p
427 `(,@(unless (eq temp val)
428 `((setq ,temp ,val)))
429 ,@body)
430 `((let ((,temp ,val))
431 ,@body))))
432 ;; no cdring to do
433 (loop-desetq-internal car `(car ,val) temp)))))
434 (otherwise
435 (unless (eq var val)
436 `((setq ,var ,val)))))))
437 (do ((actions))
438 ((null var-val-pairs)
439 (if (null (cdr actions)) (car actions) `(progn ,@(nreverse actions))))
440 (setq actions (revappend
441 (loop-desetq-internal (pop var-val-pairs) (pop var-val-pairs))
442 actions)))))
443
444
445 ;;;; LOOP-local variables
446
447 ;;;This is the "current" pointer into the LOOP source code.
448 (defvar *loop-source-code*)
449
450
451 ;;;This is the pointer to the original, for things like NAMED that
452 ;;;insist on being in a particular position
453 (defvar *loop-original-source-code*)
454
455
456 ;;;This is *loop-source-code* as of the "last" clause. It is used
457 ;;;primarily for generating error messages (see loop-error, loop-warn).
458 (defvar *loop-source-context*)
459
460
461 ;;;List of names for the LOOP, supplied by the NAMED clause.
462 (defvar *loop-names*)
463
464 ;;;The macroexpansion environment given to the macro.
465 (defvar *loop-macro-environment*)
466
467 ;;;This holds variable names specified with the USING clause.
468 ;;; See LOOP-NAMED-VARIABLE.
469 (defvar *loop-named-variables*)
470
471 ;;; LETlist-like list being accumulated for one group of parallel bindings.
472 (defvar *loop-variables*)
473
474 ;;;List of declarations being accumulated in parallel with
475 ;;;*loop-variables*.
476 (defvar *loop-declarations*)
477
478 ;;;Used by LOOP for destructuring binding, if it is doing that itself.
479 ;;; See loop-make-variable.
480 (defvar *loop-desetq-crocks*)
481
482 ;;; List of wrapping forms, innermost first, which go immediately inside
483 ;;; the current set of parallel bindings being accumulated in
484 ;;; *loop-variables*. The wrappers are appended onto a body. E.g.,
485 ;;; this list could conceivably has as its value ((with-open-file (g0001
486 ;;; g0002 ...))), with g0002 being one of the bindings in
487 ;;; *loop-variables* (this is why the wrappers go inside of the variable
488 ;;; bindings).
489 (defvar *loop-wrappers*)
490
491 ;;;This accumulates lists of previous values of *loop-variables* and the
492 ;;;other lists above, for each new nesting of bindings. See
493 ;;;loop-bind-block.
494 (defvar *loop-bind-stack*)
495
496 ;;;This is a LOOP-global variable for the (obsolete) NODECLARE clause
497 ;;;which inhibits LOOP from actually outputting a type declaration for
498 ;;;an iteration (or any) variable.
499 (defvar *loop-nodeclare*)
500
501 ;;;This is simply a list of LOOP iteration variables, used for checking
502 ;;;for duplications.
503 (defvar *loop-iteration-variables*)
504
505
506 ;;;List of prologue forms of the loop, accumulated in reverse order.
507 (defvar *loop-prologue*)
508
509 (defvar *loop-before-loop*)
510 (defvar *loop-body*)
511 (defvar *loop-after-body*)
512
513 ;;;This is T if we have emitted any body code, so that iteration driving
514 ;;;clauses can be disallowed. This is not strictly the same as
515 ;;;checking *loop-body*, because we permit some clauses such as RETURN
516 ;;;to not be considered "real" body (so as to permit the user to "code"
517 ;;;an abnormal return value "in loop").
518 (defvar *loop-emitted-body*)
519
520
521 ;;;List of epilogue forms (supplied by FINALLY generally), accumulated
522 ;;; in reverse order.
523 (defvar *loop-epilogue*)
524
525 ;;;List of epilogue forms which are supplied after the above "user"
526 ;;;epilogue. "normal" termination return values are provide by putting
527 ;;;the return form in here. Normally this is done using
528 ;;;loop-emit-final-value, q.v.
529 (defvar *loop-after-epilogue*)
530
531 ;;;The "culprit" responsible for supplying a final value from the loop.
532 ;;;This is so loop-emit-final-value can moan about multiple return
533 ;;;values being supplied.
534 (defvar *loop-final-value-culprit*)
535
536 ;;;If not NIL, we are in some branch of a conditional. Some clauses may
537 ;;;be disallowed.
538 (defvar *loop-inside-conditional*)
539
540 ;;;If not NIL, this is a temporary bound around the loop for holding the
541 ;;;temporary value for "it" in things like "when (f) collect it". It
542 ;;;may be used as a supertemporary by some other things.
543 (defvar *loop-when-it-variable*)
544
545 ;;;Sometimes we decide we need to fold together parts of the loop, but
546 ;;;some part of the generated iteration code is different for the first
547 ;;;and remaining iterations. This variable will be the temporary which
548 ;;;is the flag used in the loop to tell whether we are in the first or
549 ;;;remaining iterations.
550 (defvar *loop-never-stepped-variable*)
551
552 ;;;List of all the value-accumulation descriptor structures in the loop.
553 ;;; See loop-get-collection-info.
554 (defvar *loop-collection-cruft*) ; for multiple COLLECTs (etc)
555
556
557 ;;;; Code Analysis Stuff
558
559
560 (defun loop-constant-fold-if-possible (form &optional expected-type)
561 (declare (si::c-local))
562 (let ((new-form form) (constantp nil) (constant-value nil))
563 (when (setq constantp (constantp new-form))
564 (setq constant-value (eval new-form)))
565 (when (and constantp expected-type)
566 (unless (typep constant-value expected-type)
567 (loop-warn "The form ~S evaluated to ~S, which was not of the anticipated type ~S."
568 form constant-value expected-type)
569 (setq constantp nil constant-value nil)))
570 (values new-form constantp constant-value)))
571
572
573 ;;;; LOOP Iteration Optimization
574
575 (defparameter *loop-duplicate-code*
576 nil)
577
578
579 (defparameter *loop-iteration-flag-variable*
580 (make-symbol "LOOP-NOT-FIRST-TIME"))
581
582
583 (defmacro loop-body (&environment env
584 prologue
585 before-loop
586 main-body
587 after-loop
588 epilogue)
589 (declare (ignore env))
590 (unless (= (length before-loop) (length after-loop))
591 (error "LOOP-BODY called with non-synched before- and after-loop lists."))
592 ;;All our work is done from these copies, working backwards from the end:
593 (let ((rbefore (reverse before-loop))
594 (rafter (reverse after-loop)))
595 ;; Go backwards from the ends of before-loop and after-loop
596 ;; merging all the equivalent forms into the body.
597 (do ()
598 ((or (null rbefore)
599 (not (equal (car rbefore) (car rafter)))))
600 (push (pop rbefore) main-body)
601 (pop rafter))
602 `(tagbody
603 ,@(remove nil prologue)
604 ,@(nreverse (remove nil rbefore))
605 next-loop
606 ,@(remove nil main-body)
607 ,@(nreverse (remove nil rafter))
608 (go next-loop)
609 end-loop
610 ,@(remove nil epilogue))))
611
612 ;;;; Loop Errors
613
614
615 (defun loop-context ()
616 (declare (si::c-local))
617 (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
618 ((eq l (cdr *loop-source-code*)) (nreverse new))))
619
620
621 (defun loop-error (format-string &rest format-args)
622 (declare (si::c-local))
623 (si::simple-program-error "~?~%Current LOOP context:~{ ~S~}."
624 format-string format-args (loop-context)))
625
626
627 (defun loop-warn (format-string &rest format-args)
628 (declare (si::c-local))
629 (warn 'sys::simple-style-warning
630 :format-control "~?~%Current LOOP context:~{ ~S~}."
631 :format-arguments (list format-string format-args (loop-context))))
632
633
634 (defun loop-check-data-type (specified-type required-type
635 &optional (default-type required-type))
636 (declare (si::c-local))
637 (if (null specified-type)
638 default-type
639 (multiple-value-bind (a b) (subtypep specified-type required-type)
640 (cond ((not b)
641 (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
642 specified-type required-type))
643 ((not a)
644 (loop-error "Specified data type ~S is not a subtype of ~S."
645 specified-type required-type)))
646 specified-type)))
647
648
649 ;;;INTERFACE: Traditional, ANSI, Lucid.
650 (defmacro loop-finish ()
651 "Causes the iteration to terminate \"normally\", the same as implicit
652 termination by an iteration driving clause, or by use of WHILE or
653 UNTIL -- the epilogue code (if any) will be run, and any implicitly
654 collected result will be returned as the value of the LOOP."
655 '(go end-loop))
656
657 (defun subst-gensyms-for-nil (tree)
658 (declare (special *ignores*))
659 (cond
660 ((null tree) (car (push (gensym) *ignores*)))
661 ((atom tree) tree)
662 ((atom (cdr tree))
663 (cons (subst-gensyms-for-nil (car tree))
664 (subst-gensyms-for-nil (cdr tree))))
665 (t
666 (do* ((acc (cons '&optional nil))
667 (acc-last acc)
668 (elt tree (cdr elt)))
669 ((atom elt)
670 (setf (cdr acc-last) elt)
671 acc)
672 (setf (cdr acc-last)
673 (cons (subst-gensyms-for-nil (car elt)) nil))
674 (setf acc-last (cdr acc-last))))))
675
676 (defun loop-build-destructuring-bindings (crocks forms)
677 (if crocks
678 (let ((*ignores* ()))
679 (declare (special *ignores*))
680 `((destructuring-bind ,(subst-gensyms-for-nil (car crocks))
681 ,(cadr crocks)
682 (declare (ignore ,@*ignores*))
683 ,@(loop-build-destructuring-bindings (cddr crocks) forms))))
684 forms))
685
686 (defun loop-translate (*loop-source-code* *loop-macro-environment* *loop-universe*)
687 (declare (si::c-local))
688 (let ((*loop-original-source-code* *loop-source-code*)
689 (*loop-source-context* nil)
690 (*loop-iteration-variables* nil)
691 (*loop-variables* nil)
692 (*loop-nodeclare* nil)
693 (*loop-named-variables* nil)
694 (*loop-declarations* nil)
695 (*loop-desetq-crocks* nil)
696 (*loop-bind-stack* nil)
697 (*loop-prologue* nil)
698 (*loop-wrappers* nil)
699 (*loop-before-loop* nil)
700 (*loop-body* nil)
701 (*loop-emitted-body* nil)
702 (*loop-after-body* nil)
703 (*loop-epilogue* nil)
704 (*loop-after-epilogue* nil)
705 (*loop-final-value-culprit* nil)
706 (*loop-inside-conditional* nil)
707 (*loop-when-it-variable* nil)
708 (*loop-never-stepped-variable* nil)
709 (*loop-names* nil)
710 (*loop-collection-cruft* nil))
711 (loop-iteration-driver)
712 (loop-bind-block)
713 (let ((answer `(loop-body
714 ,(nreverse *loop-prologue*)
715 ,(nreverse *loop-before-loop*)
716 ,(nreverse *loop-body*)
717 ,(nreverse *loop-after-body*)
718 ,(nreconc *loop-epilogue* (nreverse *loop-after-epilogue*)))))
719 (dolist (entry *loop-bind-stack*)
720 (let ((vars (first entry))
721 (dcls (second entry))
722 (crocks (third entry))
723 (wrappers (fourth entry)))
724 (dolist (w wrappers)
725 (setq answer (append w (list answer))))
726 (when (or vars dcls crocks)
727 (let ((forms (list answer)))
728 ;;(when crocks (push crocks forms))
729 (when dcls (push `(declare ,@dcls) forms))
730 (setq answer `(,(cond ((not vars) 'locally)
731 (*loop-destructuring-hooks* (first *loop-destructuring-hooks*))
732 (t 'let))
733 ,vars
734 ,@(loop-build-destructuring-bindings crocks forms)))))))
735 (if *loop-names*
736 (do () ((null (car *loop-names*)) answer)
737 (setq answer `(block ,(pop *loop-names*) ,answer)))
738 `(block nil ,answer)))))
739
740
741 (defun loop-iteration-driver ()
742 (declare (si::c-local))
743 (do () ((null *loop-source-code*))
744 (let ((keyword (car *loop-source-code*)) (tem nil))
745 (cond ((not (symbolp keyword))
746 (loop-error "~S found where LOOP keyword expected." keyword))
747 (t (setq *loop-source-context* *loop-source-code*)
748 (loop-pop-source)
749 (cond ((setq tem (loop-lookup-keyword keyword (loop-universe-keywords *loop-universe*)))
750 ;;It's a "miscellaneous" toplevel LOOP keyword (do, collect, named, etc.)
751 (apply (symbol-function (first tem)) (rest tem)))
752 ((setq tem (loop-lookup-keyword keyword (loop-universe-iteration-keywords *loop-universe*)))
753 (loop-hack-iteration tem))
754 ((loop-tmember keyword '(and else))
755 ;; Alternative is to ignore it, ie let it go around to the next keyword...
756 (loop-error "Secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
757 keyword (car *loop-source-code*) (cadr *loop-source-code*)))
758 (t (loop-error "~S is an unknown keyword in LOOP macro." keyword))))))))
759
760
761
762 (defun loop-pop-source ()
763 (declare (si::c-local))
764 (if *loop-source-code*
765 (pop *loop-source-code*)
766 (loop-error "LOOP source code ran out when another token was expected.")))
767
768
769 (defun loop-get-compound-form ()
770 (declare (si::c-local))
771 (let ((form (loop-get-form)))
772 (unless (consp form)
773 (loop-error "Compound form expected, but found ~A." form))
774 form))
775
776 (defun loop-get-progn ()
777 (declare (si::c-local))
778 (do ((forms (list (loop-get-compound-form))
779 (cons (loop-get-compound-form) forms))
780 (nextform (car *loop-source-code*)
781 (car *loop-source-code*)))
782 ((atom nextform)
783 (if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
784
785
786 (defun loop-get-form ()
787 (declare (si::c-local))
788 (if *loop-source-code*
789 (loop-pop-source)
790 (loop-error "LOOP code ran out where a form was expected.")))
791
792
793 (defun loop-construct-return (form)
794 (declare (si::c-local))
795 `(return-from ,(car *loop-names*) ,form))
796
797 (defun loop-pseudo-body (form)
798 (declare (si::c-local))
799 (cond ((or *loop-emitted-body* *loop-inside-conditional*)
800 (push form *loop-body*))
801 (t (push form *loop-before-loop*) (push form *loop-after-body*))))
802
803 (defun loop-emit-body (form)
804 (declare (si::c-local))
805 (setq *loop-emitted-body* t)
806 (push form *loop-body*))
807
808 (defun loop-emit-final-value (&optional (form nil form-supplied-p))
809 (declare (si::c-local))
810 (when form-supplied-p
811 (push (loop-construct-return form) *loop-after-epilogue*))
812 (when *loop-final-value-culprit*
813 (loop-warn "LOOP clause is providing a value for the iteration,~@
814 however one was already established by a ~S clause."
815 *loop-final-value-culprit*))
816 (setq *loop-final-value-culprit* (car *loop-source-context*)))
817
818
819 (defun loop-disallow-conditional (&optional kwd)
820 (declare (si::c-local))
821 (when *loop-inside-conditional*
822 (loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
823
824 (defun loop-disallow-anonymous-collectors ()
825 (when (find-if-not 'loop-collector-name *loop-collection-cruft*)
826 (loop-error "This LOOP clause is not permitted with anonymous collectors.")))
827
828 (defun loop-disallow-aggregate-booleans ()
829 (when (loop-tmember *loop-final-value-culprit* '(always never thereis))
830 (loop-error "This anonymous collection LOOP clause is not permitted with aggregate booleans.")))
831
832
833
834 ;;;; Loop Types
835
836
837 (defun loop-typed-init (data-type)
838 (declare (si::c-local))
839 (cond ((null data-type)
840 nil)
841 ((subtypep data-type 'character)
842 #\0)
843 ((not (subtypep data-type 'number))
844 nil)
845 ((subtypep data-type '(or float (complex float)))
846 (coerce 0 data-type))
847 (t
848 0)))
849
850 (defun loop-optional-type (&optional variable)
851 (declare (si::c-local))
852 ;;No variable specified implies that no destructuring is permissible.
853 (and *loop-source-code* ;Don't get confused by NILs...
854 (let ((z (car *loop-source-code*)))
855 (cond ((loop-tequal z 'of-type)
856 ;;This is the syntactically unambigous form in that the form of the
857 ;; type specifier does not matter. Also, it is assumed that the
858 ;; type specifier is unambiguously, and without need of translation,
859 ;; a common lisp type specifier or pattern (matching the variable) thereof.
860 (loop-pop-source)
861 (loop-pop-source))
862
863 ((symbolp z)
864 ;;This is the (sort of) "old" syntax, even though we didn't used to support all of
865 ;; these type symbols.
866 (let ((type-spec (or (gethash z (loop-universe-type-symbols *loop-universe*))
867 (gethash (symbol-name z) (loop-universe-type-keywords *loop-universe*)))))
868 (when type-spec
869 (loop-pop-source)
870 type-spec)))
871 (t
872 ;;This is our sort-of old syntax. But this is only valid for when we are destructuring,
873 ;; so we will be compulsive (should we really be?) and require that we in fact be
874 ;; doing variable destructuring here. We must translate the old keyword pattern typespec
875 ;; into a fully-specified pattern of real type specifiers here.
876 (if (consp variable)
877 (unless (consp z)
878 (loop-error
879 "~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected."
880 z))
881 (loop-error "~S found where a LOOP keyword or LOOP type keyword expected." z))
882 (loop-pop-source)
883 (labels ((translate (k v)
884 (cond ((null k) nil)
885 ((atom k)
886 (replicate
887 (or (gethash k (loop-universe-type-symbols *loop-universe*))
888 (gethash (symbol-name k) (loop-universe-type-keywords *loop-universe*))
889 (loop-error
890 "Destructuring type pattern ~S contains unrecognized type keyword ~S."
891 z k))
892 v))
893 ((atom v)
894 (loop-error
895 "Destructuring type pattern ~S doesn't match variable pattern ~S."
896 z variable))
897 (t (cons (translate (car k) (car v)) (translate (cdr k) (cdr v))))))
898 (replicate (typ v)
899 (if (atom v) typ (cons (replicate typ (car v)) (replicate typ (cdr v))))))
900 (translate z variable)))))))
901
902
903
904 ;;;; Loop Variables
905
906
907 (defun loop-bind-block ()
908 (declare (si::c-local))
909 (when (or *loop-variables* *loop-declarations* *loop-wrappers*)
910 (push (list (nreverse *loop-variables*) *loop-declarations* *loop-desetq-crocks* *loop-wrappers*)
911 *loop-bind-stack*)
912 (setq *loop-variables* nil
913 *loop-declarations* nil
914 *loop-desetq-crocks* nil
915 *loop-wrappers* nil)))
916
917 (defun loop-variable-p (name)
918 (do ((entry *loop-bind-stack* (cdr entry))) (nil)
919 (cond ((null entry)
920 (return nil))
921 ((assoc name (caar entry) :test #'eq)
922 (return t)))))
923
924 (defun loop-make-variable (name initialization dtype &optional iteration-variable-p)
925 (declare (si::c-local))
926 (cond ((null name)
927 (cond ((not (null initialization))
928 (push (list (setq name (gensym "LOOP-IGNORE-"))
929 initialization)
930 *loop-variables*)
931 (push `(ignore ,name) *loop-declarations*))))
932 ((atom name)
933 (cond (iteration-variable-p
934 (if (member name *loop-iteration-variables*)
935 (loop-error "Duplicated LOOP iteration variable ~S." name)
936 (push name *loop-iteration-variables*)))
937 ((assoc name *loop-variables*)
938 (loop-error "Duplicated variable ~S in LOOP parallel binding." name)))
939 (unless (symbolp name)
940 (loop-error "Bad variable ~S somewhere in LOOP." name))
941 (let ((init (or initialization (loop-typed-init dtype))))
942 (loop-declare-variable name dtype init)
943 ;; We use ASSOC on this list to check for duplications (above),
944 ;; so don't optimize out this list:
945 (push (list name init) *loop-variables*)))
946 (initialization
947 (cond (*loop-destructuring-hooks*
948 (loop-declare-variable name dtype)
949 (push (list name initialization) *loop-variables*))
950 (t (let ((newvar (gensym "LOOP-DESTRUCTURE-")))
951 (loop-declare-variable name dtype)
952 (push (list newvar initialization) *loop-variables*)
953 ;; *LOOP-DESETQ-CROCKS* gathered in reverse order.
954 (setq *loop-desetq-crocks*
955 (list* name newvar *loop-desetq-crocks*))
956 #+ignore
957 (loop-make-variable name nil dtype iteration-variable-p)))))
958 (t (let ((tcar nil) (tcdr nil))
959 (if (atom dtype) (setq tcar (setq tcdr dtype))
960 (setq tcar (car dtype) tcdr (cdr dtype)))
961 (loop-make-variable (car name) nil tcar iteration-variable-p)
962 (loop-make-variable (cdr name) nil tcdr iteration-variable-p))))
963 name)
964
965
966 (defun loop-make-iteration-variable (name initialization dtype)
967 (declare (si::c-local))
968 (loop-make-variable name initialization dtype t))
969
970
971 (defun loop-declare-variable (name dtype &optional (initialization nil initialization-p))
972 (declare (si::c-local))
973 (cond ((or (null name) (null dtype) (eq dtype t)) nil)
974 ((symbolp name)
975 (unless (or (eq dtype t) (member (truly-the symbol name) *loop-nodeclare*))
976 (when (and initialization-p (constantp initialization))
977 (let ((init-type (type-of initialization)))
978 (unless (subtypep init-type dtype)
979 (setf dtype `(or ,dtype ,init-type)))))
980 ;; Allow redeclaration of a variable. This can be used by
981 ;; the loop constructors to make the type more and more
982 ;; precise as we add keywords
983 (let ((previous (find name *loop-declarations*
984 :key #'(lambda (d)
985 (and (consp d)
986 (= (length d) 3)
987 (eq (cons-car d) 'type)
988 (third d))))))
989 (if previous
990 (setf (second previous) dtype)
991 (push `(type ,dtype ,name) *loop-declarations*)))))
992 ((consp name)
993 ;; to be on the safe side, we always assume that
994 ;; destructuring variable bindings initialize to nil
995 (cond ((consp dtype)
996 (loop-declare-variable (car name) (car dtype) nil)
997 (loop-declare-variable (cdr name) (cdr dtype)))
998 (t (loop-declare-variable (car name) dtype nil)
999 (loop-declare-variable (cdr name) dtype))))
1000 (t (error "Invalid LOOP variable passed in: ~S." name))))
1001
1002
1003 (defun loop-maybe-bind-form (form data-type)
1004 (declare (si::c-local))
1005 (if (constantp form *loop-macro-environment*)
1006 form
1007 (loop-make-variable (gensym "LOOP-BIND-") form data-type)))
1008
1009
1010
1011 (defun loop-do-if (for negatep)
1012 (let ((form (loop-get-form))
1013 (*loop-inside-conditional* t)
1014 (it-p nil)
1015 (first-clause-p t))
1016 (flet ((get-clause (for)
1017 (do ((body nil)) (nil)
1018 (let ((key (car *loop-source-code*)) (*loop-body* nil) data)
1019 (cond ((not (symbolp key))
1020 (loop-error
1021 "~S found where keyword expected getting LOOP clause after ~S."
1022 key for))
1023 (t (setq *loop-source-context* *loop-source-code*)
1024 (loop-pop-source)
1025 (when (and (loop-tequal (car *loop-source-code*) 'it)
1026 first-clause-p)
1027 (setq *loop-source-code*
1028 (cons (or it-p (setq it-p (loop-when-it-variable)))
1029 (cdr *loop-source-code*))))
1030 (cond ((or (not (setq data (loop-lookup-keyword
1031 key (loop-universe-keywords *loop-universe*))))
1032 (progn (apply (symbol-function (car data)) (cdr data))
1033 (null *loop-body*)))
1034 (loop-error
1035 "~S does not introduce a LOOP clause that can follow ~S."
1036 key for))
1037 (t (setq body (nreconc *loop-body* body)))))))
1038 (setq first-clause-p nil)
1039 (if (loop-tequal (car *loop-source-code*) :and)
1040 (loop-pop-source)
1041 (return (if (cdr body) `(progn ,@(nreverse body)) (car body)))))))
1042 (let ((then (get-clause for))
1043 (else (when (loop-tequal (car *loop-source-code*) :else)
1044 (loop-pop-source)
1045 (list (get-clause :else)))))
1046 (when (loop-tequal (car *loop-source-code*) :end)
1047 (loop-pop-source))
1048 (when it-p (setq form `(setq ,it-p ,form)))
1049 (loop-pseudo-body
1050 `(if ,(if negatep `(not ,form) form)
1051 ,then
1052 ,@else))))))
1053
1054
1055 (defun loop-do-initially ()
1056 (loop-disallow-conditional :initially)
1057 (push (loop-get-progn) *loop-prologue*))
1058
1059 (defun loop-do-finally ()
1060 (loop-disallow-conditional :finally)
1061 (push (loop-get-progn) *loop-epilogue*))
1062
1063 (defun loop-do-do ()
1064 (loop-emit-body (loop-get-progn)))
1065
1066 (defun loop-do-named ()
1067 (let ((name (loop-pop-source)))
1068 (unless (symbolp name)
1069 (loop-error "~S is an invalid name for your LOOP." name))
1070 (when (or *loop-before-loop* *loop-body* *loop-after-epilogue* *loop-inside-conditional*)
1071 (loop-error "The NAMED ~S clause occurs too late." name))
1072 (when *loop-names*
1073 (loop-error "You may only use one NAMED clause in your loop: NAMED ~S ... NAMED ~S."
1074 (car *loop-names*) name))
1075 (setq *loop-names* (list name nil))))
1076
1077 (defun loop-do-return ()
1078 (loop-emit-body (loop-construct-return (loop-get-form))))
1079
1080
1081 ;;;; Value Accumulation: List
1082
1083
1084 (defstruct (loop-collector
1085 #+ecl (:type vector)
1086 #+nil (:copier nil)
1087 #+nil (:predicate nil))
1088 name
1089 class
1090 (history nil)
1091 (tempvars nil)
1092 dtype
1093 (data nil)) ;collector-specific data
1094
1095
1096 (defun loop-get-collection-info (collector class default-type)
1097 (declare (si::c-local))
1098 (let ((form (loop-get-form))
1099 (dtype (and (not (loop-universe-ansi *loop-universe*)) (loop-optional-type)))
1100 (name (when (loop-tequal (car *loop-source-code*) 'into)
1101 (loop-pop-source)
1102 (loop-pop-source))))
1103 (when (not (symbolp name))
1104 (loop-error "Value accumulation recipient name, ~S, is not a symbol." name))
1105 (unless name
1106 (loop-disallow-aggregate-booleans))
1107 (unless dtype
1108 (setq dtype (or (loop-optional-type) default-type)))
1109 (let ((cruft (find (truly-the symbol name) *loop-collection-cruft*
1110 :key #'loop-collector-name)))
1111 (cond ((not cruft)
1112 (when (and name (loop-variable-p name))
1113 (loop-error "Variable ~S cannot be used in INTO clause" name))
1114 (push (setq cruft (make-loop-collector
1115 :name name :class class
1116 :history (list collector) :dtype dtype))
1117 *loop-collection-cruft*))
1118 (t (unless (eq (loop-collector-class cruft) class)
1119 (loop-error
1120 "Incompatible kinds of LOOP value accumulation specified for collecting~@
1121 ~:[as the value of the LOOP~;~:*INTO ~S~]: ~S and ~S."
1122 name (car (loop-collector-history cruft)) collector))
1123 (unless (equal dtype (loop-collector-dtype cruft))
1124 (loop-warn
1125 "Unequal datatypes specified in different LOOP value accumulations~@
1126 into ~S: ~S and ~S."
1127 name dtype (loop-collector-dtype cruft))
1128 (when (eq (loop-collector-dtype cruft) t)
1129 (setf (loop-collector-dtype cruft) dtype)))
1130 (push collector (loop-collector-history cruft))))
1131 (values cruft form))))
1132
1133
1134 (defun loop-list-collection (specifically) ;NCONC, LIST, or APPEND
1135 (multiple-value-bind (lc form) (loop-get-collection-info specifically 'list 'list)
1136 (let ((tempvars (loop-collector-tempvars lc)))
1137 (unless tempvars
1138 (setf (loop-collector-tempvars lc)
1139 (setq tempvars (list* (gensym "LOOP-LIST-HEAD")
1140 (gensym "LOOP-LIST-TAIL")
1141 (and (loop-collector-name lc)
1142 (list (loop-collector-name lc))))))
1143 (push `(with-loop-list-collection-head ,tempvars) *loop-wrappers*)
1144 (unless (loop-collector-name lc)
1145 (loop-emit-final-value `(loop-collect-answer ,(car tempvars) ,@(cddr tempvars)))))
1146 (ecase specifically
1147 (list (setq form `(list ,form)))
1148 (nconc nil)
1149 (append (unless (and (consp form) (eq (car form) 'list))
1150 (setq form `(copy-list ,form)))))
1151 (loop-emit-body `(loop-collect-rplacd ,tempvars ,form)))))
1152
1153
1154 ;;;; Value Accumulation: max, min, sum, count.
1155
1156
1157
1158 (defun loop-sum-collection (specifically required-type default-type) ;SUM, COUNT
1159 (multiple-value-bind (lc form)
1160 (loop-get-collection-info specifically 'sum default-type)
1161 (loop-check-data-type (loop-collector-dtype lc) required-type)
1162 (let ((tempvars (loop-collector-tempvars lc)))
1163 (unless tempvars
1164 (setf (loop-collector-tempvars lc)
1165 (setq tempvars (list (loop-make-variable
1166 (or (loop-collector-name lc)
1167 (gensym "LOOP-SUM-"))
1168 nil (loop-collector-dtype lc)))))
1169 (unless (loop-collector-name lc)
1170 (loop-emit-final-value (car (loop-collector-tempvars lc)))))
1171 (loop-emit-body
1172 (if (eq specifically 'count)
1173 `(when ,form
1174 (setq ,(car tempvars)
1175 (1+ ,(car tempvars))))
1176 `(setq ,(car tempvars)
1177 (+ ,(car tempvars)
1178 ,form)))))))
1179
1180
1181
1182 (defun loop-maxmin-collection (specifically)
1183 (multiple-value-bind (lc form)
1184 (loop-get-collection-info specifically 'maxmin 'real)
1185 (loop-check-data-type (loop-collector-dtype lc) 'real)
1186 (let ((data (loop-collector-data lc)))
1187 (unless data
1188 (setf (loop-collector-data lc)
1189 (setq data (make-loop-minimax
1190 (or (loop-collector-name lc) (gensym "LOOP-MAXMIN-"))
1191 (loop-collector-dtype lc))))
1192 (unless (loop-collector-name lc)
1193 (loop-emit-final-value (loop-minimax-answer-variable data))))
1194 (loop-note-minimax-operation specifically data)
1195 (push `(with-minimax-value ,data) *loop-wrappers*)
1196 (loop-emit-body `(loop-accumulate-minimax-value ,data ,specifically ,form))
1197 )))
1198
1199
1200 ;;;; Value Accumulation: Aggregate Booleans
1201
1202 ;;;ALWAYS and NEVER.
1203 ;;; Under ANSI these are not permitted to appear under conditionalization.
1204 (defun loop-do-always (restrictive negate)
1205 (let ((form (loop-get-form)))
1206 (when restrictive (loop-disallow-conditional))
1207 (loop-disallow-anonymous-collectors)
1208 (loop-emit-body `(,(if negate 'when 'unless) ,form
1209 ,(loop-construct-return nil)))
1210 (loop-emit-final-value t)))
1211
1212
1213
1214 ;;;THERIS.
1215 ;;; Under ANSI this is not permitted to appear under conditionalization.
1216 (defun loop-do-thereis (restrictive)
1217 (when restrictive (loop-disallow-conditional))
1218 (loop-disallow-anonymous-collectors)
1219 (loop-emit-final-value)
1220 (loop-emit-body `(when (setq ,(loop-when-it-variable) ,(loop-get-form))
1221 ,(loop-construct-return *loop-when-it-variable*))))
1222
1223
1224 (defun loop-do-while (negate kwd &aux (form (loop-get-form)))
1225 (loop-disallow-conditional kwd)
1226 (loop-pseudo-body `(,(if negate 'when 'unless) ,form (go end-loop))))
1227
1228
1229 (defun loop-do-with ()
1230 (loop-disallow-conditional :with)
1231 (do ((var) (val) (dtype)) (nil)
1232 (setq var (loop-pop-source)
1233 dtype (loop-optional-type var)
1234 val (cond ((loop-tequal (car *loop-source-code*) :=)
1235 (loop-pop-source)
1236 (loop-get-form))
1237 (t nil)))
1238 (when (and var (loop-variable-p var))
1239 (loop-error "Variable ~S has already been used" var))
1240 (loop-make-variable var val dtype)
1241 (if (loop-tequal (car *loop-source-code*) :and)
1242 (loop-pop-source)
1243 (return (loop-bind-block)))))
1244
1245
1246 ;;;; The iteration driver
1247
1248 (defun loop-hack-iteration (entry)
1249 (declare (si::c-local))
1250 (flet ((make-endtest (list-of-forms)
1251 (cond ((null list-of-forms) nil)
1252 ((member t list-of-forms) '(go end-loop))
1253 (t `(when ,(if (null (cdr (setq list-of-forms (nreverse list-of-forms))))
1254 (car list-of-forms)
1255 (cons 'or list-of-forms))
1256 (go end-loop))))))
1257 (do ((pre-step-tests nil)
1258 (steps nil)
1259 (post-step-tests nil)
1260 (pseudo-steps nil)
1261 (pre-loop-pre-step-tests nil)
1262 (pre-loop-steps nil)
1263 (pre-loop-post-step-tests nil)
1264 (pre-loop-pseudo-steps nil)
1265 (tem) (data))
1266 (nil)
1267 ;; Note we collect endtests in reverse order, but steps in correct
1268 ;; order. MAKE-ENDTEST does the nreverse for us.
1269 (setq tem (setq data (apply (symbol-function (first entry)) (rest entry))))
1270 (and (car tem) (push (car tem) pre-step-tests))
1271 (setq steps (nconc steps (copy-list (car (setq tem (cdr tem))))))
1272 (and (car (setq tem (cdr tem))) (push (car tem) post-step-tests))
1273 (setq pseudo-steps (nconc pseudo-steps (copy-list (car (setq tem (cdr tem))))))
1274 (setq tem (cdr tem))
1275 (when *loop-emitted-body*
1276 (loop-error "Iteration in LOOP follows body code. This error is typically caused
1277 by a WHILE, UNTIL or similar condition placed in between FOR, AS, and similar iterations.
1278 Note that this is not a valid ANSI code."))
1279 (unless tem (setq tem data))
1280 (when (car tem) (push (car tem) pre-loop-pre-step-tests))
1281 (setq pre-loop-steps (nconc pre-loop-steps (copy-list (car (setq tem (cdr tem))))))
1282 (when (car (setq tem (cdr tem))) (push (car tem) pre-loop-post-step-tests))
1283 (setq pre-loop-pseudo-steps (nconc pre-loop-pseudo-steps (copy-list (cadr tem))))
1284 (unless (loop-tequal (car *loop-source-code*) :and)
1285 (setq *loop-before-loop* (list* (loop-make-desetq pre-loop-pseudo-steps)
1286 (make-endtest pre-loop-post-step-tests)
1287 (loop-make-psetq pre-loop-steps)
1288 (make-endtest pre-loop-pre-step-tests)
1289 *loop-before-loop*)
1290 *loop-after-body* (list* (loop-make-desetq pseudo-steps)
1291 (make-endtest post-step-tests)
1292 (loop-make-psetq steps)
1293 (make-endtest pre-step-tests)
1294 *loop-after-body*))
1295 (loop-bind-block)
1296 (return nil))
1297 (loop-pop-source) ; flush the "AND"
1298 (when (and (not (loop-universe-implicit-for-required *loop-universe*))
1299 (setq tem (loop-lookup-keyword
1300 (car *loop-source-code*)
1301 (loop-universe-iteration-keywords *loop-universe*))))
1302 ;;Latest ANSI clarification is that the FOR/AS after the AND must NOT be supplied.
1303 (loop-pop-source)
1304 (setq entry tem)))))
1305
1306
1307 ;;;; Main Iteration Drivers
1308
1309
1310 ;FOR variable keyword ..args..
1311 (defun loop-do-for ()
1312 (let* ((var (loop-pop-source))
1313 (data-type (loop-optional-type var))
1314 (keyword (loop-pop-source))
1315 (first-arg nil)
1316 (tem nil))
1317 (setq first-arg (loop-get-form))
1318 (unless (and (symbolp keyword)
1319 (setq tem (loop-lookup-keyword
1320 keyword
1321 (loop-universe-for-keywords *loop-universe*))))
1322 (loop-error "~S is an unknown keyword in FOR or AS clause in LOOP." keyword))
1323 (apply (car tem) var first-arg data-type (cdr tem))))
1324
1325 (defun loop-do-repeat ()
1326 (loop-disallow-conditional :repeat)
1327 (let* ((form (loop-get-form))
1328 (type (if (fixnump form) 'fixnum 'real))
1329 (var (loop-make-variable (gensym) form type))
1330 (form `(loop-unsafe (when (minusp (decf ,var)) (go end-loop)))))
1331 (push form *loop-before-loop*)
1332 (push form *loop-after-body*)
1333 ;; FIXME: What should
1334 ;; (loop count t into a
1335 ;; repeat 3
1336 ;; count t into b
1337 ;; finally (return (list a b)))
1338 ;; return: (3 3) or (4 3)? PUSHes above are for the former
1339 ;; variant, L-P-B below for the latter.
1340 #+nil (loop-pseudo-body form)))
1341
1342 (defun loop-when-it-variable ()
1343 (declare (si::c-local))
1344 (or *loop-when-it-variable*
1345 (setq *loop-when-it-variable*
1346 (loop-make-variable (gensym "LOOP-IT-") nil nil))))
1347
1348
1349 ;;;; Various FOR/AS Subdispatches
1350
1351
1352 ;;;ANSI "FOR x = y [THEN z]" is sort of like the old Genera one when the THEN
1353 ;;; is omitted (other than being more stringent in its placement), and like
1354 ;;; the old "FOR x FIRST y THEN z" when the THEN is present. I.e., the first
1355 ;;; initialization occurs in the loop body (first-step), not in the variable binding
1356 ;;; phase.
1357 (defun loop-ansi-for-equals (var val data-type)
1358 (loop-make-iteration-variable var nil data-type)
1359 (cond ((loop-tequal (car *loop-source-code*) :then)
1360 ;;Then we are the same as "FOR x FIRST y THEN z".
1361 (loop-pop-source)
1362 `(() (,var ,(loop-get-form)) () ()
1363 () (,var ,val) () ()))
1364 (t ;;We are the same as "FOR x = y".
1365 `(() (,var ,val) () ()))))
1366
1367
1368 (defun loop-for-across (var val data-type)
1369 (loop-make-iteration-variable var nil data-type)
1370 (let ((vector-var (gensym "LOOP-ACROSS-VECTOR-"))
1371 (index-var (gensym "LOOP-ACROSS-INDEX-")))
1372 (multiple-value-bind (vector-form constantp vector-value)
1373 (loop-constant-fold-if-possible val 'vector)
1374 (loop-make-variable
1375 vector-var vector-form
1376 (if (and (consp vector-form) (eq (car vector-form) 'the))
1377 (cadr vector-form)
1378 'vector))
1379 (loop-make-variable index-var 0 'fixnum)
1380 (let* ((length 0)
1381 (length-form (cond ((not constantp)
1382 (let ((v (gensym "LOOP-ACROSS-LIST")))
1383 (push `(setq ,v (length ,vector-var)) *loop-prologue*)
1384 (loop-make-variable v 0 'fixnum)))
1385 (t (setq length (length vector-value)))))
1386 (first-test `(>= ,index-var ,length-form))
1387 (other-test first-test)
1388 (step `(,var (aref ,vector-var ,index-var)))
1389 (pstep `(,index-var (1+ ,index-var))))
1390 (declare (fixnum length))
1391 (when constantp
1392 (setq first-test (= length 0))
1393 (when (<= length 1)
1394 (setq other-test t)))
1395 `(,other-test ,step () ,pstep
1396 ,@(and (not (eq first-test other-test)) `(,first-test ,step () ,pstep)))))))
1397
1398
1399
1400 ;;;; List Iteration
1401
1402
1403 (defun loop-list-step (listvar)
1404 (declare (si::c-local))
1405 ;;We are not equipped to analyze whether 'FOO is the same as #'FOO here in any
1406 ;; sensible fashion, so let's give an obnoxious warning whenever 'FOO is used
1407 ;; as the stepping function.
1408 ;;While a Discerning Compiler may deal intelligently with (funcall 'foo ...), not
1409 ;; recognizing FOO may defeat some LOOP optimizations.
1410 (let ((stepper (cond ((loop-tequal (car *loop-source-code*) :by)
1411 (loop-pop-source)
1412 (loop-get-form))
1413 (t '(function cons-cdr)))))
1414 (cond ((and (consp stepper) (eq (car stepper) 'quote))
1415 (loop-warn "Use of QUOTE around stepping function in LOOP will be left verbatim.")
1416 (values `(funcall ,stepper ,listvar) nil))
1417 ((and (consp stepper) (eq (car stepper) 'function))
1418 (values (list (cadr stepper) listvar) (cadr stepper)))
1419 (t (values `(funcall ,(loop-make-variable (gensym "LOOP-FN") stepper 'function)
1420 ,listvar)
1421 nil)))))
1422
1423
1424 (defun loop-for-on (var val data-type)
1425 (multiple-value-bind (list constantp list-value)
1426 (loop-constant-fold-if-possible val)
1427 (let ((listvar var))
1428 (cond ((and var (symbolp var))
1429 (loop-make-iteration-variable var list data-type))
1430 (t
1431 ;; using data type 'list for listvar can lead to errors for dotted lists
1432 (loop-make-variable (setq listvar (gensym)) list nil)
1433 (loop-make-iteration-variable var nil data-type)))
1434 (let ((list-step (loop-list-step listvar)))
1435 (let* ((first-endtest
1436 ;; mysterious comment from original CMU CL sources:
1437 ;; the following should use `atom' instead of `endp', per
1438 ;; [bug2428]
1439 `(atom ,listvar))
1440 (other-endtest first-endtest))
1441 (when (and constantp (listp list-value))
1442 (setq first-endtest (null list-value)))
1443 (cond ((eq var listvar)
1444 ;; The contour of the loop is different because we
1445 ;; use the user's variable...
1446 `(() (,listvar ,list-step)
1447 ,other-endtest () () () ,first-endtest ()))
1448 (t (let ((step `(,var ,listvar))
1449 (pseudo `(,listvar ,list-step)))
1450 `(,other-endtest ,step () ,pseudo
1451 ,@(and (not (eq first-endtest other-endtest))
1452 `(,first-endtest ,step () ,pseudo)))))))))))
1453
1454
1455 (defun loop-for-in (var val data-type)
1456 (multiple-value-bind (list constantp list-value)
1457 (loop-constant-fold-if-possible val)
1458 (let ((listvar (gensym "LOOP-LIST")))
1459 (loop-make-iteration-variable var nil data-type)
1460 (loop-make-variable listvar list 'list)
1461 (let ((list-step (loop-list-step listvar)))
1462 (let* ((first-endtest `(endp ,listvar))
1463 (other-endtest first-endtest)
1464 (step `(,var (cons-car ,listvar)))
1465 (pseudo-step `(,listvar ,list-step)))
1466 (when (and constantp (listp list-value))
1467 (setq first-endtest (null list-value)))
1468 `(,other-endtest ,step () ,pseudo-step
1469 ,@(and (not (eq first-endtest other-endtest))
1470 `(,first-endtest ,step () ,pseudo-step))))))))
1471
1472
1473 ;;;; Iteration Paths
1474
1475
1476 (defstruct (loop-path
1477 #+ecl (:type vector)
1478 #+nil (:copier nil)
1479 #+nil (:predicate nil))
1480 names
1481 preposition-groups
1482 inclusive-permitted
1483 function
1484 user-data)
1485
1486
1487 (defun add-loop-path (names function universe &key preposition-groups inclusive-permitted user-data)
1488 (declare (si::c-local))
1489 (unless (listp names)
1490 (setq names (list names)))
1491 (let ((ht (loop-universe-path-keywords universe))
1492 (lp (make-loop-path
1493 :names (mapcar #'symbol-name names)
1494 :function function
1495 :user-data user-data
1496 :preposition-groups (mapcar #'(lambda (x) (if (listp x) x (list x))) preposition-groups)
1497 :inclusive-permitted inclusive-permitted)))
1498 (dolist (name names) (setf (gethash (symbol-name name) ht) lp))
1499 lp))
1500
1501
1502 ;;; Note: path functions are allowed to use loop-make-variable, hack
1503 ;;; the prologue, etc.
1504 (defun loop-for-being (var val data-type)
1505 ;; FOR var BEING each/the pathname prep-phrases using-stuff...
1506 ;; each/the = EACH or THE. Not clear if it is optional, so I guess we'll warn.
1507 (let ((path nil)
1508 (data nil)
1509 (inclusive nil)
1510 (stuff nil)
1511 (initial-prepositions nil))
1512 (cond ((loop-tmember val '(:each :the)) (setq path (loop-pop-source)))
1513 ((loop-tequal (car *loop-source-code*) :and)
1514 (loop-pop-source)
1515 (setq inclusive t)
1516 (unless (loop-tmember (car *loop-source-code*) '(:its :each :his :her))
1517 (loop-error "~S found where ITS or EACH expected in LOOP iteration path syntax."
1518 (car *loop-source-code*)))
1519 (loop-pop-source)
1520 (setq path (loop-pop-source))
1521 (setq initial-prepositions `((:in ,val))))
1522 (t (loop-error "Unrecognizable LOOP iteration path syntax. Missing EACH or THE?")))
1523 (cond ((not (symbolp path))
1524 (loop-error "~S found where a LOOP iteration path name was expected." path))
1525 ((not (setq data (loop-lookup-keyword path (loop-universe-path-keywords *loop-universe*))))
1526 (loop-error "~S is not the name of a LOOP iteration path." path))
1527 ((and inclusive (not (loop-path-inclusive-permitted data)))
1528 (loop-error "\"Inclusive\" iteration is not possible with the ~S LOOP iteration path." path)))
1529 (let ((fun (loop-path-function data))
1530 (preps (nconc initial-prepositions
1531 (loop-collect-prepositional-phrases (loop-path-preposition-groups data) t)))
1532 (user-data (loop-path-user-data data)))
1533 (when (symbolp fun) (setq fun (symbol-function fun)))
1534 (setq stuff (if inclusive
1535 (apply fun var data-type preps :inclusive t user-data)
1536 (apply fun var data-type preps user-data))))
1537 (when *loop-named-variables*
1538 (loop-error "Unused USING variables: ~S." *loop-named-variables*))
1539 ;; STUFF is now (bindings prologue-forms . stuff-to-pass-back). Protect the system from the user
1540 ;; and the user from himself.
1541 (unless (member (length stuff) '(6 10))
1542 (loop-error "Value passed back by LOOP iteration path function for path ~S has invalid length."
1543 path))
1544 (do ((l (car stuff) (cdr l)) (x)) ((null l))
1545 (if (atom (setq x (car l)))
1546 (loop-make-iteration-variable x nil nil)
1547 (loop-make-iteration-variable (car x) (cadr x) (caddr x))))
1548 (setq *loop-prologue* (nconc (reverse (cadr stuff)) *loop-prologue*))
1549 (cddr stuff)))
1550
1551
1552
1553 ;;;INTERFACE: Lucid, exported.
1554 ;;; i.e., this is part of our extended ansi-loop interface.
1555 (defun loop-named-var (name)
1556 (declare (si::c-local))
1557 (let ((tem (loop-tassoc name *loop-named-variables*)))
1558 (declare (list tem))
1559 (cond ((null tem) (values (gensym) nil))
1560 (t (setq *loop-named-variables* (delete tem *loop-named-variables*))
1561 (values (cdr tem) t)))))
1562
1563
1564 (defun loop-collect-prepositional-phrases (preposition-groups &optional USING-allowed initial-phrases)
1565 (declare (si::c-local))
1566 (flet ((in-group-p (x group) (car (loop-tmember x group))))
1567 (do ((token nil)
1568 (prepositional-phrases initial-phrases)
1569 (this-group nil nil)
1570 (this-prep nil nil)
1571 (disallowed-prepositions
1572 (mapcan #'(lambda (x)
1573 (copy-list
1574 (find (car x) preposition-groups :test #'in-group-p)))
1575 initial-phrases))
1576 (used-prepositions (mapcar #'car initial-phrases)))
1577 ((null *loop-source-code*) (nreverse prepositional-phrases))
1578 (declare (symbol this-prep))
1579 (setq token (car *loop-source-code*))
1580 (dolist (group preposition-groups)
1581 (when (setq this-prep (in-group-p token group))
1582 (return (setq this-group group))))
1583 (cond (this-group
1584 (when (member this-prep disallowed-prepositions)
1585 (loop-error
1586 (if (member this-prep used-prepositions)
1587 "A ~S prepositional phrase occurs multiply for some LOOP clause."
1588 "Preposition ~S used when some other preposition has subsumed it.")
1589 token))
1590 (setq used-prepositions (if (listp this-group)
1591 (append this-group used-prepositions)
1592 (cons this-group used-prepositions)))
1593 (loop-pop-source)
1594 (push (list this-prep (loop-get-form)) prepositional-phrases))
1595 ((and USING-allowed (loop-tequal token 'using))
1596 (loop-pop-source)
1597 (do ((z (loop-pop-source) (loop-pop-source)) (tem)) (nil)
1598 (when (cadr z)
1599 (if (setq tem (loop-tassoc (car z) *loop-named-variables*))
1600 (loop-error
1601 "The variable substitution for ~S occurs twice in a USING phrase,~@
1602 with ~S and ~S."
1603 (car z) (cadr z) (cadr tem))
1604 (push (cons (car z) (cadr z)) *loop-named-variables*)))
1605 (when (or (null *loop-source-code*) (symbolp (car *loop-source-code*)))
1606 (return nil))))
1607 (t (return (nreverse prepositional-phrases)))))))
1608
1609
1610 ;;;; Master Sequencer Function
1611
1612 (defun loop-sequencer (indexv indexv-type indexv-user-specified-p
1613 variable variable-type
1614 sequence-variable sequence-type
1615 step-hack default-top
1616 prep-phrases)
1617 (declare (si::c-local)
1618 (ignore indexv-user-specified-p))
1619 (let ((endform nil) ;Form (constant or variable) with limit value.
1620 (sequencep nil) ;T if sequence arg has been provided.
1621 (testfn nil) ;endtest function
1622 (test nil) ;endtest form.
1623 (stepby (1+ (or (loop-typed-init indexv-type) 0))) ;Our increment.
1624 (stepby-constantp t)
1625 (step nil) ;step form.
1626 (dir nil) ;Direction of stepping: NIL, :UP, :DOWN.
1627 (inclusive-iteration nil) ;T if include last index.
1628 (start-given nil) ;T when prep phrase has specified start
1629 (start-value nil)
1630 (start-constantp nil)
1631 (limit-given nil) ;T when prep phrase has specified end
1632 (limit-constantp nil)
1633 (limit-value nil)
1634 )
1635 (when variable (loop-make-iteration-variable variable nil variable-type))
1636 (do ((l prep-phrases (cdr l)) (prep) (form) (odir)) ((null l))
1637 (setq prep (caar l) form (cadar l))
1638 (case prep
1639 ((:of :in)
1640 (setq sequencep t)
1641 (loop-make-variable sequence-variable form sequence-type))
1642 ((:from :downfrom :upfrom)
1643 (setq start-given t)
1644 (cond ((eq prep :downfrom) (setq dir ':down))
1645 ((eq prep :upfrom) (setq dir ':up)))
1646 (multiple-value-setq (form start-constantp start-value)
1647 (loop-constant-fold-if-possible form indexv-type))
1648 (loop-make-iteration-variable indexv form indexv-type))
1649 ((:upto :to :downto :above :below)
1650 (cond ((loop-tequal prep :upto) (setq inclusive-iteration (setq dir ':up)))
1651 ((loop-tequal prep :to) (setq inclusive-iteration t))
1652 ((loop-tequal prep :downto) (setq inclusive-iteration (setq dir ':down)))
1653 ((loop-tequal prep :above) (setq dir ':down))
1654 ((loop-tequal prep :below) (setq dir ':up)))
1655 (setq limit-given t)
1656 (multiple-value-setq (form limit-constantp limit-value)
1657 (loop-constant-fold-if-possible form indexv-type))
1658 (setq endform (if limit-constantp
1659 `',limit-value
1660 (loop-make-variable
1661 (gensym "LOOP-LIMIT") form indexv-type))))
1662 (:by
1663 (multiple-value-setq (form stepby-constantp stepby)
1664 (loop-constant-fold-if-possible form indexv-type))
1665 (unless stepby-constantp
1666 (loop-make-variable (setq stepby (gensym "LOOP-STEP-BY")) form indexv-type)))
1667 (t (loop-error
1668 "~S invalid preposition in sequencing or sequence path.~@
1669 Invalid prepositions specified in iteration path descriptor or something?"
1670 prep)))
1671 (when (and odir dir (not (eq dir odir)))
1672 (loop-error "Conflicting stepping directions in LOOP sequencing path"))
1673 (setq odir dir))
1674 (when (and sequence-variable (not sequencep))
1675 (loop-error "Missing OF or IN phrase in sequence path"))
1676 ;; Now fill in the defaults.
1677 (unless start-given
1678 (loop-make-iteration-variable
1679 indexv
1680 (setq start-constantp t start-value (or (loop-typed-init indexv-type) 0))
1681 indexv-type))
1682 (cond ((member dir '(nil :up))
1683 (when (or limit-given default-top)
1684 (unless limit-given
1685 (loop-make-variable (setq endform (gensym "LOOP-SEQ-LIMIT-"))
1686 nil indexv-type)
1687 (push `(setq ,endform ,default-top) *loop-prologue*))
1688 (setq testfn (if inclusive-iteration '> '>=)))
1689 (setq step (if (eql stepby 1) `(1+ ,indexv) `(+ ,indexv ,stepby))))
1690 (t (unless start-given
1691 (unless default-top
1692 (loop-error "Don't know where to start stepping."))
1693 (push `(setq ,indexv (1- ,default-top)) *loop-prologue*))
1694 (when (and default-top (not endform))
1695 (setq endform (loop-typed-init indexv-type) inclusive-iteration t))
1696 (when endform (setq testfn (if inclusive-iteration '< '<=)))
1697 (setq step (if (eql stepby 1) `(1- ,indexv) `(- ,indexv ,stepby)))))
1698 (setq step `(loop-unsafe ,step))
1699 (when testfn
1700 (setq test `(,testfn ,indexv ,endform)))
1701 (when step-hack
1702 (setq step-hack `(,variable ,step-hack)))
1703 (let ((first-test test) (remaining-tests test))
1704 (when (and stepby-constantp start-constantp)
1705 ;; We can make the number type more precise when we know the
1706 ;; start, end and step values.
1707 (let ((new-type (typecase (+ start-value stepby)
1708 (integer (if (and (fixnump start-value)
1709 limit-constantp
1710 (< limit-value most-positive-fixnum)
1711 (> limit-value most-negative-fixnum))
1712 'fixnum
1713 'integer))
1714 (single-float 'single-float)
1715 (double-float 'double-float)
1716 (long-float 'long-float)
1717 (short-float 'short-float)
1718 (t indexv-type))))
1719 (unless (subtypep (type-of start-value) new-type)
1720 ;; The start type may not be a subtype of the type during
1721 ;; iteration. Happens e.g. when stepping a fixnum start
1722 ;; value by a float.
1723 (setf new-type `(or ,(type-of start-value) ,new-type)))
1724 (unless (subtypep indexv-type new-type)
1725 (loop-declare-variable indexv new-type)))
1726 (when (and limit-constantp
1727 (setq first-test (funcall (symbol-function testfn)
1728 start-value
1729 limit-value)))
1730 (setq remaining-tests t)))
1731 `(() (,indexv ,step) ,remaining-tests ,step-hack
1732 () () ,first-test ,step-hack))))
1733
1734
1735 ;;;; Interfaces to the Master Sequencer
1736
1737
1738
1739 (defun loop-for-arithmetic (var val data-type kwd)
1740 (unless var
1741 (setf var (gensym)))
1742 (loop-sequencer
1743 var (loop-check-data-type data-type 'number) t
1744 nil nil nil nil nil nil
1745 (loop-collect-prepositional-phrases
1746 '((:from :upfrom :downfrom) (:to :upto :downto :above :below) (:by))
1747 nil (list (list kwd val)))))
1748
1749
1750 ;;;; Builtin LOOP Iteration Paths
1751
1752
1753 #||
1754 (loop for v being the hash-values of ht do (print v))
1755 (loop for k being the hash-keys of ht do (print k))
1756 (loop for v being the hash-values of ht using (hash-key k) do (print (list k v)))
1757 (loop for k being the hash-keys of ht using (hash-value v) do (print (list k v)))
1758 ||#
1759
1760 (defun loop-hash-table-iteration-path (variable data-type prep-phrases &key which)
1761 (check-type which (member hash-key hash-value))
1762 (cond ((or (cdr prep-phrases) (not (member (caar prep-phrases) '(:in :of))))
1763 (loop-error "Too many prepositions!"))
1764 ((null prep-phrases) (loop-error "Missing OF or IN in ~S iteration path.")))
1765 (let ((ht-var (gensym "LOOP-HASHTAB-"))
1766 (next-fn (gensym "LOOP-HASHTAB-NEXT-"))
1767 (dummy-predicate-var nil)
1768 (post-steps nil))
1769 (multiple-value-bind (other-var other-p)
1770 (loop-named-var (if (eq which 'hash-key) 'hash-value 'hash-key))
1771 ;; @@@@ LOOP-NAMED-VAR returns a second value of T if the name
1772 ;; was actually specified, so clever code can throw away the
1773 ;; GENSYM'ed-up variable if it isn't really needed. The
1774 ;; following is for those implementations in which we cannot put
1775 ;; dummy NILs into MULTIPLE-VALUE-SETQ variable lists.
1776 (setq other-p t
1777 dummy-predicate-var (loop-when-it-variable))
1778 (let* ((key-var nil)
1779 (val-var nil)
1780 (temp-val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1781 (temp-key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1782 (temp-predicate-var (gensym "LOOP-HASH-PREDICATE-VAR-"))
1783 (variable (or variable (gensym)))
1784 (bindings `((,variable nil ,data-type)
1785 (,ht-var ,(cadar prep-phrases))
1786 ,@(and other-p other-var `((,other-var nil))))))
1787 (if (eq which 'hash-key)
1788 (setq key-var variable val-var (and other-p other-var))
1789 (setq key-var (and other-p other-var) val-var variable))
1790 (push `(with-hash-table-iterator (,next-fn ,ht-var)) *loop-wrappers*)
1791 (when (consp key-var)
1792 (setq post-steps `(,key-var ,(setq key-var (gensym "LOOP-HASH-KEY-TEMP-"))
1793 ,@post-steps))
1794 (push `(,key-var nil) bindings))
1795 (when (consp val-var)
1796 (setq post-steps `(,val-var ,(setq val-var (gensym "LOOP-HASH-VAL-TEMP-"))
1797 ,@post-steps))
1798 (push `(,val-var nil) bindings))
1799 `(,bindings ;bindings
1800 () ;prologue
1801 () ;pre-test
1802 () ;parallel steps
1803 (not
1804 (multiple-value-bind (,temp-predicate-var ,temp-key-var ,temp-val-var)
1805 (,next-fn)
1806 ;; We use M-V-BIND instead of M-V-SETQ because we only
1807 ;; want to assign values to the key and val vars when we
1808 ;; are in the hash table. When we reach the end,
1809 ;; TEMP-PREDICATE-VAR is NIL, and so are temp-key-var and
1810 ;; temp-val-var. This might break any type declarations
1811 ;; on the key and val vars.
1812 (when ,temp-predicate-var
1813 (setq ,val-var ,temp-val-var)
1814 (setq ,key-var ,temp-key-var))
1815 (setq ,dummy-predicate-var ,temp-predicate-var)
1816 )) ;post-test
1817 ,post-steps)))))
1818
1819
1820 (defun loop-package-symbols-iteration-path (variable data-type prep-phrases &key symbol-types)
1821 (cond ((and prep-phrases (cdr prep-phrases))
1822 (loop-error "Too many prepositions!"))
1823 ((and prep-phrases (not (member (caar prep-phrases) '(:in :of))))
1824 (loop-error "Unknow preposition ~S" (caar prep-phrases))))
1825 (unless (symbolp variable)
1826 (loop-error "Destructuring is not valid for package symbol iteration."))
1827 (let ((pkg-var (gensym "LOOP-PKGSYM-"))
1828 (next-fn (gensym "LOOP-PKGSYM-NEXT-"))
1829 (variable (or variable (gensym)))
1830 (pkg (or (cadar prep-phrases) '*package*)))
1831 (push `(with-package-iterator (,next-fn ,pkg-var ,@symbol-types)) *loop-wrappers*)
1832 `(((,variable nil ,data-type) (,pkg-var ,pkg))
1833 ()
1834 ()
1835 ()
1836 (not (multiple-value-setq (,(progn
1837 ;;@@@@ If an implementation can get away without actually
1838 ;; using a variable here, so much the better.
1839 (loop-when-it-variable))
1840 ,variable)
1841 (,next-fn)))
1842 ())))
1843
1844 ;;;; ANSI Loop
1845
1846 (defun make-ansi-loop-universe (extended-p)
1847 (declare (si::c-local))
1848 (let ((w (make-standard-loop-universe
1849 :keywords '((named (loop-do-named))
1850 (initially (loop-do-initially))
1851 (finally (loop-do-finally))
1852 (do (loop-do-do))
1853 (doing (loop-do-do))
1854 (return (loop-do-return))
1855 (collect (loop-list-collection list))
1856 (collecting (loop-list-collection list))
1857 (append (loop-list-collection append))
1858 (appending (loop-list-collection append))
1859 (nconc (loop-list-collection nconc))
1860 (nconcing (loop-list-collection nconc))
1861 (count (loop-sum-collection count real fixnum))
1862 (counting (loop-sum-collection count real fixnum))
1863 (sum (loop-sum-collection sum number number))
1864 (summing (loop-sum-collection sum number number))
1865 (maximize (loop-maxmin-collection max))
1866 (minimize (loop-maxmin-collection min))
1867 (maximizing (loop-maxmin-collection max))
1868 (minimizing (loop-maxmin-collection min))
1869 (always (loop-do-always t nil)) ; Normal, do always
1870 (never (loop-do-always t t)) ; Negate the test on always.
1871 (thereis (loop-do-thereis t))
1872 (while (loop-do-while nil :while)) ; Normal, do while
1873 (until (loop-do-while t :until)) ; Negate the test on while
1874 (when (loop-do-if when nil)) ; Normal, do when
1875 (if (loop-do-if if nil)) ; synonymous
1876 (unless (loop-do-if unless t)) ; Negate the test on when
1877 (with (loop-do-with))
1878 (repeat (loop-do-repeat)))
1879 :for-keywords '((= (loop-ansi-for-equals))
1880 (across (loop-for-across))
1881 (in (loop-for-in))
1882 (on (loop-for-on))
1883 (from (loop-for-arithmetic :from))
1884 (downfrom (loop-for-arithmetic :downfrom))
1885 (upfrom (loop-for-arithmetic :upfrom))
1886 (below (loop-for-arithmetic :below))
1887 (above (loop-for-arithmetic :above))
1888 (to (loop-for-arithmetic :to))
1889 (upto (loop-for-arithmetic :upto))
1890 (downto (loop-for-arithmetic :downto))
1891 (by (loop-for-arithmetic :by))
1892 (being (loop-for-being)))
1893 :iteration-keywords '((for (loop-do-for))
1894 (as (loop-do-for)))
1895 :type-symbols '(array atom bignum bit bit-vector character compiled-function
1896 complex cons double-float fixnum float
1897 function hash-table integer keyword list long-float
1898 nil null number package pathname random-state
1899 ratio rational readtable sequence short-float
1900 simple-array simple-bit-vector simple-string
1901 simple-vector single-float standard-char
1902 stream string base-char
1903 symbol t vector)
1904 :type-keywords nil
1905 :ansi (if extended-p :extended t))))
1906 (add-loop-path '(hash-key hash-keys) 'loop-hash-table-iteration-path w
1907 :preposition-groups '((:of :in))
1908 :inclusive-permitted nil
1909 :user-data '(:which hash-key))
1910 (add-loop-path '(hash-value hash-values) 'loop-hash-table-iteration-path w
1911 :preposition-groups '((:of :in))
1912 :inclusive-permitted nil
1913 :user-data '(:which hash-value))
1914 (add-loop-path '(symbol symbols) 'loop-package-symbols-iteration-path w
1915 :preposition-groups '((:of :in))
1916 :inclusive-permitted nil
1917 :user-data '(:symbol-types (:internal :external :inherited)))
1918 (add-loop-path '(external-symbol external-symbols) 'loop-package-symbols-iteration-path w
1919 :preposition-groups '((:of :in))
1920 :inclusive-permitted nil
1921 :user-data '(:symbol-types (:external)))
1922 (add-loop-path '(present-symbol present-symbols) 'loop-package-symbols-iteration-path w
1923 :preposition-groups '((:of :in))
1924 :inclusive-permitted nil
1925 :user-data '(:symbol-types (:internal :external)))
1926 w))
1927
1928
1929 (defparameter *loop-ansi-universe*
1930 (make-ansi-loop-universe nil))
1931
1932
1933 (defun loop-standard-expansion (keywords-and-forms environment universe)
1934 (declare (si::c-local))
1935 (if (some #'atom keywords-and-forms)
1936 (if (symbolp (car keywords-and-forms))
1937 (loop-translate keywords-and-forms environment universe)
1938 (error "LOOP: The first form ~S is not an extended loop keyword."
1939 (car keywords-and-forms)))
1940 (let ((tag (gensym)))
1941 `(block nil (tagbody ,tag (progn ,@keywords-and-forms) (go ,tag))))))
1942
1943
1944 ;;;INTERFACE: ANSI
1945 (defmacro loop (&environment env &rest keywords-and-forms)
1946 (loop-standard-expansion keywords-and-forms env *loop-ansi-universe*))