iterate.lisp 128 KB
Newer Older
Attila Lendvai's avatar
Attila Lendvai committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
;;;-*- syntax:COMMON-LISP; Package: (ITERATE :use "COMMON-LISP" :colon-mode :external) -*-


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;                     ITERATE, An Iteration Macro
;;;
;;;                 Copyright 1989 by Jonathan Amsterdam
;;;         Adapted to ANSI Common Lisp in 2003 by Andreas Fuchs
;;;
;;; Permission to use, copy, modify, and distribute this software and its
;;; documentation for any purpose and without fee is hereby granted,
;;; provided that this copyright and permission notice appear in all
;;; copies and supporting documentation, and that the name of M.I.T. not
;;; be used in advertising or publicity pertaining to distribution of the
;;; software without specific, written prior permission. M.I.T. makes no
;;; representations about the suitability of this software for any
;;; purpose.  It is provided "as is" without express or implied warranty.

;;; M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
;;; M.I.T. BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
;;; ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
;;; WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
;;; SOFTWARE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;  FIXES.
;;; (v. 1.2-ansi)
;;;  2004-11-30 - Joerg Hoehle: a dozen small fixes to various functions
;;;  2003-12-16 - Tested a bit more, implemented FOR-HASHTABLE and
;;;               FOR-PACKAGES (FOR-PACKAGE) iteration CLtS-style
;;;               using (with-{package,hashtable}-iterator)
;;;  2003-12-16 - ported iterate-1.2 to ANSI Common Lisp (in the form
;;;               of SBCL). Extremely untested. Works for simple
;;;               examples, though.
;;; (v. 1.2)
;;;  6/14/91  - fixed generation of previous code
;;;  5/6/91   - improved code generated for COLLECT and ADJOINING
;;;  4/10/91  - added *binding-context?* to correctly determine when inside
;;;	        a binding context
;;;  12/20/90 - fixed ,. bug in IN-HASHTABLE
;;;  3/3/91 - no longer generates loop-end and loop-step tags if they're not
;;;           used, to avoid compiler warnings from some compilers (Allegro)
;;;  3/4/91 - treat cond as a special form for allegro
;;;  (v. 1.1.1)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; OUTSTANDING PROBLEMS & QUESTIONS:
;;; - What happens if there are two contradictory declarations 
;;;   about a variable's type?  We just take the second one. CLM 
;;;   doesn't say, but presumably this is an error. Let's say it is.
;;;
;;; - Is there a more general way to do synonyms that still allows
;;;   some specificity to particular clauses?  Right now, all we allow
;;;   is for the first words of clauses to have synonyms.
;;;
;;; - We should look at function type declarations, at least at the
;;;   result type, and record them.
;;;
;;; - Consider adding an if-never keyword to find...max/min
;;;
;;; - Consider allowing accumulation variables to be generalized
;;;   variables, acceptable to setf.
;;;
;;; - Consider parsing type declarations of the form (vector * integer),
;;;   to generate types for internal variables.
;;;
;;; - Vector destructuring?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TO DO: 
;;;  - do I walk &optional and &key code in lambda-lists?
;;;  - try binding *macroexpand-hook* in walk
;;;  - track down PREVIOUS bug in Symbolics and sparc lucid

