Skip to content
loop2.lsp 84.2 KiB
Newer Older
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 247 248 249 250 251 252 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 299 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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 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 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
;;;;  -*- Mode: Lisp; Syntax: Common-Lisp; Package: SYSTEM -*-
;;;;
;;;   -*- Mode: LISP; Syntax: Common-lisp; Base: 10; Lowercase:T -*-
;;;>
;;;> Portions of LOOP are Copyright (c) 1986 by the Massachusetts Institute of Technology.
;;;> All Rights Reserved.
;;;> 
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the M.I.T. copyright notice appear in all copies and that
;;;> both that copyright notice and this permission notice appear in
;;;> supporting documentation.  The names "M.I.T." and "Massachusetts
;;;> Institute of Technology" may not be used in advertising or publicity
;;;> pertaining to distribution of the software without specific, written
;;;> prior permission.  Notice must be given in supporting documentation that
;;;> copying distribution is by permission of M.I.T.  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.
;;;> 
;;;>      Massachusetts Institute of Technology
;;;>      77 Massachusetts Avenue
;;;>      Cambridge, Massachusetts  02139
;;;>      United States of America
;;;>      +1-617-253-1000
;;;>
;;;> Portions of LOOP are Copyright (c) 1989, 1990, 1991, 1992 by Symbolics, Inc.
;;;> All Rights Reserved.
;;;> 
;;;> Permission to use, copy, modify and distribute this software and its
;;;> documentation for any purpose and without fee is hereby granted,
;;;> provided that the Symbolics copyright notice appear in all copies and
;;;> that both that copyright notice and this permission notice appear in
;;;> supporting documentation.  The name "Symbolics" may not be used in
;;;> advertising or publicity pertaining to distribution of the software
;;;> without specific, written prior permission.  Notice must be given in
;;;> supporting documentation that copying distribution is by permission of
;;;> Symbolics.  Symbolics makes no representations about the suitability of
;;;> this software for any purpose.  It is provided "as is" without express
;;;> or implied warranty.
;;;> 
;;;> Symbolics, CLOE Runtime, and Minima are trademarks, and CLOE, Genera,
;;;> and Zetalisp are registered trademarks of Symbolics, Inc.
;;;>
;;;>      Symbolics, Inc.
;;;>      8 New England Executive Park, East
;;;>      Burlington, Massachusetts  01803
;;;>      United States of America
;;;>      +1-617-221-1000

;; $aclHeader: loop.cl,v 1.5 91/12/04 01:13:48 cox acl4_1 $

#+cmu
(ext:file-comment
 "$Header$")

;;;; LOOP Iteration Macro

#+allegro
(in-package :excl)
#+mkcl
(in-package "SI")

#-(or allegro mkcl)
(in-package :ansi-loop)

#-mkcl
(provide :loop)

#+Cloe-Runtime					;Don't ask.
(car (push "%Z% %M% %I% %E% %U%" system::*module-identifications*))

;;; Technology.
;;;
;;; The LOOP iteration macro is one of a number of pieces of code
;;; originally developed at MIT for which free distribution has been
;;; permitted, as long as the code is not sold for profit, and as long
;;; as notification of MIT's interest in the code is preserved.
;;;
;;; This version of LOOP, which is almost entirely rewritten both as
;;; clean-up and to conform with the ANSI Lisp LOOP standard, started
;;; life as MIT LOOP version 829 (which was a part of NIL, possibly
;;; never released).
;;;
;;; A "light revision" was performed by me (Glenn Burke) while at
;;; Palladian Software in April 1986, to make the code run in Common
;;; Lisp.  This revision was informally distributed to a number of
;;; people, and was sort of the "MIT" version of LOOP for running in
;;; Common Lisp.
;;;
;;; A later more drastic revision was performed at Palladian perhaps a
;;; year later.  This version was more thoroughly Common Lisp in style,
;;; with a few miscellaneous internal improvements and extensions.  I
;;; have lost track of this source, apparently never having moved it to
;;; the MIT distribution point.  I do not remember if it was ever
;;; distributed.
;;;
;;; This revision for the ANSI standard is based on the code of my April
;;; 1986 version, with almost everything redesigned and/or rewritten.


;;; The design of this LOOP is intended to permit, using mostly the same
;;; kernel of code, up to three different "loop" macros:
;;; 
;;; (1) The unextended, unextensible ANSI standard LOOP;
;;;
;;; (2) A clean "superset" extension of the ANSI LOOP which provides
;;; functionality similar to that of the old LOOP, but "in the style of"
;;; the ANSI LOOP.  For instance, user-definable iteration paths, with a
;;; somewhat cleaned-up interface.
;;;
;;; (3) Extensions provided in another file which can make this LOOP
;;; kernel behave largely compatibly with the Genera-vintage LOOP macro,
;;; with only a small addition of code (instead of two whole, separate,
;;; LOOP macros).
;;;
;;; Each of the above three LOOP variations can coexist in the same LISP
;;; environment.
;;; 


;;;; Miscellaneous Environment Things



