/
loop.lisp
2006 lines (1847 loc) · 73.9 KB
/
loop.lisp
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
;;;; the LOOP iteration macro
;;;; This software is part of the SBCL system. See the README file for
;;;; more information.
;;;; This code was modified by William Harold Newman beginning
;;;; 19981106, originally to conform to the new SBCL bootstrap package
;;;; system and then subsequently to address other cross-compiling
;;;; bootstrap issues, SBCLification (e.g. DECLARE used to check
;;;; argument types), and other maintenance. Whether or not it then
;;;; supported all the environments implied by the reader conditionals
;;;; in the source code (e.g. #!+CLOE-RUNTIME) before that
;;;; modification, it sure doesn't now. It might perhaps, by blind
;;;; luck, be appropriate for some other CMU-CL-derived system, but
;;;; really it only attempts to be appropriate for SBCL.
;;;; This software is derived from software originally released by the
;;;; Massachusetts Institute of Technology and Symbolics, Inc. Copyright and
;;;; release statements follow. Later modifications to the software are in
;;;; the public domain and are provided with absolutely no warranty. See the
;;;; COPYING and CREDITS files for more information.
;;;; 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
(in-package "SB!LOOP")
;;;; 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.
;;;;
;;;; KLUDGE: In SBCL, we only really use variant (1), and any generality
;;;; for the other variants is wasted. -- WHN 20000121
;;;; FIXME: the STEP-FUNCTION stuff in the code seems to've been
;;;; intended to support code which was conditionalized with
;;;; LOOP-PREFER-POP (not true on CMU CL) and which has since been
;;;; removed. Thus, STEP-FUNCTION stuff could probably be removed too.
;;;; list collection macrology
(sb!int:defmacro-mundanely with-loop-list-collection-head
((head-var tail-var &optional user-head-var) &body body)
(let ((l (and user-head-var (list (list user-head-var nil)))))
`(let* ((,head-var (list nil)) (,tail-var ,head-var) ,@l)
,@body)))
(sb!int:defmacro-mundanely loop-collect-rplacd
(&environment env (head-var tail-var &optional user-head-var) form)
(setq form (sb!xc: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 whether the form being constructed is a list of known
;; length.
(when (consp form)
(cond ((eq (car form) 'list)
(setq ncdrs (1- (length (cdr form)))))
((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.
(when user-head-var
(setq answer
`(progn ,answer
(setq ,user-head-var (cdr ,head-var)))))
answer))))
(sb!int:defmacro-mundanely loop-collect-answer (head-var
&optional user-head-var)
(or user-head-var
`(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
(:constructor make-loop-minimax-internal)
(:copier nil)
(:predicate nil))
answer-variable
type
temp-variable
flag-variable
operations
infinity-data)
(defvar *loop-minimax-type-infinities-alist*
;; FIXME: Now that SBCL supports floating point infinities again, we
;; should have floating point infinities here, as cmucl-2.4.8 did.
'((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 #'sb!xc: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)
(sb!int:defmacro-mundanely 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))))
(sb!int:defmacro-mundanely 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 `(,(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))))
(sb!int:defmacro-mundanely loop-store-table-data (symbol table datum)
`(setf (gethash (symbol-name ,symbol) ,table) ,datum))
(defstruct (loop-universe
(:copier 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
(sb!int:def!method print-object ((u loop-universe) stream)
(let ((string (case (loop-universe-ansi u)
((nil) "non-ANSI")
((t) "ANSI")
(:extended "extended-ANSI")
(t (loop-universe-ansi u)))))
(print-unreadable-object (u stream :type t)
(write-string string stream))))
;;; 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)
(declare (type (member nil t :extended) ansi))
(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, including destructuring ("DESETQ")
(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 'loop-really-desetq var-val-pairs)))
(defvar *loop-desetq-temporary*
(make-symbol "LOOP-DESETQ-TEMP"))
(sb!int:defmacro-mundanely loop-really-desetq (&environment env
&rest var-val-pairs)
(labels ((find-non-null (var)
;; See whether 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 (sb!xc: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-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-VAR.
(defvar *loop-named-vars*)
;;; LETlist-like list being accumulated for one group of parallel bindings.
(defvar *loop-vars*)
;;; list of declarations being accumulated in parallel with *LOOP-VARS*
(defvar *loop-declarations*)
;;; This is used by LOOP for destructuring binding, if it is doing
;;; that itself. See LOOP-MAKE-VAR.
(defvar *loop-desetq-crocks*)
;;; list of wrapping forms, innermost first, which go immediately
;;; inside the current set of parallel bindings being accumulated in
;;; *LOOP-VARS*. The wrappers are appended onto a body. E.g.,
;;; this list could conceivably have as its value
;;; ((WITH-OPEN-FILE (G0001 G0002 ...))),
;;; with G0002 being one of the bindings in *LOOP-VARS* (This is
;;; why the wrappers go inside of the variable bindings).
(defvar *loop-wrappers*)
;;; This accumulates lists of previous values of *LOOP-VARS* and
;;; the other lists above, for each new nesting of bindings. See
;;; LOOP-BIND-BLOCK.
(defvar *loop-bind-stack*)
;;; This is simply a list of LOOP iteration variables, used for
;;; checking for duplications.
(defvar *loop-iteration-vars*)
;;; 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 this is true, 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-var*)
;;; 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-var*)
;;; 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)
(let ((new-form form) (constantp nil) (constant-value nil))
(when (setq constantp (constantp new-form))
(setq constant-value (eval new-form)))
(when (and constantp expected-type)
(unless (sb!xc: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)
(constantp form))
;;;; LOOP iteration optimization
(defvar *loop-duplicate-code*
nil)
(defvar *loop-iteration-flag-var*
(make-symbol "LOOP-NOT-FIRST-TIME"))
(defun loop-code-duplication-threshold (env)
(declare (ignore env))
(let (;; If we could read optimization declaration information (as
;; with the DECLARATION-INFORMATION function (present in
;; CLTL2, removed from ANSI standard) we could set these
;; values flexibly. Without DECLARATION-INFORMATION, we have
;; to set them to constants.
(speed 1)
(space 1))
(+ 40 (* (- speed space) 10))))
(sb!int:defmacro-mundanely 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-var*)
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) 1)
((symbolp x) (multiple-value-bind (new-form expanded-p)
(sb!xc: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 fn 'estimate-code-size))
(typecase tem
(fixnum (f tem))
(t (funcall tem x env))))
((setq tem (assoc fn *special-code-sizes*))
(f (second tem)))
((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)
(sb!xc: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)
(error 'sb!int:simple-program-error
:format-control "~?~%current LOOP context:~{ ~S~}."
:format-arguments (list 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) (sb!xc: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 "The specified data type ~S is not a subtype of ~S."
specified-type required-type)))
specified-type)))
(defun subst-gensyms-for-nil (tree)
(declare (special *ignores*))
(cond
((null tree) (car (push (gensym "LOOP-IGNORED-VAR-") *ignores*)))
((atom tree) tree)
(t (cons (subst-gensyms-for-nil (car tree))
(subst-gensyms-for-nil (cdr tree))))))
(sb!int:defmacro-mundanely loop-destructuring-bind
(lambda-list arg-list &rest body)
(let ((*ignores* nil))
(declare (special *ignores*))
(let ((d-var-lambda-list (subst-gensyms-for-nil lambda-list)))
`(destructuring-bind ,d-var-lambda-list
,arg-list
(declare (ignore ,@*ignores*))
,@body))))
(defun loop-build-destructuring-bindings (crocks forms)
(if crocks
`((loop-destructuring-bind ,(car crocks) ,(cadr crocks)
,@(loop-build-destructuring-bindings (cddr crocks) forms)))
forms))
(defun loop-translate (*loop-source-code*
*loop-macro-environment*
*loop-universe*)
(let ((*loop-original-source-code* *loop-source-code*)
(*loop-source-context* nil)
(*loop-iteration-vars* nil)
(*loop-vars* nil)
(*loop-named-vars* nil)
(*loop-declarations* nil)
(*loop-desetq-crocks* nil)
(*loop-bind-stack* nil)
(*loop-prologue* nil)
(*loop-wrappers* nil)
(*loop-before-loop* nil)
(*loop-body* nil)
(*loop-emitted-body* nil)
(*loop-after-body* nil)
(*loop-epilogue* nil)
(*loop-after-epilogue* nil)
(*loop-final-value-culprit* nil)
(*loop-inside-conditional* nil)
(*loop-when-it-var* nil)
(*loop-never-stepped-var* nil)
(*loop-names* nil)
(*loop-collection-cruft* nil))
(loop-iteration-driver)
(loop-bind-block)
(let ((answer `(loop-body
,(nreverse *loop-prologue*)
,(nreverse *loop-before-loop*)
,(nreverse *loop-body*)
,(nreverse *loop-after-body*)
,(nreconc *loop-epilogue*
(nreverse *loop-after-epilogue*)))))
(dolist (entry *loop-bind-stack*)
(let ((vars (first entry))
(dcls (second entry))
(crocks (third entry))
(wrappers (fourth entry)))
(dolist (w wrappers)
(setq answer (append w (list answer))))
(when (or vars dcls crocks)
(let ((forms (list answer)))
;;(when crocks (push crocks forms))
(when dcls (push `(declare ,@dcls) forms))
(setq answer `(,(if vars 'let 'locally)
,vars
,@(loop-build-destructuring-bindings crocks
forms)))))))
(do () (nil)
(setq answer `(block ,(pop *loop-names*) ,answer))
(unless *loop-names* (return nil)))
answer)))
(defun loop-iteration-driver ()
(do () ((null *loop-source-code*))
(let ((keyword (car *loop-source-code*)) (tem nil))
(cond ((not (symbolp keyword))
(loop-error "~S found where LOOP keyword expected" keyword))
(t (setq *loop-source-context* *loop-source-code*)
(loop-pop-source)
(cond ((setq tem
(loop-lookup-keyword keyword
(loop-universe-keywords
*loop-universe*)))
;; It's a "miscellaneous" toplevel LOOP keyword (DO,
;; COLLECT, NAMED, etc.)
(apply (symbol-function (first tem)) (rest tem)))
((setq tem
(loop-lookup-keyword keyword
(loop-universe-iteration-keywords *loop-universe*)))
(loop-hack-iteration tem))
((loop-tmember keyword '(and else))
;; The alternative is to ignore it, i.e. let it go
;; around to the next keyword...
(loop-error "secondary clause misplaced at top level in LOOP macro: ~S ~S ~S ..."
keyword
(car *loop-source-code*)
(cadr *loop-source-code*)))
(t (loop-error "unknown LOOP keyword: ~S" keyword))))))))
(defun loop-pop-source ()
(if *loop-source-code*
(pop *loop-source-code*)
(loop-error "LOOP source code ran out when another token was expected.")))
(defun loop-get-form ()
(if *loop-source-code*
(loop-pop-source)
(loop-error "LOOP code ran out where a form was expected.")))
(defun loop-get-compound-form ()
(let ((form (loop-get-form)))
(unless (consp form)
(loop-error "A compound form was expected, but ~S found." form))
form))
(defun loop-get-progn ()
(do ((forms (list (loop-get-compound-form))
(cons (loop-get-compound-form) forms))
(nextform (car *loop-source-code*)
(car *loop-source-code*)))
((atom nextform)
(if (null (cdr forms)) (car forms) (cons 'progn (nreverse forms))))))
(defun loop-construct-return (form)
`(return-from ,(car *loop-names*) ,form))
(defun loop-pseudo-body (form)
(cond ((or *loop-emitted-body* *loop-inside-conditional*)
(push form *loop-body*))
(t (push form *loop-before-loop*) (push form *loop-after-body*))))
(defun loop-emit-body (form)
(setq *loop-emitted-body* t)
(loop-pseudo-body form))
(defun loop-emit-final-value (&optional (form nil form-supplied-p))
(when form-supplied-p
(push (loop-construct-return form) *loop-after-epilogue*))
(when *loop-final-value-culprit*
(loop-warn "The LOOP clause is providing a value for the iteration;~@
however, one was already established by a ~S clause."
*loop-final-value-culprit*))
(setq *loop-final-value-culprit* (car *loop-source-context*)))
(defun loop-disallow-conditional (&optional kwd)
(when *loop-inside-conditional*
(loop-error "~:[This LOOP~;The LOOP ~:*~S~] clause is not permitted inside a conditional." kwd)))
(defun loop-disallow-anonymous-collectors ()
(when (find-if-not 'loop-collector-name *loop-collection-cruft*)
(loop-error "This LOOP clause is not permitted with anonymous collectors.")))
(defun loop-disallow-aggregate-booleans ()
(when (loop-tmember *loop-final-value-culprit* '(always never thereis))
(loop-error "This anonymous collection LOOP clause is not permitted with aggregate booleans.")))
;;;; loop types
(defun loop-typed-init (data-type)
(when (and data-type (sb!xc:subtypep data-type 'number))
(if (or (sb!xc:subtypep data-type 'float)
(sb!xc:subtypep data-type '(complex float)))
(coerce 0 data-type)
0)))
(defun loop-optional-type (&optional variable)
;; No variable specified implies that no destructuring is permissible.
(and *loop-source-code* ; Don't get confused by NILs..
(let ((z (car *loop-source-code*)))
(cond ((loop-tequal z 'of-type)
;; This is the syntactically unambigous form in that
;; the form of the type specifier does not matter.
;; Also, it is assumed that the type specifier is
;; unambiguously, and without need of translation, a
;; common lisp type specifier or pattern (matching the
;; variable) thereof.
(loop-pop-source)
(loop-pop-source))
((symbolp z)
;; This is the (sort of) "old" syntax, even though we
;; didn't used to support all of these type symbols.
(let ((type-spec (or (gethash z
(loop-universe-type-symbols
*loop-universe*))
(gethash (symbol-name z)
(loop-universe-type-keywords
*loop-universe*)))))
(when type-spec
(loop-pop-source)
type-spec)))
(t
;; This is our sort-of old syntax. But this is only
;; valid for when we are destructuring, so we will be
;; compulsive (should we really be?) and require that
;; we in fact be doing variable destructuring here. We
;; must translate the old keyword pattern typespec
;; into a fully-specified pattern of real type
;; specifiers here.
(if (consp variable)
(unless (consp z)
(loop-error
"~S found where a LOOP keyword, LOOP type keyword, or LOOP type pattern expected"
z))
(loop-error "~S found where a LOOP keyword or LOOP type keyword expected" z))
(loop-pop-source)
(labels ((translate (k v)
(cond ((null k) nil)
((atom k)
(replicate
(or (gethash k
(loop-universe-type-symbols
*loop-universe*))
(gethash (symbol-name k)
(loop-universe-type-keywords
*loop-universe*))
(loop-error
"The destructuring type pattern ~S contains the unrecognized type keyword ~S."
z k))
v))
((atom v)
(loop-error
"The destructuring type pattern ~S doesn't match the variable pattern ~S."
z variable))
(t (cons (translate (car k) (car v))
(translate (cdr k) (cdr v))))))
(replicate (typ v)
(if (atom v)
typ
(cons (replicate typ (car v))
(replicate typ (cdr v))))))
(translate z variable)))))))