;;;  - reducing and accum: RESULT-TYPE
;;;  - rethink types 
;;;  - how to type result var?
;;;  - (for var concatenate (from 1 to 10) (in '(a b c)) (next (gensym)))
;;;  -       (if (< var 10) 
;;;		 (next [from-to])
;;;		 (if lst
;;;		     (next [in])
;;;		     (gensym)))
;;;  - for var choose, for var repeatedly

;;; For CL version 2:
;;;  - variable info from environments
;;;  - macro info     "     " (so we can support macrolet)
;;;  - use errors for EOF
;;;  - change WALK and FREE-VARIABLES to take symbol macros into account
;;;  - array indices are fixnums
;;;  - type REAL for extremum clauses

;;; Maybe:
;;;  - decls can appear not at top level, as long as they appear before use.
;;;  - extremum and find-extremum should do reductions when possible
;;;  - optimize collections, hashtables, packages for lispms 
;;;  - fix :using-type-of to check for supplied ???
;;;  - for-in should allow numerical keywords (from, to, etc.)...?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TO TEST: 
;;;  - leaving driver code where it is
;;;  - typing
;;;  - macroexpand & walk after-each
;;;  - check for duplicate keywords in defclause, defmacro-clause
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TO DOCUMENT:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;


(in-package #:iterate)

(declaim (declaration declare-variables))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Constants and global variables.
(defconst version "1.4" "Current version of Iterate")



(defconst standard-type-symbols ; of CLtL2
  '(array atom bignum bit bit-vector boolean character compiled-function
    complex cons double-float fixnum float function hash-table integer
    keyword list long-float nil null number package pathname random-state
    ratio rational readtable real sequence short-float signed-byte simple-array 
    simple-bit-vector simple-string simple-vector single-float standard-char
    stream string string-char symbol t unsigned-byte vector)
  "Table 4-1 of the Common Lisp Manual")


;;; These next two can be used for maximizing and minimizing.

#+nil ;; unused
(defconst smallest-number-alist
  `((fixnum . ,most-negative-fixnum)
    (float . ,most-negative-long-float)
    (long-float . ,most-negative-long-float)
    (short-float . ,most-negative-short-float)
    (double-float . ,most-negative-double-float)
    (single-float . ,most-negative-single-float)))

#+nil ;; unused
(defconst largest-number-alist
  `((fixnum . ,most-positive-fixnum)
    (float . ,most-positive-long-float)
    (long-float . ,most-positive-long-float)
    (short-float . ,most-positive-short-float)
    (double-float . ,most-positive-double-float)
    (single-float . ,most-positive-single-float)))


;;; This is like (declare (declare-variables)).

(defvar *always-declare-variables* nil)

;;; *result-var* is bound to a gensym before the clauses of an iterate
;;; form are processed.  In the generated code, the gensym is bound
;;; to nil before any other bindings are performed.  Clauses are free
;;; to generate code that sets the value of *result-var*.

(defvar *result-var*)

;;; Iterate binds *type-alist* to an alist of variables and their
;;; types before processing clauses.  It does this by looking at
;;; (declare (type ...)) forms in the clauses and recording the information
;;; there.  (Just variable type information, not function.)

(defvar *type-alist*)

;;; *declare-variables* is bound to T iff the 
;;;            (declare (iterate:declare-variables))
;;; declaration was seen at top-level, or if
;;; *always-declare-variables* is non-nil.  This indicates that variables 
;;; that haven't been declared by the user should be declared to have
;;; the appropriate types.  What "appropriate" means depends on the
;;; context. 

(defvar *declare-variables*)

;;; *clause* is bound to each entire iterate clause before the clause
;;; is processed.  Mostly for error output (see clause-error).

(defvar *clause*)

;;; *top-level?* is bound to T at top-level (i.e. before any forms that
;;; contain clauses inside them, like IF, LET, etc.) and to NIL
;;; inside such forms.  It is useful to ensure that certain forms
;;; (particularly iteration drivers) occur only at top-level.

(defvar *top-level?*)

;;; *binding-context?* a misnomer, should be named *declaration-context*, is
;;; bound to T inside a form that allows declarations (flet, labels).  We used
;;; to just see if *internal-variables* was non-nil, but that's wrong--you can
;;; be inside a binding context that binds no variables.

(defvar *binding-context?*)

;;; For the use of make-binding-internal, to pass back bindings.
;;; if-1st-time also uses it to create first-time variables.

(defvar *bindings*)


;;; This is a list of variable-lists containing the variables made by
;;; internal let's or other binding forms.  It is used to check for
;;; the error of having iterate try to bind one of these variables at
;;; top-level.  E.g.
;;;   (iterate (for i from 1 to 10)
;;;            (let ((a nil))
;;;              (collect i into a)))
;;; is an error.

(defvar *internal-variables*)


;;; For functions (like make-binding) that don't want to or can't pass
;;; declarations normally.  These are really decl-specs, not full
;;; declarations. 

(defvar *declarations*)


;;; This is how we get multiple accumulations into the same variable
;;; to come out right.  See make-accum-var-binding.
;;; It's an alist of (accum-var kind <possibly other info>).
;;; The currently used kinds are:
;;;   :collect     for collect, nconc, append, etc.
;;;   :increment   for count, sum and multiply
;;;   :max         for maximize
;;;   :min         for minimize
;;;   :if-exists   for always/never/thereis and finding such-that
;;; Note that we do not check for type conflict in the re-use of these
;;; variables.

(defvar *accum-var-alist*)

247 248 249 250 251 252
;;; Shared variables created by make-shared-binding.
;;; It's an alist of (name gensym-var <possibly other info>).
;;; Tipical use is FIRST-ITERATION-P.

(defvar *shared-bindings-alist*)

Attila Lendvai's avatar
Attila Lendvai committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
;;; Name of the block for this iterate form.  Used in generating
;;; return statements.

(defvar *block-name*)

;;; The index of standard clauses (a discrimination tree).  This is a
;;; defvar so that reloading doesn't clobber existing defs (though it
;;; will clobber those clauses that are defined in this file, of
;;; course).

(defvar *clause-info-index* (list :index))

(eval-when (:compile-toplevel)
  ;; This is so the variable has a value when we compile this file, since
  ;; the process of compilation results in actually setting things up.
  (if (not (boundp '*clause-info-index*)) 
      (setq *clause-info-index* (list :index))))


;;; An alist of lisp special forms and the functions for handling them.
;;; nil as function means leave form as-is.

(defparameter *special-form-alist* 
  '(;; First the special operators that every code walker must recognize
    (block . 		    walk-cddr) 
    (catch . 		    walk-cdr)
    (declare . 	 	    walk-declare)
    (eval-when .  	    walk-cddr)
    (flet . 		    walk-flet)
    (function . 	    walk-function)
    (go . 		    nil)
    (if . 		    walk-cdr) ; also walk test form
    (labels . 		    walk-flet)
    (let . 		    walk-let)
    (let* . 		    walk-let)
    (load-time-value .      nil)
    (locally .              walk-cdr-with-declarations)
    ;(macrolet . 	    walk-macrolet) ; uncomment to raise error
    (multiple-value-call .  walk-cdr)
    (multiple-value-prog1 . walk-cdr)
    (progn . 		    walk-progn)
    (progv . 		    walk-cdr)
    (quote . 		    nil)
    (return-from . 	    walk-cddr)
    (setq . 		    walk-setq)
    (symbol-macrolet . 	    walk-cddr-with-declarations)
299
    (tagbody . 		    walk-tagbody)
Attila Lendvai's avatar
Attila Lendvai committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    (the . 		    walk-cddr)
    (throw . 		    walk-cdr) 
    (unwind-protect . 	    walk-cdr)

    ;; Next some special cases:
    ;; m-v-b is a macro, not a special form, but we want to recognize bindings.
    ;; Furthermore, Lispworks macroexpands m-v-b into some unknown m-v-BIND-call special form.
    (multiple-value-bind .  walk-multiple-value-bind)
    ;; Allegro treats cond as a special form, it does not macroexpand.
    #+allegro (cond .	    walk-cond)
    ;; Prior to 2005, CLISP expanded handler-bind into some
    ;; sys::%handler-bind syntax not declared as a special operator.
    #+clisp (handler-bind . walk-cddr) ; does not recognize clauses in handlers
    ;; A suitable generalization would be a pattern language that describes
    ;; which car/cdr are forms to be walked, declarations or structure.
    ;; Walk with-*-iterator ourselves in order to avoid macrolet warnings.
    ;; Note that walk-cddr-with-declarations won't walk the
    ;; package/hash-table descriptor argument, but it's good enough for now.
    (with-package-iterator    . walk-cddr-with-declarations)
    (with-hash-table-iterator . walk-cddr-with-declarations)

    ;; Finally some cases where code compiled from the macroexpansion
    ;; may not be as good as code compiled from the original form:
    ;; -- and iterate's own expansion becomes more readable
    (and .		    walk-cdr)
    (ignore-errors .	    walk-cdr) ; expands to handler-bind in CLISP
    (multiple-value-list .  walk-cdr)
    (multiple-value-setq .  walk-cddr)
    (nth-value .	    walk-cdr)
    (or .		    walk-cdr)
    (prog1 .		    walk-cdr)
    (prog2 .		    walk-cdr)
    (psetq . 		    walk-setq)))


;;; For clauses that are "special" in the sense that they don't conform to the
;;; keyword-argument syntax of Iterate clauses.

(defvar *special-clause-alist* nil)


;;; These two are for conserving temporaries.  *temps* is a list
;;; of temporaries that have already been created and given bindings.
;;; *temps-in-use* is a list of temporaries that are currently being used.
;;; See with-temporary, with-temporaries.
;;; This seems to stem from a time where it was more efficient to use
;;; (prog (temp)
;;;    ... (setq temp #) ; somewhere deep inside the body
;;;        (foo temp)
;;;        (bar temp)
;;;    ...)
;;; than using a local let deep inside that body, as in
;;; (tagbody ... (let ((temp #)) (foo temp) (bar temp)) ...)
;;; which may be be easier for compiler data flow and lifetime analysis.

(defvar *temps*)
(defvar *temps-in-use*)

;;; This is the environment, for macroexpand.

(defvar *env*)

;;; This is a list of information about drivers, for use by the NEXT
;;; mechanism. 

(defvar *driver-info-alist*)

;;; This is used by the PREVIOUS mechanism.

(defvar *previous-vars-alist*)


;;; Loop labels

(defvar *loop-top*)
(defvar *loop-step*)
(defvar *loop-end*)

;;; Whether a label was used, to avoid generating them.  This is so we don't
;;; get a warning from compilers that check for unused tags.

(defvar *loop-step-used?*)
(defvar *loop-end-used?*)

;;; Things that we should wrap the loop's body in

(defvar *loop-body-wrappers*)

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;



(eval-when (:compile-toplevel :load-toplevel :execute)

;;; Clause-info structures, which are put in the clause index.
  (defstruct clause-info
    function
    keywords
    req-keywords
    doc-string
    generator?)

;;; Driver-info structures, for information about driver variables--used by
;;; NEXT.

  (defstruct driver-info
    next-code
    generator?
    (used nil))

;;; Previous-info structures, used by the PREVIOUS mechanism.

  (defstruct previous-info
    var
    save-info-list
    code
    (class :step))

  (defstruct save-info
    save-var
    save-vars
    iv-ref)

  )

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Macros.

(eval-when (:compile-toplevel :load-toplevel :execute)  ;; Allegro needs this 

#+nil ;; unused
(defmacro assertion (test)
  `(if (not ,test) (bug "Assertion ~a failed" ',test)))

(defmacro augment (var stuff)
  `(setf ,var (nconc ,var ,stuff)))

(defmacro prepend (stuff var)
  `(setf ,var (nconc ,stuff ,var)))

) ;end eval-when

442 443 444 445 446 447 448 449
(eval-when (:compile-toplevel :load-toplevel :execute)

(defun list-of-forms? (x)
  (and (consp x) (consp (car x))
       (not (eq (caar x) 'lambda))))

) ;end eval-when

Attila Lendvai's avatar
Attila Lendvai committed
450 451 452 453 454 455 456 457 458 459 460
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SharpL. 
;;;
;;; the #L reader macro is an abbreviation for lambdas with numbered
;;; arguments, with the last argument being the greatest numbered
;;; argument that is used in the body.  Arguments which are not used
;;; in the body are (declare ignore)d.
;;;
;;; e.g. #L(list !2 !3 !5) is equivalent to:
;;;      (lambda (!1 !2 !3 !4 !5) (declare (ignore !1 !4)) (list !2 !3 !5))

461
(eval-when (:compile-toplevel :execute)
Attila Lendvai's avatar
Attila Lendvai committed
462

463
  (defun sharpL-reader (stream subchar n-args)
Attila Lendvai's avatar
Attila Lendvai committed
464
    (declare (ignore subchar))
465 466 467 468 469 470 471 472 473
    ;; Depending how an implementation chooses to expand `(,!1 (get-free-temp))
    ;; at read-time, it might be a macro that must be expanded before groveling
    ;; the resultant sexpr. Here it gets expanded in the null environment for
    ;; lack of anything better. If the macro is sensitive to its lexical
    ;; environment, it suggests perhaps an inappropriate use of #L.
    ;; However, to support unforseen cases, we will use the original form as
    ;; read for the resulting lambda's body. Moreover, rather than stuff new
    ;; atoms into the body which is impossible if the representation is opaque,
    ;; redirect "!" vars onto gensyms using SYMBOL-MACROLET.
Attila Lendvai's avatar
Attila Lendvai committed
474
    (let* ((form (read stream t nil t))
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	   (refd-!vars (sort (bang-vars (macroexpand form))
                             #'< :key #'bang-var-num))
	   (bang-var-nums (mapcar #'bang-var-num refd-!vars))
	   (max-bv-num (if refd-!vars (car (last bang-var-nums)) 0)))
      (cond ((null n-args)
             (setq n-args max-bv-num))
            ((< n-args max-bv-num)
             (error "#L: digit-string ~d specifies too few arguments" n-args)))
      (let* ((all-!vars (loop for i from 1 to n-args collect (make-bang-var i)))
	     (formals (mapcar (lambda (x) (declare (ignore x)) (gensym))
                              all-!vars)))
	`#'(lambda ,formals
             ,@(let ((ignore (mapcan (lambda (!var tempvar)
                                       (unless (member !var refd-!vars)
                                         (list tempvar)))
                                     all-!vars formals)))
                 (if ignore `((declare (ignore ,@ignore)))))
             (symbol-macrolet ,(mapcan (lambda (!var tempvar)
                                         (when (member !var refd-!vars)
                                           (list (list !var tempvar))))
                                       all-!vars formals)
               ,@(if (list-of-forms? form) form (list form)))))))
Attila Lendvai's avatar
Attila Lendvai committed
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

  (defun make-bang-var (n)
    (intern (format nil "!~d" n)))

  (defun bang-vars (form)
    (delete-duplicates (bang-vars-1 form '()) :test #'eq))

  (defun bang-vars-1 (form vars)
    (cond
      ((consp form)
       (bang-vars-1 (cdr form)
		    (bang-vars-1 (car form) vars)))
      ((and (symbolp form) (bang-var? form)) (cons form vars))
      (t vars)))

  (defun bang-var? (sym)
    (char= (char (symbol-name sym) 0) #\!))

  (defun bang-var-num (sym)
    (let ((num (read-from-string (subseq (symbol-name sym) 1))))
      (if (not (and (integerp num) (> num 0)))
	  (error "#L: ~a is not a valid variable specifier" sym)
	  num)))

521 522
  (defun enable-sharpL-reader ()
    (set-dispatch-macro-character #\# #\L #'sharpL-reader))
523 524 525 526

  ;; According to CLHS, *readtable* must be rebound when compiling
  ;; so we are free to reassign it to a copy and modify that copy.
  (setf *readtable* (copy-readtable *readtable*))
527
  (enable-sharpL-reader)
528 529 530 531 532 533 534 535

  ) ; end eval-when

#|
;; Optionally set up Slime so that C-c C-c works with #L
#+#.(cl:when (cl:find-package "SWANK") '(:and))
(unless (assoc "ITERATE" swank:*readtable-alist* :test #'string=)
  (bind ((*readtable* (copy-readtable *readtable*)))
536
    (enable-sharpL-reader)
537 538
    (push (cons "ITERATE" *readtable*) swank:*readtable-alist*)))
;|#
Attila Lendvai's avatar
Attila Lendvai committed
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The ITERATE macro.


(defmacro iterate (&body body)
  "Jonathan Amsterdam's powerful iteration facility"
  `(iter .,body))

(defmacro iter (&body body &environment env)
  "Jonathan Amsterdam's powerful and extensible iteration facility,
providing multiple accumulation, generators, memory of previous
iterations, over 50 clauses to start with and a Lisp-like syntax.
Evaluate (iterate:display-iterate-clauses) for an overview of clauses"
  (let* ((*env* env)
	 (*result-var* (genvar 'result))
	 (*type-alist* nil)
	 (*declare-variables* *always-declare-variables*)
	 (*bindings* nil)
	 (*internal-variables* nil)
	 (*previous-vars-alist* nil)
	 (*declarations* nil)
	 (*loop-body-wrappers* nil)
	 (*accum-var-alist* nil)
563
         (*shared-bindings-alist* nil)
Attila Lendvai's avatar
Attila Lendvai committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
	 (*top-level?* t)
	 (*binding-context?* nil)
	 (*temps* nil)
	 (*temps-in-use* nil)
	 (*driver-info-alist* nil)
	 (*block-name* (if (symbolp (car body))
			   (pop body)
			   nil))
	 (*loop-top* (symbol-append 'loop-top- *block-name*))
	 (*loop-step* (symbol-append 'loop-step- *block-name*))
	 (*loop-end* (symbol-append 'loop-end- *block-name*))
	 (*loop-step-used?* nil)
	 (*loop-end-used?* nil))
    (process-top-level-decls body)
    (multiple-value-bind (body decls init-code steppers final-code final-prot)
	(walk-list body)
      (multiple-value-bind (init step)
	  (insert-previous-code)
	(augment init-code init)
	(augment steppers step))
      (prepend (default-driver-code) body)
      (let ((it-bod `(block ,*block-name*
		      (tagbody
587
			 (progn ,.init-code)
Attila Lendvai's avatar
Attila Lendvai committed
588
			 ,*loop-top*
589
			 (progn ,.body)
Attila Lendvai's avatar
Attila Lendvai committed
590
			 ,.(if *loop-step-used?* (list *loop-step*))
591
			 (progn ,.steppers)
Attila Lendvai's avatar
Attila Lendvai committed
592 593
			 (go ,*loop-top*)
			 ,.(if *loop-end-used?* (list *loop-end*))
594
			 (progn ,.final-code))
Attila Lendvai's avatar
Attila Lendvai committed
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
		      ,(if (member *result-var* *bindings* :key #'car)
			   *result-var*
			   nil))))
	(wrap-form *loop-body-wrappers*
		   `(let* ,(nreverse *bindings*)
		     ,.(if *declarations*
			   `((declare .,*declarations*)))
		     ,.decls
		     ,(if final-prot 
			  `(unwind-protect ,it-bod .,final-prot)
			  it-bod)))))))

(defmacro defmacro-clause (clause-template &body body)
  "Create your own iterate clauses"
  (define-clause 'defmacro clause-template body nil))

(defmacro defmacro-driver (clause-template &body body)
  "Create iterators which may also be used as generators"
  (define-clause 'defmacro clause-template body t))

;;;;;;;;;;;;;;;;

(defun process-top-level-decls (clauses)
  ;; This sets *type-alist* to an alist of (var . type), and
  ;; sets *declare-variables* to t if such a declaration was seen.
  (dolist (clause clauses)
    (when (and (consp clause) (eq (car clause) 'declare))
      (dolist (spec (cdr clause))
	(cond
	 ((eq (first spec) 'declare-variables)
	  (setq *declare-variables* t))
	 ((or (eq (first spec) 'type)  ; We don't do ftypes
	      ;; FIXME recognize all shorthand type declarations
	      ;; e.g. (declare ((unsigned-byte 8) x) etc.
	      ;; -- but how to recognize type specifications?
	      (member (first spec) standard-type-symbols :test #'eq))
	  (let ((type (first spec))
		(vars (cdr spec)))
	    (if (eq type 'type)
		(setq type (pop vars)))
	    (dolist (var vars)
	      (push (cons var type) *type-alist*)))))))))


(defun default-driver-code ()
  nil)

(defun wrap-form (wrappers form)
       (if (consp wrappers)
           (wrap-form (cdr wrappers)
		      (nconc (copy-list (car wrappers))
	                     (list form)))
	   form))

(defun add-loop-body-wrapper (wrapper)
  (push wrapper *loop-body-wrappers* ))

;(defun default-driver-code ()
;  ;; Collect all non-generator code.
;  ;; [Old version: Collect all code not explicitly invoked with NEXT.]
;  (let ((code nil))
;    ;; Put list in same order as clauses
;    (setq *driver-info-alist* (nreverse *driver-info-alist*)) 
;    (dolist (entry *driver-info-alist*)
;      (let ((di (cdr entry)))
;	(when (not (driver-info-generator? di))
;	  (assert (not (driver-info-used di)))
;	  (augment code (copy-list (driver-info-next-code di))))
;	(if (and (driver-info-generator? di)
;		 (not (driver-info-used di)))
;	    (clause-warning "A generator was never used"))))
;    code))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The code walker.

(defun walk (form)
  ;; Returns the usual five things; body is a list of forms.
  (cond
   ((atom form) ; symbol-macrolet must not expand into Iterate clauses
    (list form))
   ((symbolp (car form))
    (cond
     ;; The ordering of these checks is such that:
     ;; 1. We handle special operators that any Common Lisp code walker
     ;;    must recognize.
     ;; 2. We handle some special cases like Allegro's cond
     ;; 3. Then we expand macros.
     ;; 4. Then only do we recognize Iterate clauses
     ;;    -- which may thus be shadowed
     ;;
     ;; Note that implementations are permitted to let SPECIAL-OPERATOR-P
     ;; return T for any macros (e.g. CLISP for WHEN). Yet they must provide
     ;; a macroexpansion for these.

     ((special-form? (car form))
      (walk-special-form form))
     ((macro-function (car form) *env*)
      ;; Some compilers (e.g. Lucid on Sparcs) treat macros differently at
      ;; compile-time; macroexpand does not expand them.  We assume that if
      ;; this happens, macroexpand's second value is nil.  
      ;;   What do we do with the form in that case?  This is actually a
      ;; very serious problem: if we don't walk it, we miss things, but if we
      ;; do walk it, we don't know how to walk it.  Right now, we don't walk
      ;; it and print out a warning.
      ;;  --Jeff Siskind says try binding *macroexpand-hook* to #'funcall.
      (multiple-value-bind (ex-form expanded?)
	  (macroexpand-1 form *env*)
	(cond
	 (expanded? (walk ex-form))
	 (t	    (clause-warning "The form ~a is a macro that won't expand. ~
  It will not be walked, which means that Iterate clauses inside it will ~
  not be seen."
				    form)
		    (list form)))))
      ((special-operator-p (car form))
       (clause-warning "Iterate does not know how to handle the special form ~s~%~
  It will not be walked, which means that Iterate clauses inside it will ~
  not be seen." form)
       (list form))
      ((starts-clause? (symbol-synonym (car form)))
       (process-clause form))     
      (t ;; Lisp function call 
       (return-code-modifying-body #'walk-arglist (cdr form)
				   #L(list (cons (car form) !1))))))
   ((lambda-expression? (car form))
    ;; Function call with a lambda in the car
    (multiple-value-bind (bod decs init step final final-prot)
	(walk-fspec (car form))
      (multiple-value-bind (abod adecs ainit astep afinal afinal-prot)
	  (walk-arglist (cdr form))
	(values (list (cons bod abod)) (nconc decs adecs) (nconc init ainit)
		(nconc step astep) (nconc final afinal) 
		(nconc final-prot afinal-prot)))))
   #+clisp ; some macros expand into ((setf foo) value other-args...)
   ;; reported by Marco Baringer on 24 Jan 2005
   ((typep form '(cons (cons (eql setf) *) *))
    (apply #'walk-cdr form))
   (t
    (clause-error "The form ~a is not a valid Lisp expression" form))))

(defun walk-list (forms)
  (walk-list-nconcing forms #'walk))

(defun walk-arglist (args)
  (let ((*top-level?* nil))
    (walk-list-nconcing args #'walk  #L(if (is-iterate-clause? !1)
					   (list (prognify !2))
					   !2))))

(defun walk-fspec (form)
  ;; Works for lambdas and function specs in flet and labels.
  ;; FORM = (LAMBDA-or-name args . body)
  ;; We only walk at the body.  The args are set up as internal variables.
  ;; Declarations are kept internal to the body.
  (let* ((args (second form))
	 (body (cddr form))
	 (*top-level?* nil)
	 (*binding-context?* t)
	 (*internal-variables* (add-internal-vars args)))
    (multiple-value-bind (bod decs init step final finalp)
	(walk-list body)
      (values `(,(first form) ,args ,.decs ,.bod) nil init step final 
	      finalp))))

(defun walk-list-nconcing (list walk-fn 
				&optional (body-during #L!2))
  (let (body-code decls init-code step-code final-code finalp-code)
    (dolist (form list)
      (declare (optimize (speed 0)))
      (multiple-value-bind (body decs init step final finalp)
	  (funcall walk-fn form)
	(augment decls decs)
	(augment init-code init)
	(augment body-code (funcall body-during form body))
	(augment step-code step)
	(augment final-code final)
	(augment finalp-code finalp)))
    (values body-code decls init-code step-code final-code
	    finalp-code)))

(defun return-code-modifying-body (f stuff mod-f)
  (declare (optimize (speed 0)))
  (multiple-value-bind (bod decs init step final finalp)
      (funcall f stuff)
    (values (funcall mod-f bod) decs init step final finalp)))


(defun add-internal-var (var)
  ;; VAR can be a symbol or a list (symbol ...).
  (cons (if (consp var) (car var) var) *internal-variables*))

(defun add-internal-vars (vars)
  ;; VARS could be a lambda-list, a list of LET bindings, or just a list of
  ;; variables; all will work.
  (nconc (lambda-list-vars vars) *internal-variables*))

(defun lambda-list-vars (lambda-list)
  ;; Return the variables in the lambda list, omitting keywords, default
  ;; values.
  (mapcan #'(lambda (thing)
	      (cond
	       ((consp thing)
		(if (consp (car thing)) ; this is a full keyword spec
		    (list (second (car thing)))
		    (list (car thing))))
	       ((not (member thing lambda-list-keywords))
		(list thing))))
	  lambda-list))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Special forms.

(defun special-form? (symbol)
  ;; special-operator-p doesn't work in Lucid--it returns NIL for let, for
  ;; example.  Plus, we want to catch Iterate special clauses.
  (assoc symbol *special-form-alist*))

(defun walk-special-form (form)
  (let ((*clause* form)
	(func (cdr (assoc (car form) *special-form-alist*))))
    (if (null func)    ; there's nothing to transform
	(list form)
	(apply func form))))

#+nil
(defun walk-identity (&rest stuff)
  (list stuff))

(defun walk-cdr (first &rest stuff)
  ;; This is for anything where only the car isn't to be walked.
  (return-code-modifying-body #'walk-arglist stuff #L(list (cons first !1))))

(defun walk-cddr (first second &rest stuff)
  ;; This is for anything where the first two elements aren't to be walked.
  (return-code-modifying-body #'walk-arglist stuff
			      #L(list (cons first (cons second !1)))))

(defun walk-progn (progn &rest stuff)
  ;; The only difference between this and walk-cdr is that *top-level* is not
  ;; bound.  This is so macros can return PROGNs of things.  It's exactly like
  ;; the definition of "top-level" in lisp. 
  ;; (Also, just for looks, this returns nil if the progn is empty.)
  (return-code-modifying-body #'walk-list stuff 
			      #L(if (null !1)
				    nil
				    (list (cons progn !1)))))

(defun walk-setq (setq &rest things)
  ;; Walk every other thing.
  (let ((*top-level?* nil)
	(i 1)
	body-code decls init-code step-code final-code finalp-code)
    (dolist (thing things)
      (if (oddp i)
	  (push thing body-code)
	  (multiple-value-bind (body decs init step final finalp)
	      (walk thing)
	    (augment decls decs)
	    (augment init-code init)
	    (push (prognify body) body-code)
	    (augment step-code step)
	    (augment final-code final)
	    (augment finalp-code finalp)))
      (incf i))
    (values (list (cons setq (nreverse body-code)))
	    decls init-code step-code final-code finalp-code)))

(defun walk-function (function form)
  (if (lambda-expression? form)
      (return-code-modifying-body #'walk-fspec form #L(list 
						       (list function !1)))
      (list (list function form))))

(defun walk-declare (&rest declaration)
  ;; DECLARE is a declaration, and should be put in the declaration
  ;; section of the loop.  Declarations are only allowed at top-level,
  ;; except that they are allowed within binding environments, in which case
  ;; they apply only to that binding environment.
  #+ symbolics (setq declaration (copy-list declaration))
  (if (or *top-level?* *binding-context?*)
      (return-code :declarations (list declaration)) 
      (clause-error "Declarations must occur at top-level, or inside a ~
  binding context like let or multiple-value-bind.")))

(defun walk-let (let bindings &rest body)
  ;; The bindings or body may contain iterate clauses.
  ;; Important: the decls go inside this let, not at top-level.
  ;; It is an error to use a variable in the let bindings as the
  ;; target of an accumulation (i.e. INTO), because iterate will try
  ;; to make a top-level binding for that variable.  The same goes for
  ;; other variables that might be so bound.
  (let ((*top-level?* nil))
    (multiple-value-bind (binds b-decls b-init b-step b-final b-finalp)
	(walk-let-bindings let bindings)
      (let ((*binding-context?* t)
	    (*internal-variables* (add-internal-vars binds)))
	(multiple-value-bind (bod decls init step final finalp)
	    (walk-list body)
	  (return-code :declarations b-decls
		       :initial (nconc b-init init)
		       :body (list `(,let ,binds ,.decls ,.bod))
		       :step (nconc b-step step)
		       :final (nconc b-final final)
		       :final-protected (nconc b-finalp finalp)))))))

(defun walk-let-bindings (let bindings)
  (if (eq let 'let)
      (walk-list-nconcing bindings #'walk-let-binding #L(list !2))
      (walk-let*-bindings bindings)))


(defun walk-let*-bindings (bindings)
  ;; We have to do this one binding at a time, to get the variable scoping
  ;; right.
  (if (null bindings)
      nil
      (multiple-value-bind (bod decls init step final finalp)
	  (walk-let-binding (car bindings))
	(let ((*internal-variables* (add-internal-var (car bindings))))
	  (multiple-value-bind (bod1 decls1 init1 step1 final1 finalp1)
	      (walk-let*-bindings (cdr bindings))
	    (values (cons bod bod1) (nconc decls decls1) (nconc init init1)
		    (nconc step step1) (nconc final final1)
		    (nconc finalp finalp1)))))))

      
(defun walk-let-binding (binding)
  (if (consp binding)
      (multiple-value-bind (bod decls init step final finalp)
	  (walk (second binding))
	(values (list (first binding) (prognify bod)) decls init step final
		finalp))
      binding))
    
(defun walk-multiple-value-bind (mvb vars expr &rest body)
  ;; Important: decls go inside the mvb, not at top-level.  See
  ;; walk-let for binding subtleties.
  (declare (ignore mvb))
  (let ((*top-level?* nil))
    (multiple-value-bind (ebod edecls einit estep efinal efinalp)
	(walk expr)
      (let ((*binding-context?* t)
	    (*internal-variables* (add-internal-vars vars)))
	(multiple-value-bind (bod decls init step final finalp)
	    (walk-list body)
	  (return-code :declarations edecls
		       :initial (nconc einit init)
		       :body (list `(multiple-value-bind ,vars
					,(prognify ebod)
				      ,.decls ,.bod))
		       :step (nconc estep step)
		       :final (nconc efinal final)
		       :final-protected (nconc efinalp finalp)))))))

(defun walk-flet (flet bindings &rest body)
  ;; For FLET or LABELS.  We don't worry about the function bindings.
  (let ((*top-level?* nil))
    (multiple-value-bind (binds b-decls b-init b-step b-final b-finalp)
	(walk-list-nconcing bindings #'walk-fspec #L(list !2))
      (let ((*binding-context?* t))
        (multiple-value-bind (bod decls init step final finalp)
	    (walk-list body)
	  (return-code :declarations b-decls
		       :initial (nconc b-init init)
		       :body (list `(,flet ,binds ,.decls ,.bod))
		       :step (nconc b-step step)
		       :final (nconc b-final final)
		       :final-protected (nconc b-finalp finalp)))))))

(defun walk-cdr-with-declarations (first &rest stuff) ; aka walk-locally
  ;; Set *top-level?* false (via walk-arglist).
  ;; Note that when *top-level?* is false, walk won't yield declarations
  ;; because walk-declare errors out since all forms with
  ;; *declaration-context?* true keep them local (that is, in walk-let,
  ;; walk-flet and walk-multiple-value-bind b-decls/edecls are always NIL).
  ;; Ignoring code-movement issues, this approach should be fine.
  (let* ((forms (member 'declare stuff :key #L(if (consp !1) (car !1))
			:test-not #'eq))
	 (decls (ldiff stuff forms)))
    (return-code-modifying-body #'walk-arglist forms
				#L(list (cons first (nconc decls !1))))))

(defun walk-cddr-with-declarations (first second &rest stuff)
  (let* ((forms (member 'declare stuff :key #L(if (consp !1) (car !1))
			:test-not #'eq))
	 (decls (ldiff stuff forms)))
    (return-code-modifying-body #'walk-arglist forms
				#L(list (cons first (cons second (nconc decls !1)))))))

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
(defun walk-tagbody (tagbody &rest statements)
  (flet ((walk-statements (statements)
	   (walk-list-nconcing
	    statements
	    #L(if (atom !1) (list !1) (walk !1))
	    #'(lambda (form body)
		(cond ((atom form) body)
		      ;; wrap statements which expand into an atom
		      ((typep body '(cons atom null))
		       (list (cons 'progn body)))
		      (t body))))))
    (let ((*top-level?* nil))
      (return-code-modifying-body
       #'walk-statements statements
       #L(list (cons tagbody !1))))))
Attila Lendvai's avatar
Attila Lendvai committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330

(defun walk-macrolet (form-name &rest stuff)
  (declare (ignore stuff))
  (error "~A is not permitted inside Iterate. Please ~
  refactor the Iterate form (e.g. by using ~As that wrap ~
  the ITERATE form)." form-name form-name))

#+allegro
(defun walk-cond (cond &rest stuff)
  ;; Because the allegro compiler insists on treating COND as a special form,
  ;; and because some version macroexpands (cond #) into (cond #)!
  (declare (ignore cond))
  (if (null stuff)
      nil
      (let* ((first-clause (first stuff))
	     (test (if (not (consp first-clause))
		       (error "cond clause ~a is not a list" first-clause)
		       (car first-clause)))
	     (thens (cdr first-clause))
	     (if-form (if (null thens)
			  (let ((var (gensym)))
			    `(let ((,var ,test))
			      (if ,var ,var (cond ,@(cdr stuff)))))
			  `(if ,test (progn ,@thens) (cond ,@(cdr stuff))))))
	(walk if-form))))
			    


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Processing Iterate clauses.

(defvar *initial*)
(defvar *decls*)
(defvar *step*)
(defvar *final*)
(defvar *finalp*)

(defun process-clause (clause)
  ;; This should observe the invariant that the forms it returns are
  ;; already copied from the original code, hence nconc-able.  
  (let ((*clause* clause)
	(special-func (assoc (car clause) *special-clause-alist*)))
    (if special-func
	(apply-clause-function (car clause) (cdr clause))
	(let* ((ppclause (preprocess-clause clause))
	       (info (get-clause-info ppclause)))
	  (cond
	   (info
	    (arg-check ppclause info)
	    (let ((args (cons (keywordize (first ppclause))
			      (cdr ppclause)))
		  (func (clause-info-function info)))
	      (if (macro-function func *env*)
		  (walk (macroexpand-1 (cons func args) *env*))
		  (apply-clause-function func args))))
	   (t
	    (clause-error "No iterate function for this clause; do ~
  (~S) to see the existing clauses." 'display-iterate-clauses)))))))

(defun apply-clause-function (func args)
  (let ((*initial* nil)
	(*decls* nil)
	(*step* nil)
	(*final* nil)
	(*finalp* nil))
    (declare (optimize (speed 0)))
    (multiple-value-bind (body decls init step final finalp)
	(apply func args)
      (values body 
	      (nconc *decls* decls)  
	      (nconc *initial* init)
	      (nconc *step* step)
	      (nconc *final* final)
	      (nconc *finalp* finalp)))))
  
(defun preprocess-clause (clause)
  ;; First, check for errors.
  ;; Then, turn every other symbol except the first into a keyword,
  ;; and replace synonyms occurring as the first keyword.
  (do ((cl clause (cddr cl)))
      ((null cl))
    (if (not (symbolp (car cl)))
	(clause-error "~a should be a symbol" (car cl)))
    (if (null (cdr cl))
	(clause-error "Missing value for ~a keyword" (car cl))))
  (let ((new-clause nil)
	(syn (symbol-synonym (first clause))))
    (do ((cl (cddr clause) (cddr cl)))
	((null cl))
      (push (keywordize (first cl)) new-clause)
      (push (second cl) new-clause))
    ;; Hack so that (generate ...) turns into (for ... :generate t)
    (if (eq syn 'generate)
	`(for  ,(second clause) ,.(nreverse new-clause) :generate t)
	`(,syn ,(second clause) ,.(nreverse new-clause)))))


(defun symbol-synonym (symbol)
  (or (get symbol 'synonym) symbol))

(eval-when (:compile-toplevel :load-toplevel :execute)

(defun listify (x)
  (if (listp x) x (list x)))

(defun keywordize (symbol)
  (intern (symbol-name symbol) :keyword))

);end eval-when

(defun arg-check (clause info)
  ;; Make sure that each keyword in clause is in info.
  (let ((keywords (clause-info-keywords info)))
    (do ((cl clause (cddr cl)))
	((null cl))
      (if (null (cdr cl))
	  (clause-error "Missing a value for ~a" (car cl)))
      (if (not (member (car cl) keywords :test #'eq))
	  (if (eq (car cl) :generate)
	      (if (not (clause-info-generator? info))
		  (clause-error "Clause cannot be used as a generator"))
	      (clause-error "Unknown keyword ~a" (car cl)))))))

(defun walk-expr (expr)
  ;; This isn't used by the code walker itself, but is useful for clauses that
  ;; need to walk parts of themselves.  It always returns a single expression.
  ;; The other parts are collected using globals and returned by
  ;; process-clause. 
  (multiple-value-bind (body decls init step final finalp)
      (walk expr)
    (augment *decls* decls)
    (augment *initial* init)
    (augment *step* step)
    (augment *final* final)
    (augment *finalp* finalp)
    (prognify body)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Displaying clauses.

(defun display-iterate-clauses (&optional clause-spec)
  (fresh-line)
  (if (and clause-spec (symbolp clause-spec))
      (setq clause-spec (list clause-spec)))
  (if (member '&optional clause-spec)
      (error "Iterate: clause-spec cannot mention optional keywords"))
  (if clause-spec
      (setq clause-spec (cons (car clause-spec)
			      (mapcar #'keywordize (cdr clause-spec)))))
  (dolist (spec-entry *special-clause-alist*)
    (let ((spec-clause-kws (list (car spec-entry))))
      (if (clause-matches? clause-spec spec-clause-kws)
	  (display-clause spec-clause-kws (cdr spec-entry)))))
  (disp-std-clauses clause-spec *clause-info-index*)
  t)

(defun disp-std-clauses (clause-spec index)
  (if (index? index)
      (dolist (entry (cdr index))
	(disp-std-clauses clause-spec (cdr entry)))
      (if (clause-matches? clause-spec (clause-info-keywords index))
	  (display-clause (clause-info-keywords index)
			  (clause-info-doc-string index)))))
  
(defun display-clause (kws doc-string)
  (display-kws kws)
  (if doc-string
      (format t "~25,4t ~a~%" doc-string)
      (terpri)))


(defconst fill-col 77)

(defun display-kws (kws)
  (do* ((col 1)
	(kw-list kws (cdr kw-list))
	(kw (car kw-list) (car kw-list)))
      ((null kw-list))
    (let ((len (length (symbol-name kw))))
      (when (>= (+ col len) fill-col)
	(format t "~%~4t")
	(setq col 4))
      (if (= col 1) ; the first one--print package name
	  (format t "~s" kw)
	  (format t "~a" kw))
      (incf col len)
      (when (cdr kw-list) 
	(cond
	 ((>= (+ col 1) fill-col)
	  (format t "~%~4t")
	  (setq col 4))
	 (t
	  (format t " ")
	  (incf col)))))))
      

(defun clause-matches? (clause-spec kws)
  (or (null clause-spec)
      (every #'eq clause-spec kws)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Indexing of clause functions.

;;; Each clause has one or more required keywords, which must
;;; appear in order, and zero or more optional keywords, which may be
;;; omitted and may appear in any order.   

;;; The first word of a clause, though used as a keyword when the
;;; clause function is called, is kept in its original package for
;;; indexing purposes.  This provides iterate's interface with the
;;; package system.

;;; Two clauses can be ambiguous when 1) they have the same list of required
;;; keywords, or 2) #1's required-list is a prefix of #2's and #1 has optional
;;; keywords which match the remaining keywords of #2's required-list.  We
;;; check for these situations and signal an error.

;;; Indexing scheme: basically a discrimination tree.  There is a tree
;;; of alists with root *clause-info-index*.

(defun get-clause-info (clause &optional (index *clause-info-index*))
  (let ((entry (cdr (index-lookup (car clause) index))))
    (if (index? entry)
	(let ((result (get-clause-info (cddr clause) entry)))
	  ;; It could be that the required part of the clause ends here.
	  (or result (get-clause-info nil entry)))
	entry)))
      

(defun is-iterate-clause? (form)
  (and (consp form)
       (symbolp (car form))
       (starts-clause? (car form))))


(defun starts-clause? (symbol)
  ;; A symbol starts a clause if it appears in the top-level index, or if it
  ;; is in the special-clause alist, or if it is GENERATE.
  ;;   This is used to distinguish the case where there's a lisp form
  ;; (in which case the symbol doesn't start a clause), versus the
  ;; situation where an erroneous clause is provided.
  (or (assoc symbol *special-clause-alist*)
      (index-lookup symbol *clause-info-index*)
      (eq symbol 'generate)))

;;; The code generated by DEFINE-CLAUSE (below) is the only code that
;;; invokes this.

(eval-when (:compile-toplevel :load-toplevel :execute)

(defun install-clause-info (req-keywords keywords function doc-string 
			    generator?)
  (install-clause-info-1 req-keywords *clause-info-index* 
			 (make-clause-info :function function
					   :keywords keywords
					   :req-keywords req-keywords
					   :doc-string doc-string
					   :generator? generator?)))


(defun install-clause-info-1 (keywords index info)  
  ;; Here, KEYWORDS is a list of the required keywords.
  ;; The basic rule here is to build indices all the way out to the
  ;; end of the list of keywords.  That way it will be necessary for
  ;; the user's clause to contain all of the required keywords.
  ;;   If index contains no entry for the first keyword, build a full
  ;; set of indices and put it in index.  
  ;;   If there is an entry and it's an index, call recursively.
  ;;   If there's an entry and it's not an index, then we have a case of
  ;; duplication or prefix.  If duplication, we replace and warn; if
  ;; prefix, we check for ambiguity, and if so, error.
  (if (null keywords)
      (ambiguity-check-index info index))
  (let ((entry (index-lookup (car keywords) index)))
    (cond
     ((null entry)
      (index-add (car keywords) (build-index (cdr keywords) info) index))
     ((index? (cdr entry))
      (install-clause-info-1 (cdr keywords) (cdr entry) info))
     ((clause-info-p (cdr entry))
      (cond
       ((null (cdr keywords))
	;; Duplication; warn if they are not completely identical.
	(unless (equal (clause-info-keywords (cdr entry))
		       (clause-info-keywords info))
	  (warn "replacing clause ~a~%with ~a"
		(clause-info-keywords (cdr entry))
		(clause-info-keywords info)))
	(setf (cdr entry) info))
       (t
	(ambiguity-check-clause (cdr entry) info 2)
	;; Replace this entry with an index.
	(let ((index2 (build-index (cdr keywords) info)))
	  (index-add nil (cdr entry) index2)
	  (setf (cdr entry) index2)))))
     (t
      (bug "install-clause-info-1: index is broken")))))
	

(defun build-index (keywords info)
  (if (null keywords)
      info
      `(:index (,(car keywords) . ,(build-index (cdr keywords) info)))))
		 
(defun index? (x)
  (and (consp x) (eq (car x) :index)))

(defun index-add (key thing index)
  (push (cons key thing) (cdr index)))

(defun index-lookup (item index)
  (assoc item (cdr index) :test #'eq))

(defun ambiguity-check-index (ci1 index)
  ;; We're trying to add CI1, and we have to check it against all the things
  ;; in INDEX.
  (dolist (entry (cdr index))
    (if (clause-info-p (cdr entry))
	(ambiguity-check-clause ci1 (cdr entry) 1)
	(ambiguity-check-index ci1 (cdr entry)))))

(defun ambiguity-check-clause (ci1 ci2 insert-n)
  ;; It is known that the required keywords of CI1 are a prefix of those
  ;; of CI2, and that we are trying to add INSERT-N (1 or 2).
  (if (ambiguous-clauses? ci1 ci2)
      (let ((kw1 (clause-info-keywords ci1))
	    (kw2 (clause-info-keywords ci2)))
	(if (= insert-n 2)
	    (rotatef kw1 kw2))
1331 1332
	(restart-case
            (error "Iterate: Inserting clause ~a would create ~
Attila Lendvai's avatar
Attila Lendvai committed
1333
  an ambiguity with clause ~a"
1334 1335 1336 1337
                   kw1 kw2)
          (delete-conflict ()
            :report "Delete the original clause"
            (remove-clause kw2))))))
Attila Lendvai's avatar
Attila Lendvai committed
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566


(defun ambiguous-clauses? (ci1 ci2)
  ;; rk1 is a prefix of rk2
  (let* ((rk1 (clause-info-req-keywords ci1))
	 (rk2 (clause-info-req-keywords ci2))
	 (rest-rk2 (nthcdr (length rk1) rk2))
	 (ok1 (cdr (member '&optional (clause-info-keywords ci1)))))
    (if (null rest-rk2)
	nil     ; Don't consider identical clauses ambiguous--that will be
		; handled elsewhere.
	(dolist (k2 rest-rk2 t)
	  (if (not (member k2 ok1))
	      (return nil))))))

	  
	  
) ;end eval-when


(defun display-index (&optional (index *clause-info-index*) (indent 0))
  ;; for debugging
  (if (not (index? index))
      (format t "~vt~a~%" indent (clause-info-keywords index))
      (dolist (entry (cdr index))
	(format t "~vt~a:~%" indent (car entry))
	(display-index (cdr entry) (+ indent 2)))))

(defun remove-clause (clause-keywords)
  ;; CLAUSE-KEYWORDS is a list that (once the symbols have been
  ;; keywordized) should be equal to some clause in the index.
 (let* ((all-keywords
	 (cons (first clause-keywords)
	       (mapcar #L(if (eq !1 '&optional) !1 (keywordize !1))
		       (rest clause-keywords))))
	(req-keywords
	 (ldiff all-keywords (member '&optional all-keywords :test #'eq))))
   (labels ((remove-clause-internal (keywords index)
	      (let ((entry (and keywords
				(index-lookup (car keywords) index))))
		(cond ((null entry)
		       (error "Clause ~a not found" clause-keywords))
		      ((clause-info-p (cdr entry))
		       (when (equal all-keywords 
				    (clause-info-keywords (cdr entry)))
			 ;; else warn that an &optional part is missing??
			 (rplacd index (delete entry (cdr index)))
			 t))
		      (t ;; an index
		       (prog1
			   (remove-clause-internal (cdr keywords) (cdr entry))
			 ;; if the index is empty, delete it too
			 (if (null (cddr entry))
			     (rplacd index (delete entry (cdr index))))))))))
     (remove-clause-internal req-keywords *clause-info-index*))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;  Macros and useful functions for defining new iterate clauses.

(defmacro defclause (clause-template &body body)
  (define-clause 'defun clause-template body nil))

(defmacro defclause-driver (clause-template &body body)
  (define-clause 'defun clause-template body t))


;  ;; This duplicates body, which is annoying but not serious.
;  (let* ((gen-clause-template (cons 'generate (cdr clause-template)))
;	 (for-body `((let ((generator? nil)) ,@body)))
;	 (gen-body `((let ((generator? t)) ,@body))))
;    (define-clause 'defun clause-template for-body)
;    (define-clause 'defun gen-clause-template gen-body)))

(eval-when (:compile-toplevel :load-toplevel :execute)
  (defconst sequence-keyword-list
    '(:from from :upfrom upfrom :downfrom downfrom :to to :downto downto
      :above above :below below :by (by 1) :with-index with-index))

  (defun define-clause (define-form clause-template body generator?)
    ;; CLAUSE-TEMPLATE is of the form 
    ;;  (<sym1> <spec1> ... [&optional <symk> <speck> ...] [&sequence])
    ;; The <sym> forms must be symbols (in any package); they are the
    ;; keywords for the clause. The <spec> forms are to be bound to the
    ;; values of those keywords when the clause is processed; such a
    ;; form can be either a symbol, a list (symbol initform), or a list
    ;; (symbol initform svar).  These are processed exactly as if they
    ;; were keyword specifiers.  To be precise, a pair of keyword and
    ;; value-form behaves exactly like the keyword specification
    ;; ((:keyword var) initform svar). 
    ;;   If the special symbol &sequence occurs, it must be the last
    ;; form.  It is equivalent to specifying all the sequence optional
    ;; symbols (FROM, TO, etc.), with specs of the same name (i.e. the
    ;; variable bound to the FROM keyword is "from", etc.).  There are
    ;; no defaults except that BY defaults to 1.
    ;;   The BODY is just an ordinary lisp body; it will refer to the 
    ;; value-forms in the clause template.  It should use return-code to
    ;; return the appropriate arguments.
    (if (null clause-template)
	(error "Iterate: empty clause template with body ~a" body))
    (flet ((make-keyword-spec (kw val)
	     (if (symbolp val)
		 `((,kw ,val))
		 `((,kw ,(car val)) ,@(cdr val)))))
      (let ((last (car (last clause-template))))
	(if (and (symbolp last) (string= last '&sequence))
	    (setq clause-template 
		  (nconc (butlast clause-template)
			 (if (member '&optional clause-template)
			     sequence-keyword-list
			     (cons '&optional sequence-keyword-list))))))
      (multiple-value-bind (rkws rvals okws ovals) 
	  (split-clause-template clause-template)
	(let* ((req-keywords (mapcar #'keywordize rkws))
	       (req-kws-but-first (cons (car clause-template)
					(cdr req-keywords)))
	       (opt-keywords (mapcar #'keywordize okws))
	       (keywords&opt (if opt-keywords
				 (append req-kws-but-first
					 '(&optional) opt-keywords)
				 req-kws-but-first))
	       (rkw-specs (mapcar #'make-keyword-spec req-keywords rvals))
	       (okw-specs (mapcar #'make-keyword-spec opt-keywords ovals))
	       (func-name (make-function-name rkws))
	       (doc-string (if (stringp (car body))
			       (car body)
			       nil))
	       (all-keywords (append req-keywords opt-keywords))
	       (arglist `(&key ,@rkw-specs ,@okw-specs)))
	  (if (contains-duplicates? all-keywords)
	      (error "While defining ~a: keyword list contains duplicates"
		     clause-template))
	  (if generator?
	      (augment arglist (list 'generate)))
	  ;; Actually define a named function, instead of using an
	  ;; anonymous lambda, to ensure that it gets compiled.  A
	  ;; compiler should compile a sharp-quoted lambda, but the
	  ;; Symbolics one doesn't.  Also, use the original first symbol
	  ;; of the clause for indexing.  This provides the following behavior
	  ;; re the package system: the first symbol of the user's clause
	  ;; must be eq to (hence in the same package as) the first symbol of
	  ;; the defined clause; but the packages of the other symbols don't
	  ;; matter.
	  `(eval-when (:compile-toplevel :load-toplevel :execute)
	     (,define-form ,func-name ,arglist .,body)
	     (install-clause-info ',req-kws-but-first
				  ',keywords&opt 
				  ',func-name
				  ,doc-string
				  ,generator?)
	     ',clause-template)))))

  (defun make-function-name (req-syms)
    (let ((req-string "CLAUSE-"))
      (dolist (sym req-syms)
	(setq req-string (concatenate 'string req-string (symbol-name sym) "-")))
      (gentemp req-string)))

  (defun split-clause-template (ct)
    ;; Splits template into required keywords, optional keywords and
    ;; values. 
    (let* ((opt&-list (member '&optional ct))
	   (req-list (ldiff ct opt&-list))
	   (opt-list (cdr opt&-list)))
      (if (zerop (length req-list))
	  (error "DEFCLAUSE: template ~a has no required part" ct))
      (if (oddp (length req-list))
	  (error "DEFCLAUSE: required part of template ~a is of odd length" ct))
      (if (oddp (length opt-list))
	  (error "DEFCLAUSE: optional part of template ~a is of odd length" ct))
      (multiple-value-bind (rkws rvals)
	  (split-list-odd-even req-list)
	(multiple-value-bind (okws ovals)
	    (split-list-odd-even opt-list)
	  (values rkws rvals okws ovals)))))
	

  (defun split-list-odd-even (list)
    ;; Splits list into odd- and even-numbered elements, returns
    ;; the odds and evens as two values.
    (do ((lis list (cddr lis))
	 (odds nil)
	 (evens nil))
	((null lis) (values (nreverse odds) (nreverse evens)))
      (push (car lis) odds)
      (push (cadr lis) evens)))

  (defun contains-duplicates? (list)
    (not (equal list (remove-duplicates list :test #'eq))))

  )					; end eval-when



(defmacro defsynonym (syn word)
  "Makes SYN a synonym for the existing iterate keyword WORD."
  `(eval-when (:compile-toplevel :load-toplevel :execute)
     (setf (get ',syn 'synonym) ',word)))



(defmacro defclause-sequence (element-name index-name 
			      &key access-fn size-fn
			      element-type sequence-type
			      element-doc-string index-doc-string)
  "A simple way to define a simple FOR ... &sequence clause"
  ;; Package subtlety: the FOR should be in the same package as the
  ;; element-name or index-name.
  (let* ((seq-for (if element-name 
		      (intern (symbol-name 'for) (symbol-package element-name))))
	 (seq-def (if element-name
		      `(defclause-driver (,seq-for var ,element-name seq 
						   &sequence)
			 ,element-doc-string
			 (return-sequence-code 
			  :element-var   var
			  :sequence      seq
			  :access-fn   ,access-fn
			  :size-fn     ,size-fn
			  :element-type  ,element-type
			  :sequence-type ,sequence-type))))
	 (inx-for (if index-name
		      (intern (symbol-name 'for) (symbol-package index-name))))
	 (inx-def (if index-name
		      `(defclause-driver (,inx-for var ,index-name seq 
						   &sequence)
			 ,index-doc-string
			 (cond 
			  (with-index
1567 1568
			   (clause-error
			    "WITH-INDEX should not be specified for this clause"))
Attila Lendvai's avatar
Attila Lendvai committed
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
			  (t
			   (setq with-index var)
			   (return-sequence-code
			    :sequence seq
			    :size-fn ,size-fn
			    :sequence-type ,sequence-type)))))))
    `(progn ,seq-def ,inx-def)))
			     
(defun if-1st-time (then &optional else first-time-var)
  ;; Returns 1: a form which evaluates THEN the first time through the
  ;; loop, ELSE subsequent times; 2: the variable that keeps track of
  ;; the first time.
  (let* ((var (or first-time-var 
		  (make-var-and-binding 'first-time t :type 'boolean)))
	 (code (if else
		   `(cond
		     (,var
		      (setq ,var nil)
		      ,@then)
		     (t
		      ,@else))
		   `(when ,var 
		      (setq ,var nil)
		      ,@then))))
    (values code var)))

;;; Deprecated.  Dangerous when incorrectly nested
(defmacro with-temporary (var &body body)
  (let ((old-var (gensym))
	(vars (listify var)))
    `(let ((,old-var *temps-in-use*))
       (unwind-protect
	   (let ,(mapcar #L`(,!1 (get-free-temp))
			 vars)
	     .,body)
	 (setq *temps-in-use* ,old-var)))))

#+nil ;; unused
(defmacro with-temporaries (n vlist &body body)
  (let ((old-var (gensym)))
    `(let ((,old-var *temps-in-use*))
       (unwind-protect
	   (let ((,vlist (let ((ts nil)) 
			   (dotimes (i ,n) 
			     (push (get-free-temp) ts))
			   ts)))
	      .,body)
	 (setq *temps-in-use* ,old-var)))))

(defun get-free-temp ()
  (let ((temp (some #L(if (not (member !1 *temps-in-use*)) !1)
		    *temps*)))
    (when (null temp)
      (setq temp (make-var-and-default-binding 'temp))
      (push temp *temps*))
    (push temp *temps-in-use*)
    temp))



;;;;;;;;;;;;;;;;
;;; Typing.

(defun var-type (var)
  (if (the-expression? var)
      (second var)
      (var-declaration var)))

(defun var-declaration (var)
  (cdr (assoc var *type-alist* :test #'eq)))

(defun expr-type-only (expr)
  ;; If expr is self-evaluating, return its type (using type-of);
  ;; if expr is of the form (the <type> <form>), return <type>; 
  ;; else, return nil.
  (cond 
   ((self-evaluating? expr)
    ;; Attempt to work-around (type-of 0) -> useless types like
    ;; (integer 0 0) [cmucl/sbcl], (integer 0 16777215) or BIT [clisp]
    ;; -- possibly conterproductive for (array type dim1 .. dimn) types
    (let ((type (type-of expr)))
      (if (consp type) (first type) type)))
   ((the-expression? expr)
    (second expr))
   (t nil)))

(defun expression-type (form)
  (if (symbolp form)
      (var-type form)
      (expr-type-only form)))

(defun quoted? (x)
  ;; Returns T iff x is of the form (quote ...)
  (and (consp x) (eq (car x) 'quote)))

(defun function-quoted? (x)
  ;; Returns T iff x is of the form (function ...) [same as #'(...)]
  (and (consp x) (eq (car x) 'function)))

(defun lambda-expression? (x)
  (and (consp x) (eq (car x) 'lambda)))

(defun the-expression? (x)
  (and (consp x) (eq (first x) 'the)))

(defun self-evaluating? (x)
  ;; Everything but symbols and lists are self-evaluating since CLtL2.
  ;; This differs from constantp in that it returns nil for quoted
  ;; things and defconstants.
  ;; (typep x '(and atom (or (not symbol) keyword (member t nil))))
  (and (atom x) (or (null x) (not (symbolp x)) (eq x t) (keywordp x))))

(defun constant? (x)
  ;; This differs from constantp in that it doesn't acknowledge
  ;; defconstants to be constants; the problem with so acknowledging
  ;; them is that the run-time and compile-time environments may
  ;; differ.  The things constant? returns T for are really and truly
  ;; constant everywhere.
  (or (self-evaluating? x) (quoted? x) (function-quoted? x)))

(defun duplicable? (x)
  ;; Returns T if X can be copied in code.  This returns T for symbols, on the
  ;; assumption that the copies are close enough to each other so that
  ;; updating the variable cannot occur.
  (or (numberp x) (symbolp x) (characterp x)))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Variable specifiers.  They're either a symbol, or a the-expression
;;; constaining a symbol.

(defun var-spec? (x)
  (or (the-expression? x) (symbolp x)))

(defun extract-var (var-spec)
  (if (the-expression? var-spec)
      (third var-spec)
      var-spec))

;;; Possible extension:
;;; When more than one variable can occur, we allow a single
;;; the-expression to cover them all.  Unfortunately, this makes
;;; things rather hairy--probably better to avoid it.

;(defun distribute-type-spec (x)
;  (if (and (the-expression? x) (not (symbolp (third x))))
;      (let ((type (second x))
;	    (vars (third x)))
;	(mapcar #'(lambda (v) `(the ,type ,v)) vars))
;      x))



;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Binding and destructuring.

(defun make-binding (var value &key type using-type-of)
  ;; This creates a binding of VAR to VALUE.  TYPE means declare VAR
  ;; to be of that type if it isn't declared to be a type already.
  ;; (But do so only when declare-variables has been declared.)
  ;; USING-TYPE-OF means to use the type of that form, if any.  
  ;; Specifying both keyword args is an error.
  ;;   It is okay to pass nil for VAR; in this case, nothing will
  ;; happen and nil will be returned.  This is done just to simplify
  ;; coding of clauses.
  (make-binding-internal var value t type using-type-of))

(defun make-default-binding (var &key type using-type-of)
  ;; This makes a random binding of VAR (i.e. you should not depend on
  ;; the binding's value).  It will observe TYPE and USING-TYPE-OF in
  ;; choosing a value to bind to (see the comment for make-binding).
  ;;   It is okay to pass nil for VAR; in this case, nothing will
  ;; happen and nil will be returned.  This is done just to simplify
  ;; coding of clauses.
  (make-binding-internal var nil nil type using-type-of))

(defun make-var-and-binding (string value &key type using-type-of)
  (let ((var (genvar string)))
    (make-binding-internal var value t type using-type-of)
    var))

(defun make-var-and-default-binding (string &key type using-type-of)
  (let ((var (genvar string)))
    (make-binding-internal var nil nil type using-type-of)
    var))

(defun make-accum-var-binding (var value kind &key type using-type-of)
  (make-accum-var-binding-internal var value t kind type using-type-of))

(defun make-accum-var-default-binding (var kind &key type using-type-of)
  (make-accum-var-binding-internal var nil nil kind type using-type-of))

(defun make-accum-var-binding-internal (var value value-supplied?
					kind type using-type-of)
  ;; Possibly creates a binding for an accumulation variable, like
  ;; those generated by COLLECT, MAXIMIZE, COUNT, etc.  
  ;; It checks *accum-var-alist* to see if the variable already exists.
  ;; If so, and it is of the right kind, it does not create a new
  ;; binding.  If it is of the wrong kind, an error is signalled.  If kind is
  ;; NIL, then we don't do this error check.  However, we aways check to make
  ;; sure the initial value, if supplied, is correct.
  ;;    In all cases, *internal-variables* is checked to make sure the
  ;; variable does not occur there.
  ;;    The alist entry is returned.  It can be used to store
  ;; additional info, like the end-pointer for collections.
  (let ((entry (assoc var *accum-var-alist* :test #'eq)))
    (cond
     ((null entry)
      (if value-supplied?
	  (make-binding var value :type type :using-type-of using-type-of)
	  (make-default-binding var :type type :using-type-of using-type-of))
      (setq entry (list var kind))
      (push entry *accum-var-alist*)
      entry)
     ((and kind (second entry) (not (eq (second entry) kind)))
      (clause-error "Attempt to do ~a accumulation into a variable ~
  already being used for ~a accumulation."
		    kind (second entry)))
     (t
      (if value-supplied?
	  (let ((orig-value  (second (assoc var *bindings*))))
	    (if (not (equal value orig-value))
		(clause-error "Initial values ~a and ~a are not equal ~
  for variable ~a"
			      orig-value value var))))
      (check-internal-variables var)
      entry))))

1796 1797 1798 1799 1800 1801 1802 1803 1804
(defun make-shared-binding (var value &key type using-type-of)
  "Look up or create an alist entry keyed by var, store a gensym
   in the value and also add it as a binding. Return the entry."
  (let ((entry (assoc var *shared-bindings-alist* :test #'eq)))
    (unless entry
        (setq entry (list var (gensym (string var))))
        (push entry *shared-bindings-alist*)
        (make-binding (second entry) value :type type :using-type-of using-type-of))
    entry))
Attila Lendvai's avatar
Attila Lendvai committed
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372

(defun make-binding-internal (var-spec value value-supplied? 
				       use-type using-type-of)
  ;; This returns T if it actually created a binding, else NIL.
  ;; Declaration and typing rules: first of all, no declaration is
  ;; generated unless *declare-variables* is T and var doesn't already
  ;; have a type declaration.  If there is no type for var, we infer
  ;; it as best we can as follows: if use-type is supplied, we use
  ;; that type.  If using-type-of is supplied, we try to determine a
  ;; type for that variable or expression (see expression-type) and
  ;; use that if we find it.  (It is erroneous to supply both use-type
  ;; and using-type-of.)  If neither is supplied, we DO NOT try to
  ;; infer the type of value--we just give up.  Otherwise, someone who
  ;; innocently did (make-binding 'foo nil) would discover that the
  ;; resulting code, if declare-variables was used, would 
  ;; have foo declared to be of type symbol (since, in Lucid at least,
  ;; (type-of nil) == symbol).  Note that we do not check for a type
  ;; conflict between a supplied type and the existing type; the
  ;; existing type just wins.
  ;;
  ;;   The var can actually be of the form (the <type> var).
  (let ((var (extract-var var-spec)))
    (cond
     ((null var-spec)
      nil)
     ((not (symbolp var))
      (clause-error "The variable ~a is not a symbol" var))
     (t
      (let* ((existing-type (var-type var-spec))
	     (declared? (var-declaration var))
	     (type (or existing-type
		       use-type
		       (if using-type-of (expression-type using-type-of)))))
	(if (or declared? (and *declare-variables* type))
	    ;; We only have to be concerned about getting value to be
	    ;; the right type if there will actually be a declaration
	    ;; for var.  This will be either when there is an existing
	    ;; declaration, or when *declare-variables* is true and
	    ;; there is some type.
	    (setq value (make-initial-value value value-supplied? type)))
	(if (and (not declared?) *declare-variables* type)
	    (push `(type ,type ,var) *declarations*))
	(add-binding var value)
      t)))))


(defun make-initial-value (value value-supplied? type)
  ;; This should really be done by trying to coerce, then trapping the error,
  ;; because the subtype checks aren't really right--nil, for instance, is a
  ;; subtype of anything, but you can't coerce anything to it.  (Sure, we
  ;; check for nil explicitly, but there are other things like it.)  Yet if we
  ;; omit the subtype tests currently, how will we know that we can convert
  ;; nil to a vector?
  (cond
   ((null type)
    value)
   (value-supplied?
    (if (self-evaluating? value)
	(coerce value type)
	`(the ,type ,value)))
   ((or (subtypep 'number type) (subtypep type 'number))
    (coerce 0 type))
   ((or (subtypep 'sequence type) (subtypep 'symbol type)
	(subtypep type 'sequence) (subtypep type 'symbol))
    (coerce nil type))
   ((subtypep type 'character)
    (coerce (code-char 0) type)) ; Neither #\Null nor #\Nul are valid characters.
   (t 
    (clause-warning 
     "Cannot supply an initial value for type ~s; using NIL."
     type)
    nil)))

(defun add-binding (var value)
  (cond
   ((var-binding var)
    (clause-error "Duplicate variable: ~a" var))
   (t
    (check-internal-variables var)
    (push (list var value) *bindings*))))

(defun check-internal-variables (var)
  (if (internal-variable? var)
      (clause-error 
       "The variable ~a, which Iterate would like to bind, already has a ~
  binding in a context internal to the iterate form.  Give the variable ~
  another name." var)))

(defun internal-variable? (var)
  (member var *internal-variables* :test #'eq))

;  (some #L(if (symbolp !1) 
;	      (eq var !1) 
;	      (member var !1 :test #'eq))
;	*internal-variables*))

(defun var-binding (var)
  (car (member var *bindings* :test #'eq :key #'car)))



;;;;;;;;;;;;;;;;;;
;;; Destructuring.

;;; Where destructuring happens:
;;;  WITH (bind)
;;;  FOR...INIT...THEN (setq)
;;;  FOR...FIRST...THEN (setq)
;;;  FOR...= (setq)
;;;  FOR...IN-FILE (setq)
;;;  FOR...IN-STREAM (setq)
;;;  FOR...IN-HASHTABLE (setq)
;;;  FOR...IN-PACKAGE (setq)
;;;  element-var of sequence & list drivers (setq)


(defun make-destructuring-bindings (template value 
				    &key type using-type-of)
  (cond
   ((null template)
    (clause-error "Can't bind to NIL: ~a" value))
   ((var-spec? template)
    (make-binding template value :type type :using-type-of using-type-of))
   ((atom template)
    (clause-error "Invalid binding form: ~a" template))
   ((eq (car template) 'values)
    (clause-error "Cannot perform multiple-value destructuring in ~
  this context"))
   (t
    (let ((var (make-var-and-binding 'temp value)))
      (push var *temps*)  ; so that others can benefit
      (do-destructuring-bindings template var)))))


(defun do-destructuring-bindings (template value)
  (cond
   ((null template)
    nil)
   ((var-spec? template)
    (make-binding template value)
    nil)
   ((atom template)
    (clause-error "Invalid binding form: ~a" template))
   ((eq (car template) 'values)
    (clause-error "Multiple-value destructuring cannot be nested"))
   (t
    (nconc (do-destructuring-bindings (car template) `(car ,value))
	   (do-destructuring-bindings (cdr template) `(cdr ,value))))))

(defun extract-vars (template)
  ;; Like extract-var, but will work with a destructuring template as well.
  ;; Returns a list of variables.
  (cond
   ((null template)
    nil)
   ((var-spec? template)
    (list (extract-var template)))
   ((not (consp template))
    (clause-error "Invalid binding form: ~a" template))
   ((eq (car template) 'values)
    (mapcan #'extract-vars (cdr template)))
   (t
    (nconc (extract-vars (car template))
	   (extract-vars (cdr template))))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dsetq.

(defmacro dsetq (template value)
  "Destructuring assignment; supports both
(VALUES ...) for destructuring a multiple-value form and
NIL as a variable name, meaning to ignore that position,
e.g. (DSETQ (VALUES (a . b) nil c) form)"
  ;; This macro can be used outside an Iterate form. 
  ;; The semantics are that if you say (DSETQ (A B) A), then b will get its
  ;; value from the original A.
  (do-dsetq template value nil))

  
(defun do-dsetq (template value &optional (bindings? t) type)
  (cond
   ((null template)
    (dsetq-error "Can't bind to nil"))
   ((var-spec? template) ; not only (symbolp template)
    (if bindings?
	(make-default-binding template :type type))
    `(setq ,(extract-var template) ,value))
   ((and (consp template) (eq (car template) 'values))
    ;; Just do a simple check for the most common errors.  There's no way we
    ;; can catch all problems.
    (if (or (atom value) (member (car value) '(car cdr cdar caar aref get)))
	(dsetq-error "Multiple values make no sense for this expression" )
	(make-mv-dsetqs (cdr template) value bindings?)))
   (t
    (let ((temp (gensym "DSETQ")))
      `(let ((,temp ,value))
	 ,.(if (and type *declare-variables*) `((declare (type ,type ,temp))))
	 ,.(make-dsetqs template temp bindings?)
	 ,temp)))))

(defun make-dsetqs (template value bindings?)
  (cond 
   ((null template)
    nil)
   ((var-spec? template)
    (if bindings?
	(make-default-binding template))
    `((setq ,(extract-var template) ,value)))
   ((atom template)
    (dsetq-error "Invalid binding form: ~a" template))
   ((eq (car template) 'values)
    (dsetq-error "Multiple-value destructuring cannot be nested"))
   (t
    (nconc (make-dsetqs (car template) `(car ,value) bindings?)
	   (make-dsetqs (cdr template) `(cdr ,value) bindings?)))))

(defun make-mv-dsetqs (templates value bindings?)
  (let ((temps '()) (vars '()) (tplates '()))
    (declare (type list temps vars tplates))
    (dolist (tp templates)
      (cond
       ((and tp (var-spec? tp)) ; either var or (the type var)
	(push nil tplates)
	(push nil temps)
	(push (extract-var tp) vars)
	(if bindings?
	    (make-default-binding tp)))
       (t ; either NIL or destructuring template
	(let ((temp (gensym "VALUE")))
	  (push tp tplates)
	  (push temp temps)
	  (push temp vars)))))
    (setq temps (nreverse temps))
    (setq vars (nreverse vars))
    (setq tplates (nreverse tplates))
    (let ((mv-setq `(multiple-value-setq ,vars ,value))
	  ;; Remove, don't delete. Bug
	  ;; reported by Francois Ren'e Rideau on 2005-11-01
	  (temp-vars (remove nil temps)))
      (if (null temp-vars)
	  mv-setq
	  `(let ,temp-vars
	     (declare (ignorable .,temp-vars)) ; in case of NIL template
	     ,mv-setq
	     ,.(mapcan #L(make-dsetqs !1 !2 bindings?)
		       tplates temps)
	     ,(car vars))))))

(defun dsetq-error (format-string &rest args)
  (if (in-iterate?)
      (apply #'clause-error format-string args)
      (apply #'error (concatenate 'string "DSETQ: " format-string) args)))

(defun in-iterate? ()
  (boundp '*result-var*))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Free variables; checking for local bindings.

(defun local-binding-check (form)
  (when *internal-variables* ; else no need to extract free variables
    (let ((vars (remove-if-not #'internal-variable? (free-variables form))))
      (if vars
	  (clause-error "The variable~p ~{~a~^, ~} ~:[is~;are~] bound in a context internal to ~
  the Iterate form.~%~
  This part of the clause will be moved outside the body of the loop, so it ~
  must not contain anything that depends on the body."
			(length vars) vars (rest vars))))))


(defun free-variables (form)
  ;; This will return a list of the (lexically) free variables in FORM.  It
  ;; will never return anything that is not a free variable (except for not
  ;; processing MACROLET), but it may not get all of them. 
  (delete-duplicates (free-vars form nil) :test #'eq))

(defun free-vars (form bound-vars)
  ;; To compute the variables that are free in a form, we have to walk it,
  ;; keeping track of what variables are bound.
  (cond
   ((constantp form)
    nil)
   ((symbolp form)
    (if (not (member form bound-vars :test #'eq))
	(list form)))
   ((atom form)
    nil)
   ((symbolp (car form))
    (cond
     ((or (special-operator-p (car form)) 
	  ;; Lucid doesn't think that these are special forms
	  ;; and we need to handle declarations:
	  (member (car form) '(declare multiple-value-bind
			       flet labels let let*) :test #'eq))
      (case (car form)
	((catch if locally multiple-value-call multiple-value-prog1
	  progn progv setq tagbody throw unwind-protect)
	    (free-vars-list (cdr form) bound-vars))
	((block eval-when return-from the)
	    (free-vars-list (cddr form) bound-vars))
	(multiple-value-bind
	    (free-vars-list (cddr form) (append (cadr form) bound-vars)))
	(function
	    (free-vars-fspec (second form) bound-vars))
	((flet labels macrolet)
	    (nconc (mapcan #L(free-vars-fspec !1 bound-vars)
			   (second form))
		   (free-vars-list (cddr form) bound-vars)))
	((let symbol-macrolet)
	    (let* ((bindings (second form))
		   (body (cddr form))
		   (vars (mapcar #L(if (consp !1) (car !1) !1)
				 bindings)))
	      (nconc (mapcan #L(if (consp !1)
				   (free-vars (second !1) bound-vars)
				   nil)
			     bindings)
		     (free-vars-list body (append vars bound-vars)))))
	(let*
	    (let* ((bindings (second form))
		   (body (cddr form))
		   (free-vars nil))
	      (dolist (binding bindings)
		(if (consp binding)
		    (augment free-vars (free-vars (second binding) 
						  bound-vars)))
		(push (if (consp binding) (car binding) binding) bound-vars))
	      (nconc free-vars (free-vars-list body bound-vars))))
	(otherwise
	    nil)))
     ((macro-function (car form) *env*)
      (free-vars (macroexpand-1 form *env*) bound-vars))
     (t ; function call
      (free-vars-list (cdr form) bound-vars))))
   ((and (consp (car form)) (eq (caar form) 'lambda))
    (nconc (free-vars-fspec (car form) bound-vars)
	   (free-vars-list (cdr form) bound-vars)))
   (t
    (error "The form ~a is not a valid Lisp expression" form))))

(defun free-vars-list (list bound-vars)
  (mapcan #L(free-vars !1 bound-vars)
	  list))

(defun free-vars-fspec (fspec bound-vars)
  ;; FSPEC is either: a symbol, or
  ;; (<name-or-lambda> (<vars>) . body), or
  ;; (SETF <symbol>)
  (if (or (symbolp fspec) (eq (car fspec) 'setf))
      nil
      (free-vars-list (cddr fspec) (append (second fspec) bound-vars))))


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Functions that return code.

(defun return-code (&key declarations initial body step final final-protected)
  (values body declarations initial step final final-protected))

(defmacro return-driver-code (&key variable initial declarations body step
				   final final-protected next)
  ;; This assumes there is a local var called 'generate'
  (let ((btemp (gensym))
	(ntemp (gensym)))
    `(let ((,btemp ,body)
	   (,ntemp ,next))
      (add-driver-info ,variable ,ntemp generate)
      (if (not generate)
	  (augment ,btemp ,ntemp))
      (values ,btemp ,declarations ,initial ,step ,final ,final-protected))))

(defun add-driver-info (var-template next-code generator?)
  ;; VAR-TEMPLATE could be a single var-spec or a destructuring template.
  ;; Copy the code--the original could be nconc'ed.
  (let ((vars (extract-vars var-template))
	(di (make-driver-info :next-code (copy-list next-code)
			      :generator? generator?)))
    (register-previous-code vars next-code :next)
    (push (cons vars di) *driver-info-alist*)))

(defmacro return-sequence-code (&key element-var sequence access-fn
				     size-fn element-type sequence-type)
  ;; This assumes all the sequence keywords will be in the lexical
  ;; environment. 
  `(return-seq-code
    :element-var ,element-var
    :sequence ,sequence
    :access-fn ,access-fn
    :size-fn ,size-fn
    :element-type ,element-type
    :sequence-type ,sequence-type
    :from from :upfrom upfrom :to to :downto downto :above above :below below
    :downfrom downfrom :by by
    :with-index with-index
    :generate generate))

(defun return-seq-code (&key element-var sequence access-fn size-fn
			     element-type sequence-type
			     from upfrom to downto above below downfrom 
			     with-index (by 1) generate)
  ;; element-var might involve destructuring; the others won't.  If
  ;; access-fn is NIL, don't generate element-accessing code at all.
  (top-level-check)
  (check-sequence-keywords from upfrom downfrom to downto above below t)
  (let* ((index-var-spec (or with-index (genvar 'index))) 
	 (index-var (extract-var index-var-spec))
	 (seq-var (if (or access-fn (not (symbolp sequence)))
		      (make-var-and-default-binding 'sequence
						    :type sequence-type)))
	 (seq-code (or seq-var sequence))
	 (step-var (if (not (constant? by))
		       (make-var-and-default-binding 'step :type 'fixnum)))
	 (step (or step-var by))
	 (step-func (if (or downto downfrom above) '- '+))
	 (test-func (cond
		     (to '>)
		     ((or downto downfrom) '<)
		     (below '>=)
		     (above '<=)
		     (t '>=)))
	 (size-code (make-application size-fn seq-code))
	 (limit-value (cond
		       ((or to below))
		       ((or downto above))
		       (downfrom 0)
		       (t size-code)))
	 (limit-var (if (not (numberp limit-value)) 
			(make-var-and-default-binding 'limit :type 'fixnum)))
	 (limit-code (or limit-var limit-value))
	 (other-func (if (eq step-func '-) '+ '-))
	 (initial-value (eval-const-expr
			 (cond
			  ((or from upfrom downfrom)
			   `(,other-func ,(or from upfrom downfrom) ,step))
			  ((or downto above)
			   (if (eql step 1) size-code `(+ ,size-code (1- ,step))))
			  (t `(- ,step)))))
	 (access-code (if (null access-fn)
			  nil
			  (make-application access-fn seq-code index-var)))
	 (step-code `(setq ,index-var (,step-func ,index-var ,step)))
	 (setqs	(if access-fn (do-dsetq element-var access-code 
					t element-type)))
	 (test `(if (,test-func ,index-var ,limit-code) (go ,*loop-end*))))
    (make-default-binding index-var-spec :type 'fixnum)
    (setq *loop-end-used?* t)
    (return-driver-code
     :initial (nconc (if seq-var `((setq ,seq-var ,sequence)))
		     (if step-var `((setq ,step-var ,by)))
		     (if limit-var `((setq ,limit-var ,limit-value)))
		     (if index-var `((setq ,index-var ,initial-value))))
     :next (list step-code test setqs)
     ;; say (list nil ...) in case element-var = VALUES
     :variable (list nil element-var index-var))))

(defun check-sequence-keywords (from upfrom downfrom to downto above below
				known-limits? &aux count)

  ;; If the limits aren't known, the possibilities are: FROM; UPFROM;
  ;; DOWNFROM; TO; BELOW; or FROM and exactly one of TO, DOWNTO, ABOVE and
  ;; BELOW.
  ;; If the limits are known: you also have DOWNTO; ABOVE; and nothing.
  (if (or (and upfrom downfrom)
	  (and (or upfrom downfrom) (or from to downto above below)))
      (clause-error "UPFROM or DOWNFROM must occur alone"))
  (if (> (setq count (count-if #'identity (list to downto above below))) 1)
      (clause-error "Use at most one of TO, DOWNTO, ABOVE and BELOW"))
  (if (not known-limits?)
      ;; eliminate the cases DOWNTO, ABOVE, and nothing.
      (if (and (not (or from upfrom downfrom))
	       (or downto above (zerop count)))
	  (clause-error "Illegal set of sequence keywords"))))

(defun eval-const-expr (expr)
  ;; This is very simple: if expr is a list, and all the args are constants,
  ;; it will evaluate it; else it will just return it.
  (if (and (consp expr) (every #'constantp (cdr expr)))
      (eval expr)
      expr))

(defun make-funcall (fn &rest args)
  ;; This should be used when FN is something the user has written in a
  ;; clause. 
  #+symbolics (setq args (copy-list args))
  (cond
   ((or (quoted? fn) (function-quoted? fn))
    `(,(second fn) ,@args))
   ((lambda-expression? fn)
    `(,fn ,@args))
   ;;((functionp fn) `(funcall ,fn ,@args)) ; same treatment as default case
   (t
    `(funcall ,fn ,@args))))

(defun make-application (fn &rest args)
  ;; Use this when FN is given in the implementation code.
  #+ symbolics (setq args (copy-list args))
  (cond
   ((or (symbolp fn) (lambda-expression? fn))
    `(,fn ,@args))
   ((function-quoted? fn)
    `(,(second fn) ,@args))
   ((and (consp fn) (eq (car fn) 'subst))
    (apply-subst-expr fn args))
   ((functionp fn) `(funcall ,fn ,@args)) ;; Siskind's patch for compiled fns
   (t
    (clause-error "~a should denote a function, but it doesn't" fn))))
      
(defun apply-subst-expr (subst-expr args)
  (let ((params (second subst-expr))
	(body (cddr subst-expr)))
    (prognify (sublis (pairlis params args) body))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;   Clauses   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Special clauses.  These must return freshly consed lists that are
;;; nconcable. 

(defmacro def-special-clause (name arglist &body body)
  `(progn
     (defun ,name ,arglist .,body)
     (install-special-clause-function ',name
				      ,(if (stringp (car body))
					   (car body)))))

(defun install-special-clause-function (symbol &optional doc-string)
  ;; Put it at the end, if not already present.
  (let ((entry (assoc symbol *special-clause-alist*)))
    (if (null entry)
	(augment *special-clause-alist* (list (cons symbol doc-string)))
	(setf (cdr entry) doc-string))
    symbol))

;;; (INITIALLY &rest)
(def-special-clause initially (&rest forms)
  "Lisp forms to execute before loop starts"
  (mapc #'local-binding-check forms)
  (return-code :initial (copy-list forms)))

;;; (AFTER-EACH &rest)
(def-special-clause after-each (&rest forms)
  "Lisp forms to execute after each iteration"
  (mapc #'local-binding-check forms)
  (return-code :step (walk-list forms)))

;;; (ELSE &rest)
(def-special-clause else (&rest forms)
  "Lisp forms to execute if the loop is never entered"
  (mapc #'local-binding-check forms)
  (let ((flag (make-var-and-binding 'else t :type 'boolean)))
    (return-code :final `((when ,flag
			    .,(walk-list forms)))
                 :body (list `(setq ,flag nil)))))

;;; (FINALLY &rest)
(def-special-clause finally (&rest forms)
  "Lisp forms to execute after loop ends"
  (mapc #'local-binding-check forms)
  (return-code :final (copy-list forms)))

;;; (FINALLY-PROTECTED &rest)
(def-special-clause finally-protected (&rest forms)
  "Lisp forms in an UNWIND-PROTECT after loop ends"
  (mapc #'local-binding-check forms)
  (return-code :final-protected (copy-list forms)))

2373 2374
;;; (IF-FIRST-TIME then &optional else)
(def-special-clause if-first-time (then &optional else)
Attila Lendvai's avatar
Attila Lendvai committed
2375
  "Evaluate branch depending on whether this clause is met for the first time"
2376 2377 2378 2379 2380
  (return-code :body (list
		      (if-1st-time (list (walk-expr then))
				   (if else (list (walk-expr else)))))))

;;; (FIRST-TIME-P)
2381
(def-special-clause FIRST-TIME-P ()
2382 2383
  "True when evaluated for the first time"
  (return-code :body (list (if-1st-time '(t)))))
2384

2385
;;; (FIRST-ITERATION-P)
2386
(def-special-clause FIRST-ITERATION-P ()
2387 2388 2389
  "True within first iteration through the body"
  ;; Like (with ,var = t) (after-each (setq ,var nil))
  ;; except all these clauses shares a single binding.
2390 2391 2392 2393 2394 2395 2396 2397 2398
  (let* ((entry (make-shared-binding 'first-iteration t :type 'boolean))
         (step-body nil)
         (first-usage (not (cddr entry)))
         (var (second entry)))
    (when first-usage
      (setf step-body (list `(setf ,var nil)))
      (setf (cddr entry) (list t)))
    (return-code :body `(,var)
                 :step step-body)))
Attila Lendvai's avatar
Attila Lendvai committed
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538

;;; (IN &body)
(def-special-clause in (block-name &rest forms)
  "Process forms in a named Iterate block"
  ;; VALUE: depends on forms
  (if (eq block-name *block-name*)
      (walk-list forms)
      `((in ,block-name ,.(copy-list forms)))))

;;; (NEXT var)
(def-special-clause next (var &optional (n 1))
  "Explicitly step a driver variable"
  ;; VALUE: var, after stepping.
  ;; Enclose the returned code in a PROGN so that the variable reference isn't
  ;; confusable with a tag (since the code might appear within a tagbody).
  ;; The PROGN is also necessary so that spliced-in save code will not result
  ;; in extra forms, for cases when the NEXT appears as an argument.
  (let ((entry (assoc var *driver-info-alist* :test #'member)))
    (if (or (null entry) (not (driver-info-generator? (cdr entry))))
	(clause-error "Variable is not associated with a generator")
	(let* ((vars (car entry))
	       (di (cdr entry))
	       (code (copy-list (driver-info-next-code di))))
	  (if (internal-variable? var)
	      (clause-error "The variable ~a is bound in a context internal ~
  to the Iterate form. ~
  It cannot be stepped at this point in the code." var))
	  (if (some #'internal-variable? vars)
	      (clause-error "Some of the variables ~a, which will be stepped ~
  when this clause is executed, are bound in a context internal to the Iterate ~
  form, so ~a cannot be stepped at this point in the code." vars var))
	  (setf (driver-info-used di) t)
	  (register-previous-code vars code :next)
	  (return-code :body (make-next-code var code n))))))


(defun make-next-code (var code n)
  ;; Construct the body carefully (avoid backquote), ensuring that CODE,
  ;; and not a copy, appears in it.
  (if (eql n 1)
      (let ((var-code (if (eq var (var-value-returned code))
			  ()
			  (list var))))
	;; This var-value-returned optimization benefits
	;; FOR IN-VECTOR/SEQUENCE/STRING.
	;; Too small a benefit in light of current compilers?
	(list (cons 'progn (nconc code var-code))))
      (let ((i (genvar 'next)))
	(list (list* 'dotimes (list i n var) `(declare (ignorable ,i)) code)))))


(defun var-value-returned (forms)
  ;; If the result of evaluating FORMS would be the value of some variable,
  ;; then that variable is returned; else NIL.
  ;;  We only check for progns, setqs and raw variables.
  (let ((form (car (last forms))))
    (cond
     ((symbolp form)
      form)
     ((atom form)
      nil)
     ((eq (car form) 'setq)
      (second (last form 3)))		; support degenerated (setq)
     ((eq (car form) 'progn)
      (var-value-returned (cdr form)))
     (t
      nil))))

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Iteration-driving clauses.

(defsynonym as for)

(defsynonym generating generate)

(defclause (repeat n)
  "Repeat the loop some number of times"
  (top-level-check)
  (let* ((c-type (or (expression-type n) 'fixnum))
	 (count-var (make-var-and-default-binding 'count :type c-type)))
    (setq *loop-end-used?* t)
    (return-code :initial `((setq ,count-var ,n))
		 :body `((if (<= ,count-var 0) (go ,*loop-end*)))
		 :step `((setq ,count-var (1- ,count-var))))))


;;; (FOR &sequence)
(defclause-driver (for var-spec &sequence)
  "Numbers"
  (top-level-check)
  (if with-index
      (clause-error "WITH-INDEX should not be specified for this clause"))
  (check-sequence-keywords from upfrom downfrom to downto above below nil)
  (make-default-binding var-spec :type 'number)
  (let* ((var (extract-var var-spec))
	 (initial (or from upfrom downfrom 0))
	 (limit (or to downto above below))
	 (step-func (if (or downfrom downto above)
			'-
			'+))
	 (test-func (cond
		     (to '>)
		     (downto '<)
		     (below '>=)
		     (above '<=)))
	 (limit-var (if (and limit (not (constant? limit)))
			(make-var-and-default-binding 
			 'limit
			 :using-type-of (if (expression-type limit)
					    limit
					    var))))
	 (step-var (if (not (constantp by)) 
		       (make-var-and-default-binding 'step
						     :using-type-of by)))
	 (step-thing (or step-var by))
	 (limit-code (or limit-var limit))
	 (init-val (eval-const-expr
		    (list (if (eq step-func '+) '- '+) initial step-thing)))
	 (test (if limit
		   (progn (setq *loop-end-used?* t)
			  `((if (,test-func ,var ,limit-code) 
				(go ,*loop-end*))))
		   nil))
	 (next `((setq ,var (,step-func ,var ,step-thing)) .,test)))
    (return-driver-code :initial `(,.(if limit-var
					 `((setq ,limit-var ,limit)))
				   ,.(if step-var
					 `((setq ,step-var ,by)))
				   (setq ,var ,init-val))
			:next next
			:variable var)))


;;;;;;;;;;;;;;;;;;;;;;;
;;; Sequence iteration

;;; (FOR ON &optional BY)
(defclause-driver (for var on list &optional by (step ''cdr))
  "Sublists of a list"
  (top-level-check)
2539 2540
  (let* ((list-var (make-var-and-default-binding 'list))
	 ;; Handle dotted lists, so type declaration is not possible
Attila Lendvai's avatar
Attila Lendvai committed
2541
	 (setqs (do-dsetq var list-var t 'list))
2542
	 (test `(if (atom ,list-var) (go ,*loop-end*))))
Attila Lendvai's avatar
Attila Lendvai committed
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
    (setq *loop-end-used?* t)
    (return-driver-code :initial `((setq ,list-var ,list))
			:next (list test
				    setqs
				    (generate-function-step-code 
				     list-var step))
			:variable var)))

;;; (FOR IN &optional BY)
(defclause-driver (for var in list &optional by (step ''cdr))
  "Elements of a list"
  (top-level-check)
2555
  (let* ((on-var (make-var-and-default-binding 'list :type 'list))
Attila Lendvai's avatar
Attila Lendvai committed
2556
	 (setqs (do-dsetq var `(car ,on-var)))
2557
	 (test `(if (endp ,on-var) (go ,*loop-end*))))
Attila Lendvai's avatar
Attila Lendvai committed
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
    (setq *loop-end-used?* t)
    (return-driver-code :initial `((setq ,on-var ,list))
			:next (list test
				    setqs
				    (generate-function-step-code on-var step))
			:variable var)))


(defun generate-function-step-code (var step) 
  ;; If the stepping function is quoted or sharp-quoted, we don't need to make
  ;; a variable for it.  The two constant cases are distinguished solely for
  ;; compilers too stupid to compile (funcall 'cdr foo) the same as (cdr foo).
  ;; (Really, for cosmetics--there probably are no such stupid compilers.)
  (cond
   ((quoted? step)
    `(setq ,var (,(second step) ,var)))
   ((function-quoted? step)
    `(setq ,var (funcall ,step ,var)))
   (t
    (let ((step-var (make-var-and-binding 'step step :type 'function)))
      `(setq ,var (funcall ,step-var ,var))))))


;;; (FOR IN-VECTOR &sequence)
(defclause-sequence in-vector index-of-vector
  ;; This observes fill-pointers.
  :access-fn 'aref
  :size-fn 'length
  :sequence-type 'vector
  :element-doc-string "Elements of a vector"
  :index-doc-string "Indices of a vector")

;;; (FOR IN-SEQUENCE)
(defclause-sequence in-sequence index-of-sequence
  ;; This observes fill pointers, and works for any sequence.
  :access-fn 'elt
  :size-fn 'length
  :sequence-type 'sequence
  :element-doc-string "Elements of a sequence (vector or list)"
  :index-doc-string "Indices of a sequence (vector or list)")

;;; (FOR IN-STRING)
(defclause-sequence in-string index-of-string
  :access-fn 'char
  :size-fn 'length
  :sequence-type 'string
  :element-type 'character
  :element-doc-string "Characters in a string"
  :index-doc-string "Indices of a string")


;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Hash-table, Packages and Streams

;;; (FOR IN-HASHTABLE)
(defclause-driver (for key-val-vars in-hashtable table)
  "Elements and keys of a hashtable"
  (top-level-check)
  (unless (consp key-val-vars)
    (clause-error "~a should be a list of up to two variables: the first ~
  for the keys, the second for the values." key-val-vars))
  (let* ((iterator (gensym "HASH-TABLE-ITERATOR-"))
	 (more?    (gensym))
	 (var-spec `(values ,more? .,key-val-vars))
	 (setqs    (do-dsetq var-spec `(,iterator)))
	 (test     `(if (not ,more?) (go ,*loop-end*))))
    ;; FIXME 2004-11-11 destructure only after termination test
    (setq *loop-end-used?* t)
    (add-loop-body-wrapper `(with-hash-table-iterator (,iterator ,table)))
    (return-driver-code :next (list setqs test)
			:variable var-spec)))

;;; (FOR IN-PACKAGES &optional HAVING-ACCESS)
(defclause-driver (for sym-access-pkg-vars in-packages pkgs &optional having-access (sym-types '(:external :internal :inherited)))
  "Symbols and their access-types in packages"
  ;;defclause-driver has the benefit over defmacro-driver of less code walking
  (top-level-check)
  (unless (and (listp sym-access-pkg-vars) ; empty list is allowed (count)
	       (every #'symbolp sym-access-pkg-vars))
    (clause-error "~a should be a list of up to three variables: the symbol, ~
  the access type and the home package." sym-access-pkg-vars))
  (unless (consp sym-types)
    (clause-error "~s should be a list of symbols indicating the symbols' ~
  access types." sym-types))
  (let* ((iterator (gensym "PACKAGE-ITERATOR-"))
	 (more?    (gensym))
	 (var-spec `(values ,more? .,sym-access-pkg-vars))
	 (setqs    (do-dsetq var-spec `(,iterator)))
	 (test     `(if (not ,more?) (go ,*loop-end*))))
    (setq *loop-end-used?* t)
    (add-loop-body-wrapper `(with-package-iterator (,iterator ,pkgs .,sym-types)))
    (return-driver-code :next (list setqs test)
			:variable var-spec)))

;;; (FOR IN-PACKAGE &optional EXTERNAL-ONLY)
(defmacro-driver (for var in-package pkg &optional external-only (ext nil))
  "Symbols accessible in a package"
  `(,(if generate 'generate 'for) (,var) in-packages ,pkg having-access
	 ,(if ext '(:external) '(:external :internal :inherited))))

;;; (FOR IN-FILE &optional USING)
(defclause-driver (for var in-file filename &optional using (reader '#'read))
  "Forms in a file"
  (top-level-check)
  (return-stream-driver-code var filename reader :file generate))

;;; (FOR IN-STREAM &optional USING)
(defclause-driver (for var in-stream stream &optional using (reader '#'read))
  "Forms in a stream (which will be closed at the end)"
  (top-level-check)
  (return-stream-driver-code var stream reader :stream generate))

(defun return-stream-driver-code (var thing reader stream-or-file generate)
  (let* ((evar (extract-var var))
	 (type (or (var-type evar) t))
	 (stream-var (make-var-and-binding 'stream nil))
	 (set-var (if (and (var-spec? var)
			   (subtypep 'symbol type))
		      ;; We can use the given variable directly if no
		      ;; destructuring is required, and if the type of the
		      ;; variable can hold a symbol (since we use a gensym for
		      ;; the eof-marker).
		      evar
		      (genvar 'element)))
	 (setq (cond ((eq set-var evar)
		      (make-default-binding var) ())
		     (t (make-default-binding set-var)
			(list (do-dsetq var set-var)))))
	 (eof (gensym "EOF")))
    (setq *loop-end-used?* t)
    (return-driver-code 
     :initial (if (eq stream-or-file :file)
		  `((setq ,stream-var (open ,thing :direction :input)))
		  `((setq ,stream-var ,thing)))
     :next `((if (eq (setq ,set-var ,(make-funcall
				      reader stream-var nil `',eof))
		     ',eof) (go ,*loop-end*))
	     .,setq)
     :final-protected `((if (streamp ,stream-var)
			    (close ,stream-var)))
     :variable var)))
  
  
;;; (FOR NEXT)
(defclause-driver (for var next next)
  "General driver; VAR is set to value of NEXT"
  (return-driver-code :variable var
		      :next (list (do-dsetq var (walk-expr next)))))
  
;;; (FOR DO-NEXT)
(defclause-driver (for var do-next next)
  "General driver; VAR must be set in DO-NEXT"
    (do-dsetq var '(list)) ; for effect only, to make var known
    ;; We can't use (make-destructuring-bindings var) here because
    ;; we support the (values ...) template,
    ;; to maintain the documented equivalence with FOR ... NEXT.
    (return-driver-code
     :variable var
     :next (mapcar #'walk-expr (if (list-of-forms? next)
				   (copy-list next)
				   (list next)))))

; No NEXT:
; LOOP-TOP: SET
;          (if test (go LOOP-END))
;          STEP
;
; NEXT:
;	...
; LOOP-TOP ...
;	[next] SET; (if test (go LOOP-END)); STEP


;(FOR var FROM n) => (initially (setq var (- n 1)))
;                    (FOR var NEXT (1+ var))
;
;(FOR var FROM n TO m) => (initially (setq var (- n 1)) (setq limit (- m 1)))
;                         (FOR var NEXT (if (> var limit) (finish) (1+ var))
2736
;
Attila Lendvai's avatar
Attila Lendvai committed
2737 2738
;
;(FOR var ON list)  =>    (initially (setq temp list))
2739
;                         (FOR var NEXT (if (atom temp)
Attila Lendvai's avatar
Attila Lendvai committed
2740 2741 2742 2743 2744
;					   (finish)
;					   (progn (setq temp (cdr temp))
;						  temp)))
;
;(FOR var IN list) =>    (initially (setq temp list))
2745
;			(FOR var NEXT (if (endp temp)
Attila Lendvai's avatar
Attila Lendvai committed
2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842