;;;The LOOP-Prefer-POP feature makes LOOP generate code which "prefers" to use POP or
;;; its obvious expansion (prog1 (car x) (setq x (cdr x))).  Usually this involves
;;; shifting fenceposts in an iteration or series of carcdr operations.  This is
;;; primarily recognized in the list iterators (FOR .. {IN,ON}), and LOOP's
;;; destructuring setq code.
(eval-when (compile load eval)
  #+(or Genera Minima) (pushnew :LOOP-Prefer-POP *features*)
  )


;;; The uses of this macro are retained in the CL version of loop, in
;;; case they are needed in a particular implementation.  Originally
;;; dating from the use of the Zetalisp COPYLIST* function, this is used
;;; in situations where, were cdr-coding in use, having cdr-NIL at the
;;; end of the list might be suboptimal because the end of the list will
;;; probably be RPLACDed and so cdr-normal should be used instead.
(defmacro loop-copylist* (l)
  #+Genera `(lisp:copy-list ,l nil t)		; arglist = (list &optional area force-dotted)
  ;;Explorer??
  #-Genera `(copy-list ,l)
  )

(defvar *loop-real-data-type* 'real)

(defun loop-optimization-quantities (env)
  ;; The ANSI conditionalization here is for those lisps that implement
  ;; DECLARATION-INFORMATION (from cleanup SYNTACTIC-ENVIRONMENT-ACCESS).
  ;; It is really commentary on how this code could be written.  I don't
  ;; actually expect there to be an ANSI #+-conditional -- it should be
  ;; replaced with the appropriate conditional name for your
  ;; implementation/dialect.
  (declare #-ANSI (ignore env)
	   #+Genera (values speed space safety compilation-speed debug))
  #+ANSI (let ((stuff (declaration-information 'optimize env)))
	   (values (or (cdr (assoc 'speed stuff)) 1)
		   (or (cdr (assoc 'space stuff)) 1)
		   (or (cdr (assoc 'safety stuff)) 1)
		   (or (cdr (assoc 'compilation-speed stuff)) 1)
		   (or (cdr (assoc 'debug stuff)) 1)))
  #+CLOE-Runtime (values compiler::time compiler::space
			 compiler::safety compiler::compilation-speed 1)
  #-(or ANSI CLOE-Runtime) (values 1 1 1 1 1))


;;; The following form takes a list of variables and a form which presumably
;;; references those variables, and wraps it somehow so that the compiler does not
;;; consider those variables have been referenced.  The intent of this is that
;;; iteration variables can be flagged as unused by the compiler, e.g. I in
;;; (loop for i from 1 to 10 do (print t)), since we will tell it when a usage
;;; of it is "invisible" or "not to be considered".
;;;We implicitly assume that a setq does not count as a reference.  That is, the
;;; kind of form generated for the above loop construct to step I, simplified, is
;;; `(SETQ I ,(HIDE-VARIABLE-REFERENCES '(I) '(1+ I))).
(defun hide-variable-references (variable-list form)
  (declare #-Genera (ignore variable-list))
  #+Genera (if variable-list `(compiler:invisible-references ,variable-list ,form) form)
  #-Genera form)


;;; The following function takes a flag, a variable, and a form which presumably
;;; references that variable, and wraps it somehow so that the compiler does not
;;; consider that variable to have been referenced.  The intent of this is that
;;; iteration variables can be flagged as unused by the compiler, e.g. I in
;;; (loop for i from 1 to 10 do (print t)), since we will tell it when a usage
;;; of it is "invisible" or "not to be considered".
;;;We implicitly assume that a setq does not count as a reference.  That is, the
;;; kind of form generated for the above loop construct to step I, simplified, is
;;; `(SETQ I ,(HIDE-VARIABLE-REFERENCES T 'I '(1+ I))).
;;;Certain cases require that the "invisibility" of the reference be conditional upon
;;; something.  This occurs in cases of "named" variables (the USING clause).  For instance,
;;; we want IDX in (LOOP FOR E BEING THE VECTOR-ELEMENTS OF V USING (INDEX IDX) ...)
;;; to be "invisible" when it is stepped, so that the user gets informed if IDX is
;;; not referenced.  However, if no USING clause is present, we definitely do not
;;; want to be informed that some random gensym is not used.
;;;It is easier for the caller to do this conditionally by passing a flag (which
;;; happens to be the second value of NAMED-VARIABLE, q.v.) to this function than
;;; for all callers to contain the conditional invisibility construction.
(defun hide-variable-reference (really-hide variable form)
  (declare #-Genera (ignore really-hide variable))
  #+Genera (if (and really-hide variable (atom variable))	;Punt on destructuring patterns
	       `(compiler:invisible-references (,variable) ,form)
	       form)
  #-Genera form)


;;;; List Collection Macrology


(defmacro with-loop-list-collection-head ((head-var tail-var &optional user-head-var)
					  &body body)
  ;; TI? Exploder?
  #+LISPM (let ((head-place (or user-head-var head-var)))
	    `(let* ((,head-place nil)
		    (,tail-var
		      ,(hide-variable-reference
			 user-head-var user-head-var
			 `(progn #+Genera (scl:locf ,head-place)
				 #-Genera (system:variable-location ,head-place)))))
	       ,@body))
  #-LISPM (let ((l (and user-head-var (list (list user-head-var nil)))))
	    #+CLOE `(sys::with-stack-list* (,head-var nil nil)
		      (let ((,tail-var ,head-var) ,@l)
			,@body))
	    #-CLOE `(let* ((,head-var (list nil)) (,tail-var ,head-var) ,@l)
		      ,@body)))


(defmacro loop-collect-rplacd (&environment env
			       (head-var tail-var &optional user-head-var) form)
  (declare
    #+LISPM (ignore head-var user-head-var)	;use locatives, unconditionally update through the tail.
    )
  (setq form (macroexpand form env))
  (flet ((cdr-wrap (form n)
	   (declare (fixnum n))
	   (do () ((<= n 4) (setq form `(,(case n
					    (1 'cdr)
					    (2 'cddr)
					    (3 'cdddr)
					    (4 'cddddr))
					 ,form)))
	     (setq form `(cddddr ,form) n (- n 4)))))
    (let ((tail-form form) (ncdrs nil))
      ;;Determine if the form being constructed is a list of known length.
      (when (consp form)
	(cond ((eq (car form) 'list)
	       (setq ncdrs (1- (length (cdr form))))
	       ;; Because the last element is going to be RPLACDed,
	       ;; we don't want the cdr-coded implementations to use
	       ;; cdr-nil at the end (which would just force copying
	       ;; the whole list again).
	       #+LISPM (setq tail-form `(list* ,@(cdr form) nil)))
	      ((member (car form) '(list* cons))
	       (when (and (cddr form) (member (car (last form)) '(nil 'nil)))
		 (setq ncdrs (- (length (cdr form)) 2))))))
      (let ((answer
	      (cond ((null ncdrs)
		     `(when (setf (cdr ,tail-var) ,tail-form)
			(setq ,tail-var (last (cdr ,tail-var)))))
		    ((< ncdrs 0) (return-from loop-collect-rplacd nil))
		    ((= ncdrs 0)
		     ;; Here we have a choice of two idioms:
		     ;; (rplacd tail (setq tail tail-form))
		     ;; (setq tail (setf (cdr tail) tail-form)).
		     ;;Genera and most others I have seen do better with the former.
		     `(rplacd ,tail-var (setq ,tail-var ,tail-form)))
		    (t `(setq ,tail-var ,(cdr-wrap `(setf (cdr ,tail-var) ,tail-form)
						   ncdrs))))))
	;;If not using locatives or something similar to update the user's
	;; head variable, we've got to set it...  It's harmless to repeatedly set it
	;; unconditionally, and probably faster than checking.
	#-LISPM (when user-head-var
		  (setq answer `(progn ,answer (setq ,user-head-var (cdr ,head-var)))))
	answer))))


(defmacro loop-collect-answer (head-var &optional user-head-var)
  (or user-head-var
      (progn
	;;If we use locatives to get tail-updating to update the head var,
	;; then the head var itself contains the answer.  Otherwise we
	;; have to cdr it.
	#+LISPM head-var
	#-LISPM `(cdr ,head-var))))



;;;; Maximization Technology

#|
The basic idea of all this minimax randomness here is that we have to
have constructed all uses of maximize and minimize to a particular
"destination" before we can decide how to code them.  The goal is to not
have to have any kinds of flags, by knowing both that (1) the type is
something which we can provide an initial minimum or maximum value for
and (2) know that a MAXIMIZE and MINIMIZE are not being combined.

SO, we have a datastructure which we annotate with all sorts of things,
incrementally updating it as we generate loop body code, and then use
a wrapper and internal macros to do the coding when the loop has been
constructed.
|#


(defstruct (loop-minimax
	     #+mkcl (:type vector)
	     (:constructor make-loop-minimax-internal)
	     #+nil (:copier nil)
	     #+nil (:predicate nil))
  answer-variable
  type
  temp-variable
  flag-variable
  operations
  infinity-data)


(defvar *loop-minimax-type-infinities-alist*
	;; This is the sort of value this should take on for a Lisp that has
	;; "eminently usable" infinities.  n.b. there are neither constants nor
	;; printed representations for infinities defined by CL.
	;; This grotesque read-from-string below is to help implementations
	;; which croak on the infinity character when it appears in a token, even
	;; conditionalized out.
; 	#+Genera
; 	  '#.(read-from-string
; 	      "((fixnum 	most-positive-fixnum	 most-negative-fixnum)
; 		(short-float 	+1s			 -1s)
; 		(single-float	+1f			 -1f)
; 		(double-float	+1d			 -1d)
; 		(long-float	+1l			 -1l))")
	;;This is how the alist should look for a lisp that has no infinities.  In
	;; that case, MOST-POSITIVE-x-FLOAT really IS the most positive.
	#+(or CLOE-Runtime Minima)
	  '((fixnum   		most-positive-fixnum		most-negative-fixnum)
	    (short-float	most-positive-short-float	most-negative-short-float)
	    (single-float	most-positive-single-float	most-negative-single-float)
	    (double-float	most-positive-double-float	most-negative-double-float)
	    (long-float		most-positive-long-float	most-negative-long-float))
	;; CMUCL has infinities so let's use them.
	#+CMU
	  '((fixnum		most-positive-fixnum			most-negative-fixnum)
	    (short-float	ext:single-float-positive-infinity	ext:single-float-negative-infinity)
	    (single-float	ext:single-float-positive-infinity	ext:single-float-negative-infinity)
	    (double-float	ext:double-float-positive-infinity	ext:double-float-negative-infinity)
	    (long-float		ext:long-float-positive-infinity	ext:long-float-negative-infinity))
	;; If we don't know, then we cannot provide "infinite" initial values for any of the
	;; types but FIXNUM:
	#-(or Genera CLOE-Runtime Minima CMU)
	  '((fixnum   		most-positive-fixnum		most-negative-fixnum))
	  )


(defun make-loop-minimax (answer-variable type)
  (let ((infinity-data (cdr (assoc type *loop-minimax-type-infinities-alist* :test #'subtypep))))
    (make-loop-minimax-internal
      :answer-variable answer-variable
      :type type
      :temp-variable (gensym "LOOP-MAXMIN-TEMP-")
      :flag-variable (and (not infinity-data) (gensym "LOOP-MAXMIN-FLAG-"))
      :operations nil
      :infinity-data infinity-data)))


(defun loop-note-minimax-operation (operation minimax)
  (pushnew (the symbol operation) (loop-minimax-operations minimax))
  (when (and (cdr (loop-minimax-operations minimax))
	     (not (loop-minimax-flag-variable minimax)))
    (setf (loop-minimax-flag-variable minimax) (gensym "LOOP-MAXMIN-FLAG-")))
  operation)


(defmacro with-minimax-value (lm &body body)
  (let ((init (loop-typed-init (loop-minimax-type lm)))
	(which (car (loop-minimax-operations lm)))
	(infinity-data (loop-minimax-infinity-data lm))
	(answer-var (loop-minimax-answer-variable lm))
	(temp-var (loop-minimax-temp-variable lm))
	(flag-var (loop-minimax-flag-variable lm))
	(type (loop-minimax-type lm)))
    (if flag-var
	`(let ((,answer-var ,init) (,temp-var ,init) (,flag-var nil))
	   (declare (type ,type ,answer-var ,temp-var))
	   ,@body)
	`(let ((,answer-var ,(if (eq which 'min) (first infinity-data) (second infinity-data)))
	       (,temp-var ,init))
	   (declare (type ,type ,answer-var ,temp-var))
	   ,@body))))


(defmacro loop-accumulate-minimax-value (lm operation form)
  (let* ((answer-var (loop-minimax-answer-variable lm))
	 (temp-var (loop-minimax-temp-variable lm))
	 (flag-var (loop-minimax-flag-variable lm))
	 (test
	   (hide-variable-reference
	     t (loop-minimax-answer-variable lm)
	     `(,(ecase operation
		  (min '<)
		  (max '>))
	       ,temp-var ,answer-var))))
    `(progn
       (setq ,temp-var ,form)
       (when ,(if flag-var `(or (not ,flag-var) ,test) test)
	 (setq ,@(and flag-var `(,flag-var t))
	       ,answer-var ,temp-var)))))



;;;; Loop Keyword Tables

#|
LOOP keyword tables are hash tables string keys and a test of EQUAL.

The actual descriptive/dispatch structure used by LOOP is called a "loop
universe" contains a few tables and parameterizations.  The basic idea is
that we can provide a non-extensible ANSI-compatible loop environment,
an extensible ANSI-superset loop environment, and (for such environments
as CLOE) one which is "sufficiently close" to the old Genera-vintage
LOOP for use by old user programs without requiring all of the old LOOP
code to be loaded.
|#


;;;; Token Hackery


;;;Compare two "tokens".  The first is the frob out of *LOOP-SOURCE-CODE*,
;;; the second a symbol to check against.
(defun loop-tequal (x1 x2)
  (and (symbolp x1) (string= x1 x2)))


(defun loop-tassoc (kwd alist)
  (and (symbolp kwd) (assoc kwd alist :test #'string=)))


(defun loop-tmember (kwd list)
  (and (symbolp kwd) (member kwd list :test #'string=)))


(defun loop-lookup-keyword (loop-token table)
  (and (symbolp loop-token)
       (values (gethash (symbol-name loop-token) table))))


(defmacro loop-store-table-data (symbol table datum)
  `(setf (gethash (symbol-name ,symbol) ,table) ,datum))


(defstruct (loop-universe
	     #+mkcl (:type vector)
	     #-mkcl (:print-function print-loop-universe)
	     #+nil (:copier nil)
	     #+nil (:predicate nil))
  keywords					;hash table, value = (fn-name . extra-data).
  iteration-keywords				;hash table, value = (fn-name . extra-data).
  for-keywords					;hash table, value = (fn-name . extra-data).
  path-keywords					;hash table, value = (fn-name . extra-data).
  type-symbols					;hash table of type SYMBOLS, test EQ, value = CL type specifier.
  type-keywords					;hash table of type STRINGS, test EQUAL, value = CL type spec.
  ansi						;NIL, T, or :EXTENDED.
  implicit-for-required				;see loop-hack-iteration
  )


#-mkcl
(defun print-loop-universe (u stream level)
  (declare (ignore level))
  (let ((str (case (loop-universe-ansi u)
	       ((nil) "Non-ANSI")
	       ((t) "ANSI")
	       (:extended "Extended-ANSI")
	       (t (loop-universe-ansi u)))))
    ;;Cloe could be done with the above except for bootstrap lossage...
    #+CLOE
    (format stream "#<~S ~A ~X>" (type-of u) str (sys::address-of u))
    #+Genera					; This is reallly the ANSI definition.
    (print-unreadable-object (u stream :type t :identity t)
      (princ str stream))
    #-(or Genera CLOE)
    (format stream "#<~S ~A>" (type-of u) str)
    ))


;;;This is the "current" loop context in use when we are expanding a
;;;loop.  It gets bound on each invocation of LOOP.
(defvar *loop-universe*)


(defun make-standard-loop-universe (&key keywords for-keywords iteration-keywords path-keywords
				    type-keywords type-symbols ansi)
  #-(and CLOE Source-Bootstrap mkcl) (check-type ansi (member nil t :extended))
  (flet ((maketable (entries)
	   (let* ((size (length entries))
		  (ht (make-hash-table :size (if (< size 10) 10 size) :test #'equal)))
	     (dolist (x entries) (setf (gethash (symbol-name (car x)) ht) (cadr x)))
	     ht)))
    (make-loop-universe
      :keywords (maketable keywords)
      :for-keywords (maketable for-keywords)
      :iteration-keywords (maketable iteration-keywords)
      :path-keywords (maketable path-keywords)
      :ansi ansi
      :implicit-for-required (not (null ansi))
      :type-keywords (maketable type-keywords)
      :type-symbols (let* ((size (length type-symbols))
			   (ht (make-hash-table :size (if (< size 10) 10 size) :test #'eq)))
		      (dolist (x type-symbols)
			(if (atom x) (setf (gethash x ht) x) (setf (gethash (car x) ht) (cadr x))))
		      ht)))) 


;;;; Setq Hackery


(defvar *loop-destructuring-hooks*
	nil
  "If not NIL, this must be a list of two things:
a LET-like macro, and a SETQ-like macro, which perform LOOP-style destructuring.")


(defun loop-make-psetq (frobs)
  (and frobs
       (loop-make-desetq
	 (list (car frobs)
	       (if (null (cddr frobs)) (cadr frobs)
		   `(prog1 ,(cadr frobs)
			   ,(loop-make-psetq (cddr frobs))))))))


(defun loop-make-desetq (var-val-pairs)
  (if (null var-val-pairs)
      nil
      (cons (if *loop-destructuring-hooks*
		(cadr *loop-destructuring-hooks*)
		'loop-really-desetq)
	    var-val-pairs)))


(defvar *loop-desetq-temporary*
	(make-symbol "LOOP-DESETQ-TEMP"))


(defmacro loop-really-desetq (&environment env &rest var-val-pairs)
  (labels ((find-non-null (var)
	     ;; see if there's any non-null thing here
	     ;; recurse if the list element is itself a list
	     (do ((tail var)) ((not (consp tail)) tail)
	       (when (find-non-null (pop tail)) (return t))))
	   (loop-desetq-internal (var val &optional temp)
	     ;; returns a list of actions to be performed
	     (typecase var
	       (null
		 (when (consp val)
		   ;; don't lose possible side-effects
		   (if (eq (car val) 'prog1)
		       ;; these can come from psetq or desetq below.
		       ;; throw away the value, keep the side-effects.
		       ;;Special case is for handling an expanded POP.
		       (mapcan #'(lambda (x)
				   (and (consp x)
					(or (not (eq (car x) 'car))
					    (not (symbolp (cadr x)))
					    (not (symbolp (setq x (macroexpand x env)))))
					(cons x nil)))
			       (cdr val))
		       `(,val))))
	       (cons
		 (let* ((car (car var))
			(cdr (cdr var))
			(car-non-null (find-non-null car))
			(cdr-non-null (find-non-null cdr)))
		   (when (or car-non-null cdr-non-null)
		     (if cdr-non-null
			 (let* ((temp-p temp)
				(temp (or temp *loop-desetq-temporary*))
				(body #+LOOP-Prefer-POP `(,@(loop-desetq-internal
							      car
							      `(prog1 (car ,temp)
								      (setq ,temp (cdr ,temp))))
							  ,@(loop-desetq-internal cdr temp temp))
				      #-LOOP-Prefer-POP `(,@(loop-desetq-internal car `(car ,temp))
							  (setq ,temp (cdr ,temp))
							  ,@(loop-desetq-internal cdr temp temp))))
			   (if temp-p
			       `(,@(unless (eq temp val)
				     `((setq ,temp ,val)))
				 ,@body)
			       `((let ((,temp ,val))
				   ,@body))))
			 ;; no cdring to do
			 (loop-desetq-internal car `(car ,val) temp)))))
	       (otherwise
		 (unless (eq var val)
		   `((setq ,var ,val)))))))
    (do ((actions))
	((null var-val-pairs)
	 (if (null (cdr actions)) (car actions) `(progn ,@(nreverse actions))))
      (setq actions (revappend
		      (loop-desetq-internal (pop var-val-pairs) (pop var-val-pairs))
		      actions)))))


;;;; LOOP-local variables

;;;This is the "current" pointer into the LOOP source code.
(defvar *loop-source-code*)


;;;This is the pointer to the original, for things like NAMED that
;;;insist on being in a particular position
(defvar *loop-original-source-code*)


;;;This is *loop-source-code* as of the "last" clause.  It is used
;;;primarily for generating error messages (see loop-error, loop-warn).
(defvar *loop-source-context*)


;;;List of names for the LOOP, supplied by the NAMED clause.
(defvar *loop-names*)

;;;The macroexpansion environment given to the macro.
(defvar *loop-macro-environment*)

;;;This holds variable names specified with the USING clause.
;;; See LOOP-NAMED-VARIABLE.
(defvar *loop-named-variables*)

;;; LETlist-like list being accumulated for one group of parallel bindings.
(defvar *loop-variables*)

;;;List of declarations being accumulated in parallel with
;;;*loop-variables*.
(defvar *loop-declarations*)

;;;Used by LOOP for destructuring binding, if it is doing that itself.
;;; See loop-make-variable.
(defvar *loop-desetq-crocks*)

;;; List of wrapping forms, innermost first, which go immediately inside
;;; the current set of parallel bindings being accumulated in
;;; *loop-variables*.  The wrappers are appended onto a body.  E.g.,
;;; this list could conceivably has as its value ((with-open-file (g0001
;;; g0002 ...))), with g0002 being one of the bindings in
;;; *loop-variables* (this is why the wrappers go inside of the variable
;;; bindings).
(defvar *loop-wrappers*)

;;;This accumulates lists of previous values of *loop-variables* and the
;;;other lists  above, for each new nesting of bindings.  See
;;;loop-bind-block.
(defvar *loop-bind-stack*)

;;;This is a LOOP-global variable for the (obsolete) NODECLARE clause
;;;which inhibits  LOOP from actually outputting a type declaration for
;;;an iteration (or any) variable.
(defvar *loop-nodeclare*)

;;;This is simply a list of LOOP iteration variables, used for checking
;;;for duplications.
(defvar *loop-iteration-variables*)


;;;List of prologue forms of the loop, accumulated in reverse order.
(defvar *loop-prologue*)

(defvar *loop-before-loop*)
(defvar *loop-body*)
(defvar *loop-after-body*)

;;;This is T if we have emitted any body code, so that iteration driving
;;;clauses can be disallowed.   This is not strictly the same as
;;;checking *loop-body*, because we permit some clauses  such as RETURN
;;;to not be considered "real" body (so as to permit the user to "code"
;;;an  abnormal return value "in loop").
(defvar *loop-emitted-body*)


;;;List of epilogue forms (supplied by FINALLY generally), accumulated
;;; in reverse order.
(defvar *loop-epilogue*)

;;;List of epilogue forms which are supplied after the above "user"
;;;epilogue.  "normal" termination return values are provide by putting
;;;the return form in here.  Normally this is done using
;;;loop-emit-final-value, q.v.
(defvar *loop-after-epilogue*)

;;;The "culprit" responsible for supplying a final value from the loop.
;;;This  is so loop-emit-final-value can moan about multiple return
;;;values being supplied.
(defvar *loop-final-value-culprit*)

;;;If not NIL, we are in some branch of a conditional.  Some clauses may
;;;be disallowed.
(defvar *loop-inside-conditional*)

;;;If not NIL, this is a temporary bound around the loop for holding the
;;;temporary  value for "it" in things like "when (f) collect it".  It
;;;may be used as a supertemporary by some other things.
(defvar *loop-when-it-variable*)

;;;Sometimes we decide we need to fold together parts of the loop, but
;;;some part of the generated iteration  code is different for the first
;;;and remaining iterations.  This variable will be the temporary which 
;;;is the flag used in the loop to tell whether we are in the first or
;;;remaining iterations.
(defvar *loop-never-stepped-variable*)

;;;List of all the value-accumulation descriptor structures in the loop.
;;; See loop-get-collection-info.
(defvar *loop-collection-cruft*)		; for multiple COLLECTs (etc)


;;;; Code Analysis Stuff


(defun loop-constant-fold-if-possible (form &optional expected-type)
  #+Genera (declare (values new-form constantp constant-value))
  (let ((new-form form) (constantp nil) (constant-value nil))
    #+Genera (setq new-form (compiler:optimize-form form *loop-macro-environment*
						    :repeat t
						    :do-macro-expansion t
						    :do-named-constants t
						    :do-inline-forms t
						    :do-optimizers t
						    :do-constant-folding t
						    :do-function-args t)
		   constantp (constantp new-form *loop-macro-environment*)
		   constant-value (and constantp (lt:evaluate-constant new-form *loop-macro-environment*)))
    #-Genera (when (setq constantp (constantp new-form))
	       (setq constant-value (eval new-form)))
    (when (and constantp expected-type)
      (unless (typep constant-value expected-type)
	(loop-warn "The form ~S evaluated to ~S, which was not of the anticipated type ~S."
		   form constant-value expected-type)
	(setq constantp nil constant-value nil)))
    (values new-form constantp constant-value)))


(defun loop-constantp (form)
  #+Genera (constantp form *loop-macro-environment*)
  #-Genera (constantp form))


;;;; LOOP Iteration Optimization

(defvar *loop-duplicate-code*
	nil)


(defvar *loop-iteration-flag-variable*
	(make-symbol "LOOP-NOT-FIRST-TIME"))


(defun loop-code-duplication-threshold (env)
  (multiple-value-bind (speed space) (loop-optimization-quantities env)
    (+ 40 (* (- speed space) 10))))


(defmacro loop-body (&environment env
		     prologue
		     before-loop
		     main-body
		     after-loop
		     epilogue
		     &aux rbefore rafter flagvar)
  (unless (= (length before-loop) (length after-loop))
    (error "LOOP-BODY called with non-synched before- and after-loop lists."))
  ;;All our work is done from these copies, working backwards from the end:
  (setq rbefore (reverse before-loop) rafter (reverse after-loop))
  (labels ((psimp (l)
	     (let ((ans nil))
	       (dolist (x l)
		 (when x
		   (push x ans)
		   (when (and (consp x) (member (car x) '(go return return-from)))
		     (return nil))))
	       (nreverse ans)))
	   (pify (l) (if (null (cdr l)) (car l) `(progn ,@l)))
	   (makebody ()
	     (let ((form `(tagbody
			    ,@(psimp (append prologue (nreverse rbefore)))
			 next-loop
			    ,@(psimp (append main-body (nreconc rafter `((go next-loop)))))
			 end-loop
			    ,@(psimp epilogue))))
	       (if flagvar `(let ((,flagvar nil)) ,form) form))))
    (when (or *loop-duplicate-code* (not rbefore))
      (return-from loop-body (makebody)))
    ;; This outer loop iterates once for each not-first-time flag test generated
    ;; plus once more for the forms that don't need a flag test
    (do ((threshold (loop-code-duplication-threshold env))) (nil)
      (declare (fixnum threshold))
      ;; Go backwards from the ends of before-loop and after-loop merging all the equivalent
      ;; forms into the body.
      (do () ((or (null rbefore) (not (equal (car rbefore) (car rafter)))))
	(push (pop rbefore) main-body)
	(pop rafter))
      (unless rbefore (return (makebody)))
      ;; The first forms in rbefore & rafter (which are the chronologically
      ;; last forms in the list) differ, therefore they cannot be moved
      ;; into the main body.  If everything that chronologically precedes
      ;; them either differs or is equal but is okay to duplicate, we can
      ;; just put all of rbefore in the prologue and all of rafter after
      ;; the body.  Otherwise, there is something that is not okay to
      ;; duplicate, so it and everything chronologically after it in
      ;; rbefore and rafter must go into the body, with a flag test to
      ;; distinguish the first time around the loop from later times.
      ;; What chronologically precedes the non-duplicatable form will
      ;; be handled the next time around the outer loop.
      (do ((bb rbefore (cdr bb)) (aa rafter (cdr aa)) (lastdiff nil) (count 0) (inc nil))
	  ((null bb) (return-from loop-body (makebody)))	;Did it.
	(cond ((not (equal (car bb) (car aa))) (setq lastdiff bb count 0))
	      ((or (not (setq inc (estimate-code-size (car bb) env)))
		   (> (incf count inc) threshold))
	       ;; Ok, we have found a non-duplicatable piece of code.  Everything
	       ;; chronologically after it must be in the central body.
	       ;; Everything chronologically at and after lastdiff goes into the
	       ;; central body under a flag test.
	       (let ((then nil) (else nil))
		 (do () (nil)
		   (push (pop rbefore) else)
		   (push (pop rafter) then)
		   (when (eq rbefore (cdr lastdiff)) (return)))
		 (unless flagvar
		   (push `(setq ,(setq flagvar *loop-iteration-flag-variable*) t) else))
		 (push `(if ,flagvar ,(pify (psimp then)) ,(pify (psimp else)))
		       main-body))
	       ;; Everything chronologically before lastdiff until the non-duplicatable form (car bb) 
	       ;; is the same in rbefore and rafter so just copy it into the body
	       (do () (nil)
		 (pop rafter)
		 (push (pop rbefore) main-body)
		 (when (eq rbefore (cdr bb)) (return)))
	       (return)))))))



(defun duplicatable-code-p (expr env)
  (if (null expr) 0
      (let ((ans (estimate-code-size expr env)))
	(declare (fixnum ans))
	;; Use (DECLARATION-INFORMATION 'OPTIMIZE ENV) here to get an alist of
	;; optimize quantities back to help quantify how much code we are willing to
	;; duplicate.
	ans)))


(defvar *special-code-sizes*
	'((return 0) (progn 0)
	  (null 1) (not 1) (eq 1) (car 1) (cdr 1)
	  (when 1) (unless 1) (if 1)
	  (caar 2) (cadr 2) (cdar 2) (cddr 2)
	  (caaar 3) (caadr 3) (cadar 3) (caddr 3) (cdaar 3) (cdadr 3) (cddar 3) (cdddr 3)
	  (caaaar 4) (caaadr 4) (caadar 4) (caaddr 4)
	  (cadaar 4) (cadadr 4) (caddar 4) (cadddr 4)
	  (cdaaar 4) (cdaadr 4) (cdadar 4) (cdaddr 4)
	  (cddaar 4) (cddadr 4) (cdddar 4) (cddddr 4)))


(defvar *estimate-code-size-punt*
	'(block
	   do do* dolist
	   flet
	   labels lambda let let* locally
	   macrolet multiple-value-bind
	   prog prog*
	   symbol-macrolet
	   tagbody
	   unwind-protect
	   with-open-file))


(defun destructuring-size (x)
  (do ((x x (cdr x)) (n 0 (+ (destructuring-size (car x)) n)))
      ((atom x) (+ n (if (null x) 0 1)))))


(defun estimate-code-size (x env)
  (catch 'estimate-code-size
    (estimate-code-size-1 x env)))


(defun estimate-code-size-1 (x env)
  (flet ((list-size (l)
	   (let ((n 0))
	     (declare (fixnum n))
	     (dolist (x l n) (incf n (estimate-code-size-1 x env))))))
    ;; ???? (declare (function list-size (list) fixnum))
    (cond ((constantp x #+Genera env) 1)
	  ((symbolp x) (multiple-value-bind (new-form expanded-p) (macroexpand-1 x env)
			 (if expanded-p (estimate-code-size-1 new-form env) 1)))
	  ((atom x) 1)				;??? self-evaluating???
	  ((symbolp (car x))
	   (let ((fn (car x)) (tem nil) (n 0))
	     (declare (symbol fn) (fixnum n))
	     (macrolet ((f (overhead &optional (args nil args-p))
			  `(the fixnum (+ (the fixnum ,overhead)
					  (the fixnum (list-size ,(if args-p args '(cdr x))))))))
	       (cond ((setq tem (get-sysprop fn 'estimate-code-size))
		      (typecase tem
			(fixnum (f tem))
			(t (funcall tem x env))))
		     ((setq tem (assoc fn *special-code-sizes*)) (f (second tem)))
		     #+Genera
		     ((eq fn 'compiler:invisible-references) (list-size (cddr x)))
		     ((eq fn 'cond)
		      (dolist (clause (cdr x) n) (incf n (list-size clause)) (incf n)))
		     ((eq fn 'desetq)
		      (do ((l (cdr x) (cdr l))) ((null l) n)
			(setq n (+ n (destructuring-size (car l)) (estimate-code-size-1 (cadr l) env)))))
		     ((member fn '(setq psetq))
		      (do ((l (cdr x) (cdr l))) ((null l) n)
			(setq n (+ n (estimate-code-size-1 (cadr l) env) 1))))
		     ((eq fn 'go) 1)
		     ((eq fn 'function)
		      ;;This skirts the issue of implementationally-defined lambda macros
		      ;; by recognizing CL function names and nothing else.
		      (if (or (symbolp (cadr x))
			      (and (consp (cadr x)) (eq (caadr x) 'setf)))
			  1
			  (throw 'duplicatable-code-p nil)))
		     ((eq fn 'multiple-value-setq) (f (length (second x)) (cddr x)))
		     ((eq fn 'return-from) (1+ (estimate-code-size-1 (third x) env)))
		     ((or (special-operator-p fn) (member fn *estimate-code-size-punt*))
		      (throw 'estimate-code-size nil))
		     (t (multiple-value-bind (new-form expanded-p) (macroexpand-1 x env)
			  (if expanded-p
			      (estimate-code-size-1 new-form env)
			      (f 3))))))))
	  (t (throw 'estimate-code-size nil)))))


;;;; Loop Errors


(defun loop-context ()
  (do ((l *loop-source-context* (cdr l)) (new nil (cons (car l) new)))
      ((eq l (cdr *loop-source-code*)) (nreverse new))))


(defun loop-error (format-string &rest format-args)
  (si::simple-program-error "~?~%Current LOOP context:~{ ~S~}."
			    format-string format-args (loop-context)))


(defun loop-warn (format-string &rest format-args)
  (warn "~?~%Current LOOP context:~{ ~S~}." format-string format-args (loop-context)))


(defun loop-check-data-type (specified-type required-type
			     &optional (default-type required-type))
  (if (null specified-type)
      default-type
      (multiple-value-bind (a b) (subtypep specified-type required-type)
	(cond ((not b)
	       (loop-warn "LOOP couldn't verify that ~S is a subtype of the required type ~S."
			  specified-type required-type))
	      ((not a)
	       (loop-error "Specified data type ~S is not a subtype of ~S."
			   specified-type required-type)))
	specified-type)))


;;;INTERFACE: Traditional, ANSI, Lucid.
(defmacro loop-finish () 
  "Causes the iteration to terminate \"normally\", the same as implicit
termination by an iteration driving clause, or by use of WHILE or
UNTIL -- the epilogue code (if any) will be run, and any implicitly
collected result will be returned as the value of the LOOP."
  '(go end-loop))



(defun subst-gensyms-for-nil (tree)
  (declare (special *ignores*))
  (cond
    ((null tree) (car (push (gensym) *ignores*)))
    ((atom tree) tree)
    (t (cons (subst-gensyms-for-nil (car tree))
	     (subst-gensyms-for-nil (cdr tree))))))
 
(defun loop-build-destructuring-bindings (crocks forms)
  (if crocks
      (let ((*ignores* ()))
	(declare (special *ignores*))
	`((destructuring-bind ,(subst-gensyms-for-nil (car crocks))
	      ,(cadr crocks)
	    (declare (ignore ,@*ignores*))
	    ,@(loop-build-destructuring-bindings (cddr crocks) forms))))
      forms))

(defun loop-translate (*loop-source-code* *loop-macro-environment* *loop-universe*)