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