/
loop.scm
3980 lines (3444 loc) · 142 KB
/
loop.scm
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
; automatically generated; do not edit
(define loop-expand (let ()
(define-macro (push v s)
(unless (symbol? s) (error))
`(begin (set! ,s (cons ,v ,s)) ,s))
(define (list* . p)
(if (null? (cdr p))
(car p)
(cons (car p) (apply list* (cdr p)))))
; a la j: x f&g y ←→ (f x) g (f y)
; hence, ((& f g) x y z...) ←→ (f (g x) (g y) (g z)...)
(define (compose f g) (lambda args (apply f (map g args))))
; and here: x (f g) y ←→ x f g y
; ((hook f g) x y) ←→ (f x (g y))
(define (hook f g) (lambda (x y) (f x (g y))))
; in particular, cl (higher-order-fn :pred f :key g)
; can be expressed here using simply (higher-order fn :pred (hook f g))
(define (bind f . rest) (lambda args (apply f (append rest args))))
(define (rbind f . rest) (lambda args (apply f (append args rest))))
(define (filter f xs)
(cond
((null? xs) '())
((f (car xs)) (cons (car xs) (filter f (cdr xs))))
(#t (filter f (cdr xs)))))
(define (any f l) (not (null? (filter f l))))
(define (constantly val)
(lambda - val))
(define (identity x) x)
(define (remove-duplicates l pred)
(let ((ret '()))
(let loop ((l l))
(unless (null? l)
(unless (any (lambda (x) (pred x (car l))) ret)
(push (car l) ret))
(loop (cdr l))))
(reverse ret)))
(define (remove-duplicates-from-end l pred)
(let ((ret '()))
(let loop ((l l))
(unless (null? l)
(loop (cdr l))
(unless (any (lambda (x) (pred x (car l))) ret)
(push (car l) ret))))
ret))
(define (every f l)
(if (null? l)
#t
(and (f (car l))
(every f (cdr l)))))
(define (position-if pred l)
(let loop ((l l)
(i 0))
(cond
((null? l) #f)
((pred (car l)) i)
(#t (loop (cdr l) (+ 1 i))))))
(define (position-if-from-end pred l)
(let loop ((l l)
(i 0))
(cond ((null? l) #f)
((pred (car l)) (or (loop (cdr l) (+ 1 i)) i))
(#t (loop (cdr l) (+ 1 i))))))
(define (for-each-on f xs)
(if (null? xs)
'()
(begin
(f xs)
(for-each-on f (cdr xs)))))
(define (count x xs pred)
(let loop ((xs xs)
(acc 0))
(if (null? xs) acc
(loop (cdr xs) (+ acc (if (pred x (car xs)) 1 0))))))
(define (intersection x y pred)
(filter (rbind member y pred) x))
; to make up for multiple-value-bind
(define-macro (pidgin-destructuring-bind spec var . body)
(let ((v (gensym)))
(letrec ((expand (lambda (spec)
(if (null? spec)
`((unless (null? ,v) (error "too many values specified for destructuring")))
(list* `(set! ,(car spec) (car ,v))
`(set! ,v (cdr ,v))
(expand (cdr spec)))))))
`(let ((,v ,var)
,@(map (lambda (s) `(,s #f)) spec))
,@(expand spec)
,@body))))
; simple stub generics implementation (single dispatch only)
; (defgeneric m (x y z) body*) will define a function 'm' that expects 'x' to
; be a let containing a bound lambda 'm'; y and z will be passed to that
; lambda. If 'm' is not bound, body will be evaluated instead. If body is
; nil, an error will be signaled
(define-macro (defgeneric name pspec . body)
`(define (,name ,@pspec)
(if (eq? ,name (,(car pspec) ',name))
,(if (null? body) `(error "No method ~a bound in class ~a" ',name (,(car pspec) 'class-name)) `(begin ,@body))
((,(car pspec) ',name) ,@pspec))))
(define *classes* (make-hash-table 8 eq?))
(define (type-specifier? x) (or (symbol? x) (eq? x #f)))
(define-macro (defclass name super slots . methods)
(when (*classes* name) (error "Class already defined: ~a" name))
(let* ((super (map (lambda (s) (let ((r (*classes* s))) (unless r (error "No superclass ~a" s)) r)) super))
(auxiliary-slots (apply append (map (lambda (c) (c 'all-slots)) super)))
(auxiliary-methods (apply append (map (lambda (c) (c 'all-methods)) super)))
(methods (map (lambda (m) `(,(car m) (lambda* ,(cadr m) ,@(cddr m)))) methods))
(slots (map (lambda (s) (if (pair? s) s `(,s (error ,(format #f "No initializer supplied for slot ~a" s))))) slots))
(accessor-methods '())
(all-slots (remove-duplicates-from-end `(,@auxiliary-slots ,@slots) (compose eq? car)))
(all-methods (remove-duplicates-from-end `(,@auxiliary-methods ,@accessor-methods ,@methods) (compose eq? car)))
(classes (cons name (remove-duplicates (apply append (map (lambda (x) (x 'classes)) super)) eq?))))
`(set! (*classes* ',name)
(inlet 'all-slots ',all-slots
'all-methods ',all-methods
'class-name ',name
'classes ',classes
'make (lambda* ,all-slots
(let ((class-name ',name)
,@all-methods)
(curlet)))))))
(define (make-instance what . p)
(apply ((*classes* what) 'make) p))
(define (type? var type) (member type ((*classes* (var 'class-name)) 'classes)))
(define *loop-errors* (make-hash-table 8 eq?))
(define-macro (add-error-formatter name parameter-list . body)
`(set! (*loop-errors* ',name)
(lambda*
(stream ,@(map (lambda (x) (if (pair? x) x `(,x (error "No argument supplied for parameter ~a" ',x))))
parameter-list))
,@body)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Condition reporters for parse errors.
(add-error-formatter expected-var-spec-but-end ()
(format stream
"Expected a variable specification, but reached the end of the loop body."))
(add-error-formatter expected-var-spec-but-found (found)
(format stream
"Expected a variable specification but found the following instead: ~s"
found))
(add-error-formatter expected-simple-var-but-end ()
(format stream
"Expected a simple variable but reached the end of the loop body."))
(add-error-formatter expected-simple-var-but-found (found)
(format stream
"Expected a simple variable but found the following instead: ~s"
found))
(add-error-formatter expected-type-spec-but-end ()
(format stream
"Expected a variable specification but reached the end of the loop body."))
(add-error-formatter expected-type-spec-but-found (found)
(format stream
"Expected a type specification but found the following instead: ~s"
found))
(add-error-formatter expected-compound-form-but-end ()
(format stream
"Expected a compound form but reached the end of the loop body."))
(add-error-formatter expected-compound-form-but-found (found)
(format stream
"Expected a compound form but found the following instead: ~s"
found))
(add-error-formatter expected-form-but-end ()
(format stream
"Expected a form but reached the end of the loop body."))
(add-error-formatter expected-symbol-but-end ()
(format stream
"Expected a symbol but reached the end of the loop body."))
(add-error-formatter expected-symbol-but-found (found)
(format stream
"Expected a symbol but found the following instead: ~s"
found))
(add-error-formatter expected-keyword-but-found (found)
(format stream
"Expected a loop keyword, but found the following instead: ~s"
found))
(add-error-formatter expected-for/as-subclause-but-end ()
(format stream
"Expected a loop keyword indicating a for/as subclause, but reached the end of the loop body."))
(add-error-formatter expected-symbol-but-found (found)
(format stream
"Expected a loop keyword indicating a for/as subclause, but found the following instead: ~s"
found))
(add-error-formatter expected-each/the-but-end ()
(format stream
"Expected the loop keyword each/the, but reached the end of the loop body."))
(add-error-formatter expected-each/the-but-found (found)
(format stream
"Expected the loop keyword each/the, but found the following instead: ~s"
found))
(add-error-formatter expected-in/of-but-end ()
(format stream
"Expected the loop keyword in/or, but reached the end of the loop body."))
(add-error-formatter expected-in/of-but-found (found)
(format stream
"Expected the loop keyword in/or, but found the following instead: ~s"
found))
(add-error-formatter conflicting-stepping-directions ()
(format stream "Conflicting stepping directions."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Condition reporters for syntax errors.
(add-error-formatter name-clause-not-first ()
(format stream
"A NAME loop clause was found, but it was not the first clause."))
(add-error-formatter multiple-name-clauses ()
(format stream
"Multiple NAME clauses where found."))
(add-error-formatter invalid-clause-order ()
(format stream
"Invalid clause order. Variable clauses must precede main clauses."))
(add-error-formatter multiple-variable-occurrences (bound-variable)
(format stream
"Multiple occurrences of the following variable were found: ~s"
bound-variable))
;;; The purpose of this generic function is to generate a list of all
;;; bound variables in a clause. The same variable occurs as many
;;; times in the list as the number of times it is bound in the
;;; clause.
(defgeneric bound-variables (clause))
;;; The purpose of this generic function is to generate a list of all
;;; the accumulation variables in a clause. Each element of the list
;;; is itself a list of three elements. The first element is the name
;;; of a variable used in an INTO clause, or NIL if the clause has no
;;; INTO. The second element determines the kind of accumulation, and
;;; can be one of the symbols LIST, COUNT/SUM, or MAX/MIN. The third
;;; element is a type specifier which can be T.
; NB. the scheme port uses #f instead of nil.
(defgeneric accumulation-variables (clause))
;;; The purpose of this generic function is to extract a list of
;;; declaration specifiers from the clause. Notice that it is a list
;;; of declaration specifiers, not a list of declarations. In other
;;; words, the symbol DECLARE is omitted.
(defgeneric declarations (clause)
'())
(defgeneric initial-bindings (clause)
'())
(defgeneric final-bindings (clause)
'())
(defgeneric bindings (clause)
(append (initial-bindings clause) (final-bindings clause)))
;;; This generic function returns a form for CLAUSE that should go in
;;; the LOOP prologue. The INITIALLY clause is an obvious candidate
;;; for such code. But the stepping clauses also have code that goes
;;; in the prologue, namely an initial termination test to determine
;;; whether any iterations at all should be executed. END-TAG is the
;;; tag to GO to when the initial termination test says that no
;;; iterations should be executed.
(defgeneric prologue-form (clause end-tag)
'())
;;; This generic function returns a form for CLAUSE that should go
;;; between the body code and the stepping forms in the body of the
;;; expanded code. Some of the FOR-AS clauses and also the REPEAT
;;; clause generate code here. END-TAG is the tag to GO to when
;;; iteration should terminate.
(defgeneric termination-form (clause end-tag)
'())
;;; This generic function returns a form for CLAUSE that should go in
;;; the main the body code, before the termination test and the
;;; stepping forms, in the body of the expanded code. The DO clause
;;; and the accumulation clauses are obvious candidates for such code.
;;;
;;; FIXME: Currently, END-TAG is used only in the WHILE clause as a
;;; termination test. Investigate whether the WHILE clause should use
;;; TERMINATION-TEST instead, so that we can eliminate this parameter.
(defgeneric body-form (clause end-tag)
'())
;;; This generic function returns a form for CLAUSE that should go
;;; after the main body code and the termination tests in the body of
;;; the expanded code. The FOR-AS clauses and also the REPEAT clause
;;; generate code here.
(defgeneric step-form (clause)
'())
;;; This generic function returns a form for CLAUSE that should go in
;;; the LOOP epilogue. Of the clause types defined by the Common Lisp
;;; standard, only the method specialized to the FINALLY clause
;;; returns a value other than NIL.
(defgeneric epilogue-form (clause)
'())
;;; Once the LOOP prologue, the LOOP body, and the LOOP epilogue have
;;; all been constructed, a bunch of successive WRAPPERS are applied
;;; so as to obtain the final expansion. Each clause type defines how
;;; it needs to be wrapped. Some clauses only require the
;;; establishment of variable bindings in the wrapper. Other clauses
;;; might need to be wrapped in some iterator form. The generic
;;; function WRAP-CLAUSE defines how each clause type is wrapped.
;;; The default method is applicable only if the clause type does not
;;; admit any subclauses. For this type of clause, the default
;;; implemented here is to wrap the clause in all the bindings, i.e.,
;;; both the initial and the final bindings of both exist.
(defgeneric wrap-clause (clause inner-form)
`(let* ,(bindings clause)
,inner-form))
;;; If a clause can have subclauses, then each subclause may need to
;;; be wrapped separately. The generic function WRAP-SUBCLAUSE
;;; determines how this is done.
;;; By default, the wrapper for each subclause contains only the final
;;; bindings, leaving the initial bindings to a single binding form of
;;; the entire clause.
(defgeneric wrap-subclause (subclause inner-form)
`(let ,(final-bindings subclause)
,inner-form))
;;; This variable is bound by the code generator for
;;; CONDITIONAL-CLAUSE before calling the code generators for the
;;; clauses in its THEN and ELSE branches.
(define *it-var* #f)
(define *accumulation-variable* #f)
(define *list-tail-accumulation-variable* #f)
(define *tail-variables* #f)
(define *loop-name* #f)
(define *loop-return-sym* #f)
(define *indent-level* 0)
(define *parse-trace?* #f)
;;; compare symbols and keywords indiscriminantly
(define (symbol-equal symbol1 symbol2)
(let ((f (lambda (x) (if (keyword? x) (keyword->symbol x) x))))
(let ((symbol1 (f symbol1))
(symbol2 (f symbol2)))
(and (symbol? symbol1)
(symbol? symbol2)
(eq? symbol1 symbol2)))))
;;; This function generates code for destructuring a value according
;;; to a tree of variables. D-VAR-SPEC is a tree of variable names
;;; (symbols). FORM is a form that, at runtime, computes the value to
;;; be assigned to the root of D-VAR-SPEC. This function returns a
;;; list of bindings to be used in a LET* form. These bindings
;;; destructure the root value until the leaves of the tree are
;;; reached, generating intermediate temporary variables as necessary.
;;; The destructuring code calls the function LIST-CAR and LIST-CDR so
;;; that an error is signaled whenever the corresponding place in the
;;; value tree is not a CONS cell.
(define (destructure-variables d-var-spec form)
(let ((bindings '()))
(letrec ((traverse (lambda (d-var-spec form)
(cond ((null? d-var-spec))
((symbol? d-var-spec)
(push `(,d-var-spec ,form) bindings))
((not (pair? d-var-spec))
(error 'expected-var-spec-but-found
:found d-var-spec))
(#t
(let ((temp (gensym)))
(push `(,temp ,form) bindings)
(traverse (car d-var-spec) `(,list-car ,temp))
(traverse (cdr d-var-spec) `(,list-cdr ,temp))))))))
(traverse d-var-spec form)
(reverse bindings))))
;;; Given a D-VAR-SPEC, compute a D-VAR-SPEC with the same structure
;;; as the one given as argument, except that the non-NIL leaves
;;; (i.e., the variables names) have been replaced by fresh symbols.
;;; Return two values: the new D-VAR-SPEC and a dictionary in the form
;;; of an association list that gives the correspondence between the
;;; original and the new variables.
(define (fresh-variables d-var-spec)
(let* ((dictionary '()))
(letrec ((traverse (lambda (d-var-spec)
(cond ((null? d-var-spec) '())
((symbol? d-var-spec)
(let ((temp (gensym)))
(push (cons d-var-spec temp) dictionary)
temp))
(#t
(cons (traverse (car d-var-spec))
(traverse (cdr d-var-spec))))))))
(list (traverse d-var-spec)
(reverse dictionary)))))
(define (generate-assignments d-var-spec form)
(pidgin-destructuring-bind (temp-d-var-spec dictionary)
(fresh-variables d-var-spec)
(if (null? dictionary)
()
`(let* ,(destructure-variables temp-d-var-spec form)
,@(map (lambda (t) `(set! ,(car t) ,(cdr t))) dictionary)))))
;;; Extract variables
(define (extract-variables d-var-spec d-type-spec)
(let ((result '()))
(letrec ((extract-aux (lambda (d-var-spec d-type-spec)
(cond ((null? d-var-spec))
((symbol? d-var-spec)
(push (list d-var-spec (or d-type-spec 't)) result))
((type-specifier? d-type-spec)
(if (not (pair? d-var-spec))
(error 'expected-var-spec-but-found
:found d-var-spec)
(begin (extract-aux (car d-var-spec) d-type-spec)
(extract-aux (cdr d-var-spec) d-type-spec))))
((not (pair? d-var-spec))
(error 'expected-var-spec-but-found
:found d-var-spec))
((not (pair? d-type-spec))
(error 'expected-type-spec-but-found
:found d-type-spec))
(#t
(extract-aux (car d-var-spec) (if d-type-spec (car d-type-spec) #f))
(extract-aux (cdr d-var-spec) (if d-type-spec (cdr d-type-spec) #f)))))))
(extract-aux d-var-spec d-type-spec)
result)))
;;; A parser is a function that takes a list of tokens to parse, and
;;; that returns three values:
;;;
;;; * A generalized Boolean indicating whether the parse succeeded.
;;;
;;; * The result of the parse. If the parse does not succeed, then
;;; this value is unspecified.
;;;
;;; * A list of the tokens that remain after the parse. If the
;;; parse does not succeed, then this list contains the original
;;; list of tokens passed as an argument.
;;; Functions that take one or more parsers as arguments can take
;;; either a function or the name of a function.
(define (parse-trace-output format-control . arguments)
(when *parse-trace?*
(format #t (make-string (* 2 *indent-level*) #\space))
(apply format #t format-control arguments)))
(define (trace-parser name parser tokens)
(let-temporarily ((*indent-level* (+ 1 *indent-level*)))
(parse-trace-output "trying ~s on ~s~%" name tokens)
(pidgin-destructuring-bind (successp result rest)
(parser tokens)
(parse-trace-output "~asuccess~%" (if successp "" "no "))
(list successp result rest))))
(define-macro (define-parser name . body)
`(define (,name tokens) (trace-parser ',name (begin ,@body) tokens)))
;;; Take a function designator (called the TRANSFORMER) and a
;;; predicate P and return a parser Q that invokes the predicate on
;;; the first token. If P returns true then Q succeeds and returns
;;; the result of invoking TRANSFORMER on the token together with the
;;; remaining tokens (all tokens except the first one). If P returns
;;; false, then Q fails. If there are no tokens, then Q also fails.
(define (singleton transformer predicate)
(lambda (tokens)
(if (and (not (null? tokens))
(predicate (car tokens)))
(list #t (transformer (car tokens)) (cdr tokens))
(list #f #f tokens))))
;;; Take a list of parsers P1, P2, ..., Pn and return a parser Q that
;;; invokes Pi in order until one of them succeeds. If some Pi
;;; succeeds. then Q also succeeds with the same result as Pi. If
;;; every Pi fails, then Q also fails.
(define (alternative . parsers)
(lambda (tokens)
(let loop ((parsers parsers))
(if (null? parsers)
(list #f #f tokens)
(pidgin-destructuring-bind (success result rest)
((car parsers) tokens)
(if success
(list #t result rest)
(loop (cdr parsers))))))))
;;; Take a function designator (called the COMBINER) and a list of
;;; parsers P1, P2, ..., Pn and return a parser Q that invokes every
;;; Pi in order. If any Pi fails, then Q fails as well. If every Pi
;;; succeeds, then Q also succeeds and returns the result of calling
;;; APPLY on COMBINER and the list of results of the invocation of
;;; each Pi.
(define (consecutive combiner . parsers)
(lambda (tokens)
(let loop ((remaining-tokens tokens)
(remaining-parsers parsers)
(results '()))
(if (null? remaining-parsers)
(list #t (apply combiner (reverse results)) remaining-tokens)
(pidgin-destructuring-bind (success result rest)
((car remaining-parsers) remaining-tokens)
(if success
(loop rest (cdr remaining-parsers) (cons result results))
(list #f #f tokens)))))))
;;; Take a function designator (called the COMBINER) and a parser P
;;; and return a parser Q that invokes P repeatedly until it fails,
;;; each time with the tokens remaining from the previous invocation.
;;; The result of the invocation of Q is the result of calling APPLY
;;; on COMBINER and the list of the results of each invocation of P.
;;; Q always succeeds. If the first invocation of P fails, then Q
;;; succeeds returning the result of calling APPLY on COMBINER and the
;;; empty list of results, and the original list of tokens as usual.
(define (repeat* combiner parser)
(lambda (tokens)
(let loop ((remaining-tokens tokens)
(results '()))
(pidgin-destructuring-bind (success result rest)
(parser remaining-tokens)
(if success
(loop rest (cons result results))
(list #t (apply combiner (reverse results)) remaining-tokens))))))
;;; Take a function designator (called the COMBINER) and a parser P
;;; and return a parser Q that invokes P repeatedly until it fails,
;;; each time with the tokens remaining from the previous invocation.
;;; The result of the invocation of Q is the result of calling APPLY
;;; on COMBINER and the list of the results of each invocation of P.
;;; Q succeeds if and only if at least one invocation of P succeeds.
(define (repeat+ combiner parser)
(lambda (tokens)
(pidgin-destructuring-bind (success result rest)
(parser tokens)
(if (not success)
(list #f #f tokens)
(let loop ((remaining-tokens rest)
(results (list result)))
(pidgin-destructuring-bind (success result rest)
(parser remaining-tokens)
(if success
(loop rest (cons result results))
(list #t (apply combiner (reverse results)) remaining-tokens))))))))
;;; Take a default value and a parser P and return a parser Q that
;;; always succeeds. Q invokes P once. If P succeeds, then Q
;;; succeeds with the same result as P and with the same remaining
;;; tokens. If P fails, then Q succeeds, returning the default value
;;; and the original list of tokens.
(define (optional default parser)
(lambda (tokens)
(pidgin-destructuring-bind (success result rest)
(parser tokens)
(if success
(list #t result rest)
(list #t default tokens)))))
;;; LocalWords: parsers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Given a symbol S (no matter what package), return a singleton
;;; parser Q that recognizes symbols with the same name as S. If Q
;;; succeeds, it returns S.
(define (keyword-parser symbol)
(singleton (constantly symbol)
(lambda (token) (symbol-equal symbol token))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Parser for anything, i.e. a parser that succeeds whenever the list
;;; of tokens is not empty. It returns the first token as a result of
;;; the parse, and the list of tokens with the first one removed as
;;; the list of remaining tokens.
(define-parser anything-parser
(singleton identity (constantly #t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; A parser that recognizes one of the LOOP keywords EACH and THE.
;;; It is used to parse FOR-AS-HASH and FOR-AS-PACKAGE subclauses.
(define-parser each-the-parser
(alternative (keyword-parser 'each)
(keyword-parser 'the)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; A parser that recognizes one of the LOOP keywords IN and OF.
;;; It is used to parse FOR-AS-HASH and FOR-AS-PACKAGE subclauses.
(define-parser in-of-parser
(alternative (keyword-parser 'in)
(keyword-parser 'of)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; A parser that recognizes one of the LOOP keyword BEING.
;;; It is used to parse FOR-AS-HASH and FOR-AS-PACKAGE subclauses.
(define-parser being-parser
(keyword-parser 'being))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Parser for COMPOUND-FORM+, i.e. a non-empty sequence of compound
;;; forms.
(define-parser compound+
(repeat+ (lambda forms
(cons 'begin forms))
(singleton identity pair?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; This parser succeeds whenever the list of tokens is either empty
;;; or starts with a form that is not a loop keyword that can start a
;;; clause. When it succeeds, it returns NIL as the result and the
;;; original list of tokens.
(define *clause-keywords*
'(initially finally
with
do return
collect collecting
append appending
nconc nconcing
count counting
sum summing
maximize maximizing
minimize minimizing
if when unless
while until repeat always never thereis
for as))
(define (non-clause-keyword tokens)
(if (or (null tokens)
(member (car tokens) *clause-keywords*
symbol-equal))
(list #t #f tokens)
(list #f #f tokens)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Manage a list of clause parsers.
(define *clause-parsers* '())
(define (add-clause-parser parser)
(push parser *clause-parsers*))
;;; A parser that tries every parser in *CLAUSE-PARSERS* until one
;;; succeeds.
(define (parse-clause tokens)
(let loop ((parsers *clause-parsers*))
(if (null? parsers)
(list #f #f tokens)
(pidgin-destructuring-bind (success result rest)
((car parsers) tokens)
(if success
(list #t result rest)
(loop (cdr parsers)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Class LOOP-BODY.
;;;
;;; An instance of this class is the result of parsing the clauses.
;(defclass loop-body ()
; ((%clauses :initform '() :initarg :clauses :accessor clauses)
; (%accumulation-variable :initform nil :accessor accumulation-variable)
; (%accumulation-list-tail :initform nil :accessor accumulation-list-tail)
; (%accumulation-type :initform nil :accessor accumulation-type)))
;;; Create a list of clauses from the body of the LOOP form.
(define (parse-loop-body body)
(let loop ((remaining-body body)
(clauses '()))
(if (null? remaining-body)
(reverse clauses)
(pidgin-destructuring-bind (success clause rest)
(parse-clause remaining-body)
(if success
(loop rest (cons clause clauses))
;; FIXME: this is not the right error to signal.
(error 'expected-keyword-but-found
:found (car rest)))))))
;;;; The terminology used here is that of the BNF grammar in the
;;;; dictionary description of the loop macro in the HyperSpec. It is
;;;; not the same as the terminology used in the section 6.1.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Common classes.
;;; The base class of all clauses.
(defclass clause () ())
;;; Mixin for clauses that accept `AND'.
(defclass subclauses-mixin ()
(subclauses)
;;; Method on WRAP-CLAUSE specialized to clause types that admit
;;; subclauses. This method overrides the default method above. It
;;; wraps each subclause individually, and then wraps the result in
;;; the initial bindings for the entire clause.
(wrap-clause (clause inner-form)
(let ((result inner-form))
(map (lambda (subclause)
(set! result (wrap-subclause subclause result)))
(reverse (clause 'subclauses)))
`(let ,(initial-bindings clause)
,result))))
;;; Mixin for clauses and subclauses that take
;;; a VAR-SPEC and a TYPE-SPEC.
(defclass var-and-type-spec-mixin ()
(var-spec type-spec))
;;; Mixin for clauses that take a list of compound forms.
(defclass compound-forms-mixin ()
(forms))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Mixin for clauses that make the loop return a value.
(defclass loop-return-clause-mixin () ())
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Mixin for clauses that has an implicit IT argument.
(defclass it-mixin () ())
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Mixin for clauses that has an explicit form argument.
(defclass form-mixin ()
(form))
(define (tail-variable head-variable)
(let ((result (*tail-variables* head-variable)))
(unless result
(set! result (gensym))
(set! (*tail-variables* head-variable) result))
result))
(define (accumulation-bindings clauses)
(let* ((descriptors
(apply append
(map accumulation-variables clauses)))
(equal-fun (lambda (d1 d2)
(and (eq? (car d1) (car d2))
(eq? (cadr d1) (cadr d2)))))
(unique (remove-duplicates descriptors equal-fun)))
(let loop ((unique unique))
(if (null? unique)
'()
(let ((name (caar unique))
(category (cadar unique))
(type (caddar unique)))
(let ((initial-value (cond ((eq? category 'count/sum) (car (arithmetic-value-and-type type))) ;(coerce 0 type)
((eq? category 'always/never) #t)
((eq? category 'thereis) #f)
((eq? category 'max) -inf.0)
((eq? category 'min) +inf.0)
((eq? category 'string) "")
((eq? category 'array) #())
(#t ''()))))
(append
(if (not name)
`((,*accumulation-variable* ,initial-value))
`((,name ,initial-value)))
(if (eq? category 'list)
(if (not name)
`((,*list-tail-accumulation-variable* '()))
`((,(tail-variable name) '())))
'())
(loop (cdr unique)))))))))
(define *clause* #f)
(define (prologue-body-epilogue clauses end-tag)
(let ((start-tag (gensym)))
`(letrec ((,end-tag (lambda ()
,@(map epilogue-form clauses)
(,*loop-return-sym*
,*accumulation-variable*))))
(letrec ((,start-tag (lambda ()
,@(map (lambda (clause)
(body-form clause end-tag))
clauses)
,@(map (lambda (clause)
(termination-form clause end-tag))
clauses)
,@(map step-form clauses)
(,start-tag))))
,@(map (lambda (clause)
(prologue-form clause end-tag)) clauses)
(,start-tag)))))
;;; Process all clauses by first computing the prologue, the body, and
;;; the epilogue, and then applying the clause-specific wrapper for
;;; each clause to the result.
(define (do-clauses all-clauses end-tag)
(let ((result (prologue-body-epilogue all-clauses end-tag)))
(map (lambda (clause)
(set! result (wrap-clause clause result)))
(reverse all-clauses))
result))
(define (expand-clauses all-clauses end-tag)
(let ((acc (accumulation-bindings all-clauses)))
`(let (,@(if (member *accumulation-variable* (map car acc))
'()
`((,*accumulation-variable* '()))) ;*accumulation-variable* was nil originally; is '() right?
,@acc)
,(do-clauses all-clauses end-tag))))
; consider making a dedicated 'loop error' tag and stuffing the actual data
; into the tag so that we don't have to awkwardly rethrow other errors?
(define-macro (augment-error-with-nice-message . body)
`(catch #t (lambda () ,@body)
(lambda (err rest)
(if (,*loop-errors* err)
(error err (apply (,*loop-errors* err) #f rest))
(apply error err rest)))))
(define (expand-body loop-body)
(augment-error-with-nice-message
(if (every pair? loop-body)
(let ((tag (gensym)))
`(call-with-exit
(letrec ((,tag (lambda (return)
,@loop-body
(,tag return))))
,tag)))
(let ((clauses (parse-loop-body loop-body))
(end-tag (gensym)))
(analyze-clauses clauses)
(let-temporarily ((*loop-name* (if (type? (car clauses) 'name-clause)
((car clauses) 'name)
#f))
(*loop-return-sym* (gensym))
(*accumulation-variable* (gensym))
(*list-tail-accumulation-variable* (gensym))
(*tail-variables* (make-hash-table 8 eq?)))
; todo incorporate *loop-name* to allow named return
`(,augment-error-with-nice-message
(call-with-exit
(lambda (return)
(call-with-exit
(lambda (,*loop-return-sym*)
(let ((loop-finish (macro () `(,',end-tag))))
,(expand-clauses clauses end-tag))))))))))))
;;; In the dictionary entry for LOOP, the HyperSpec says:
;;;
;;; main-clause ::= unconditional |
;;; accumulation |
;;; conditional |
;;; termination-test |
;;; initial-final
;;;
;;; Here, we exclude initial-final. The reason for that is that
;;; initial-final is also one of the possibilities for a
;;; variable-clause, and the reason for this "multiple inheritance" is
;;; so that the LOOP macro syntax can be defined to have the syntax:
;;;
;;; loop [name-clause] {variable-clause}* {main-clause}*
;;;
;;; which then allows for INITIALLY and FINALLY clauses to occur
;;; anywhere after the name-clause.
;;;
;;; What we do here is to treat INITIALLY and FINALLY specially, so
;;; that they are neither main clauses nor variable clauses.
;;; Therefore, here, we have:
;;;
;;; main-clause ::= unconditional |
;;; accumulation |
;;; conditional |
;;; termination-test
;;;
;;; Furthermore, the HyperSpec defines selectable-clause like this:
;;;
;;; selectable-clause ::= unconditional | accumulation | conditional
;;;
;;; so we can say:
;;;
;;; main-clause ::= selectable-clause | termination-test
(defclass main-clause (clause) ())
;;; In the dictionary entry for LOOP, the HyperSpec says:
;;;
;;; variable-clause ::= with-clause | initial-final | for-as-clause
;;;
;;; Here, we exclude initial-final. The reason for that is that
;;; initial-final is also one of the possibilities for a
;;; main-clause, and the reason for this "multiple inheritance" is
;;; so that the LOOP macro syntax can be defined to have the syntax:
;;;
;;; loop [name-clause] {variable-clause}* {main-clause}*
;;;
;;; which then allows for INITIALLY and FINALLY clauses to occur
;;; anywhere after the name-clause.
;;;
;;; What we do here is to treat INITIALLY and FINALLY specially, so
;;; that they are neither main clauses nor variable clauses.
;;; Therefore, here, we have:
;;;
;;; variable-clause ::= with-clause | for-as-clause
(defclass variable-clause (clause) ()
;;; No variable clause defines any accumulation variables
(accumulation-variables (clause)
'()))
;;; Recall that in the dictionary entry for LOOP, the HyperSpec says:
;;;
;;; main-clause ::= unconditional |
;;; accumulation |
;;; conditional |
;;; termination-test |
;;; initial-final
;;;
;;; Though here, we exclude initial-final so that we have:
;;;
;;; main-clause ::= unconditional |
;;; accumulation |
;;; conditional |
;;; termination-test
;;;
;;; Furthermore, the HyperSpec defines selectable-clause like this:
;;;
;;; selectable-clause ::= unconditional | accumulation | conditional
;;;
;;; so we can say:
;;;
;;; main-clause ::= selectable-clause | termination-test
(defclass selectable-clause (main-clause) ()
(bound-variables (clause)
'()))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Parsers.
(define-parser selectable-clause-parser
(alternative do-clause-parser
return-clause-parser
collect-clause-parser
append-clause-parser
nconc-clause-parser
count-clause-parser
sum-clause-parser
maximize-clause-parser
minimize-clause-parser
conditional-clause-parser))