Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / module / language / tree-il / analyze.scm
1 ;;; TREE-IL -> GLIL compiler
2
3 ;; Copyright (C) 2001, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 ;;; Code:
20
21 (define-module (language tree-il analyze)
22 #:use-module (srfi srfi-1)
23 #:use-module (srfi srfi-9)
24 #:use-module (srfi srfi-11)
25 #:use-module (srfi srfi-26)
26 #:use-module (ice-9 vlist)
27 #:use-module (ice-9 match)
28 #:use-module (system base syntax)
29 #:use-module (system base message)
30 #:use-module (system vm program)
31 #:use-module (language tree-il)
32 #:use-module (system base pmatch)
33 #:export (analyze-lexicals
34 analyze-tree
35 unused-variable-analysis
36 unused-toplevel-analysis
37 unbound-variable-analysis
38 arity-analysis
39 format-analysis))
40
41 ;; Allocation is the process of assigning storage locations for lexical
42 ;; variables. A lexical variable has a distinct "address", or storage
43 ;; location, for each procedure in which it is referenced.
44 ;;
45 ;; A variable is "local", i.e., allocated on the stack, if it is
46 ;; referenced from within the procedure that defined it. Otherwise it is
47 ;; a "closure" variable. For example:
48 ;;
49 ;; (lambda (a) a) ; a will be local
50 ;; `a' is local to the procedure.
51 ;;
52 ;; (lambda (a) (lambda () a))
53 ;; `a' is local to the outer procedure, but a closure variable with
54 ;; respect to the inner procedure.
55 ;;
56 ;; If a variable is ever assigned, it needs to be heap-allocated
57 ;; ("boxed"). This is so that closures and continuations capture the
58 ;; variable's identity, not just one of the values it may have over the
59 ;; course of program execution. If the variable is never assigned, there
60 ;; is no distinction between value and identity, so closing over its
61 ;; identity (whether through closures or continuations) can make a copy
62 ;; of its value instead.
63 ;;
64 ;; Local variables are stored on the stack within a procedure's call
65 ;; frame. Their index into the stack is determined from their linear
66 ;; postion within a procedure's binding path:
67 ;; (let (0 1)
68 ;; (let (2 3) ...)
69 ;; (let (2) ...))
70 ;; (let (2 3 4) ...))
71 ;; etc.
72 ;;
73 ;; This algorithm has the problem that variables are only allocated
74 ;; indices at the end of the binding path. If variables bound early in
75 ;; the path are not used in later portions of the path, their indices
76 ;; will not be recycled. This problem is particularly egregious in the
77 ;; expansion of `or':
78 ;;
79 ;; (or x y z)
80 ;; -> (let ((a x)) (if a a (let ((b y)) (if b b z))))
81 ;;
82 ;; As you can see, the `a' binding is only used in the ephemeral
83 ;; `consequent' clause of the first `if', but its index would be
84 ;; reserved for the whole of the `or' expansion. So we have a hack for
85 ;; this specific case. A proper solution would be some sort of liveness
86 ;; analysis, and not our linear allocation algorithm.
87 ;;
88 ;; Closure variables are captured when a closure is created, and stored in a
89 ;; vector inline to the closure object itself. Each closure variable has a
90 ;; unique index into that vector.
91 ;;
92 ;; There is one more complication. Procedures bound by <fix> may, in
93 ;; some cases, be rendered inline to their parent procedure. That is to
94 ;; say,
95 ;;
96 ;; (letrec ((lp (lambda () (lp)))) (lp))
97 ;; => (fix ((lp (lambda () (lp)))) (lp))
98 ;; => goto FIX-BODY; LP: goto LP; FIX-BODY: goto LP;
99 ;; ^ jump over the loop ^ the fixpoint lp ^ starting off the loop
100 ;;
101 ;; The upshot is that we don't have to allocate any space for the `lp'
102 ;; closure at all, as it can be rendered inline as a loop. So there is
103 ;; another kind of allocation, "label allocation", in which the
104 ;; procedure is simply a label, placed at the start of the lambda body.
105 ;; The label is the gensym under which the lambda expression is bound.
106 ;;
107 ;; The analyzer checks to see that the label is called with the correct
108 ;; number of arguments. Calls to labels compile to rename + goto.
109 ;; Lambda, the ultimate goto!
110 ;;
111 ;;
112 ;; The return value of `analyze-lexicals' is a hash table, the
113 ;; "allocation".
114 ;;
115 ;; The allocation maps gensyms -- recall that each lexically bound
116 ;; variable has a unique gensym -- to storage locations ("addresses").
117 ;; Since one gensym may have many storage locations, if it is referenced
118 ;; in many procedures, it is a two-level map.
119 ;;
120 ;; The allocation also stored information on how many local variables
121 ;; need to be allocated for each procedure, lexicals that have been
122 ;; translated into labels, and information on what free variables to
123 ;; capture from its lexical parent procedure.
124 ;;
125 ;; In addition, we have a conflation: while we're traversing the code,
126 ;; recording information to pass to the compiler, we take the
127 ;; opportunity to generate labels for each lambda-case clause, so that
128 ;; generated code can skip argument checks at runtime if they match at
129 ;; compile-time.
130 ;;
131 ;; Also, while we're a-traversing and an-allocating, we check prompt
132 ;; handlers to see if the "continuation" argument is used. If not, we
133 ;; mark the prompt as being "escape-only". This allows us to implement
134 ;; `catch' and `throw' using `prompt' and `control', but without causing
135 ;; a continuation to be reified. Heh heh.
136 ;;
137 ;; That is:
138 ;;
139 ;; sym -> {lambda -> address}
140 ;; lambda -> (labels . free-locs)
141 ;; lambda-case -> (gensym . nlocs)
142 ;; prompt -> escape-only?
143 ;;
144 ;; address ::= (local? boxed? . index)
145 ;; labels ::= ((sym . lambda) ...)
146 ;; free-locs ::= ((sym0 . address0) (sym1 . address1) ...)
147 ;; free variable addresses are relative to parent proc.
148
149 (define (make-hashq k v)
150 (let ((res (make-hash-table)))
151 (hashq-set! res k v)
152 res))
153
154 (define (analyze-lexicals x)
155 ;; bound-vars: lambda -> (sym ...)
156 ;; all identifiers bound within a lambda
157 (define bound-vars (make-hash-table))
158 ;; free-vars: lambda -> (sym ...)
159 ;; all identifiers referenced in a lambda, but not bound
160 ;; NB, this includes identifiers referenced by contained lambdas
161 (define free-vars (make-hash-table))
162 ;; assigned: sym -> #t
163 ;; variables that are assigned
164 (define assigned (make-hash-table))
165 ;; refcounts: sym -> count
166 ;; allows us to detect the or-expansion in O(1) time
167 (define refcounts (make-hash-table))
168 ;; labels: sym -> lambda
169 ;; for determining if fixed-point procedures can be rendered as
170 ;; labels.
171 (define labels (make-hash-table))
172
173 ;; returns variables referenced in expr
174 (define (analyze! x proc labels-in-proc tail? tail-call-args)
175 (define (step y) (analyze! y proc '() #f #f))
176 (define (step-tail y) (analyze! y proc labels-in-proc tail? #f))
177 (define (step-tail-call y args) (analyze! y proc labels-in-proc #f
178 (and tail? args)))
179 (define (recur/labels x new-proc labels)
180 (analyze! x new-proc (append labels labels-in-proc) #t #f))
181 (define (recur x new-proc) (analyze! x new-proc '() tail? #f))
182 (record-case x
183 ((<call> proc args)
184 (apply lset-union eq? (step-tail-call proc args)
185 (map step args)))
186
187 ((<primcall> args)
188 (apply lset-union eq? (map step args)))
189
190 ((<conditional> test consequent alternate)
191 (lset-union eq? (step test) (step-tail consequent) (step-tail alternate)))
192
193 ((<lexical-ref> gensym)
194 (hashq-set! refcounts gensym (1+ (hashq-ref refcounts gensym 0)))
195 (if (not (and tail-call-args
196 (memq gensym labels-in-proc)
197 (let ((p (hashq-ref labels gensym)))
198 (and p
199 (let lp ((c (lambda-body p)))
200 (and c (lambda-case? c)
201 (or
202 ;; for now prohibit optional &
203 ;; keyword arguments; can relax this
204 ;; restriction later
205 (and (= (length (lambda-case-req c))
206 (length tail-call-args))
207 (not (lambda-case-opt c))
208 (not (lambda-case-kw c))
209 (not (lambda-case-rest c)))
210 (lp (lambda-case-alternate c)))))))))
211 (hashq-set! labels gensym #f))
212 (list gensym))
213
214 ((<lexical-set> gensym exp)
215 (hashq-set! assigned gensym #t)
216 (hashq-set! labels gensym #f)
217 (lset-adjoin eq? (step exp) gensym))
218
219 ((<module-set> exp)
220 (step exp))
221
222 ((<toplevel-set> exp)
223 (step exp))
224
225 ((<toplevel-define> exp)
226 (step exp))
227
228 ((<seq> head tail)
229 (lset-union eq? (step head) (step-tail tail)))
230
231 ((<lambda> body)
232 ;; order is important here
233 (hashq-set! bound-vars x '())
234 (let ((free (recur body x)))
235 (hashq-set! bound-vars x (reverse! (hashq-ref bound-vars x)))
236 (hashq-set! free-vars x free)
237 free))
238
239 ((<lambda-case> opt kw inits gensyms body alternate)
240 (hashq-set! bound-vars proc
241 (append (reverse gensyms) (hashq-ref bound-vars proc)))
242 (lset-union
243 eq?
244 (lset-difference eq?
245 (lset-union eq?
246 (apply lset-union eq? (map step inits))
247 (step-tail body))
248 gensyms)
249 (if alternate (step-tail alternate) '())))
250
251 ((<let> gensyms vals body)
252 (hashq-set! bound-vars proc
253 (append (reverse gensyms) (hashq-ref bound-vars proc)))
254 (lset-difference eq?
255 (apply lset-union eq? (step-tail body) (map step vals))
256 gensyms))
257
258 ((<letrec> gensyms vals body)
259 (hashq-set! bound-vars proc
260 (append (reverse gensyms) (hashq-ref bound-vars proc)))
261 (for-each (lambda (sym) (hashq-set! assigned sym #t)) gensyms)
262 (lset-difference eq?
263 (apply lset-union eq? (step-tail body) (map step vals))
264 gensyms))
265
266 ((<fix> gensyms vals body)
267 ;; Try to allocate these procedures as labels.
268 (for-each (lambda (sym val) (hashq-set! labels sym val))
269 gensyms vals)
270 (hashq-set! bound-vars proc
271 (append (reverse gensyms) (hashq-ref bound-vars proc)))
272 ;; Step into subexpressions.
273 (let* ((var-refs
274 (map
275 ;; Since we're trying to label-allocate the lambda,
276 ;; pretend it's not a closure, and just recurse into its
277 ;; body directly. (Otherwise, recursing on a closure
278 ;; that references one of the fix's bound vars would
279 ;; prevent label allocation.)
280 (lambda (x)
281 (record-case x
282 ((<lambda> body)
283 ;; just like the closure case, except here we use
284 ;; recur/labels instead of recur
285 (hashq-set! bound-vars x '())
286 (let ((free (recur/labels body x gensyms)))
287 (hashq-set! bound-vars x (reverse! (hashq-ref bound-vars x)))
288 (hashq-set! free-vars x free)
289 free))))
290 vals))
291 (vars-with-refs (map cons gensyms var-refs))
292 (body-refs (recur/labels body proc gensyms)))
293 (define (delabel-dependents! sym)
294 (let ((refs (assq-ref vars-with-refs sym)))
295 (if refs
296 (for-each (lambda (sym)
297 (if (hashq-ref labels sym)
298 (begin
299 (hashq-set! labels sym #f)
300 (delabel-dependents! sym))))
301 refs))))
302 ;; Stepping into the lambdas and the body might have made some
303 ;; procedures not label-allocatable -- which might have
304 ;; knock-on effects. For example:
305 ;; (fix ((a (lambda () (b)))
306 ;; (b (lambda () a)))
307 ;; (a))
308 ;; As far as `a' is concerned, both `a' and `b' are
309 ;; label-allocatable. But `b' references `a' not in a proc-tail
310 ;; position, which makes `a' not label-allocatable. The
311 ;; knock-on effect is that, when back-propagating this
312 ;; information to `a', `b' will also become not
313 ;; label-allocatable, as it is referenced within `a', which is
314 ;; allocated as a closure. This is a transitive relationship.
315 (for-each (lambda (sym)
316 (if (not (hashq-ref labels sym))
317 (delabel-dependents! sym)))
318 gensyms)
319 ;; Now lift bound variables with label-allocated lambdas to the
320 ;; parent procedure.
321 (for-each
322 (lambda (sym val)
323 (if (hashq-ref labels sym)
324 ;; Remove traces of the label-bound lambda. The free
325 ;; vars will propagate up via the return val.
326 (begin
327 (hashq-set! bound-vars proc
328 (append (hashq-ref bound-vars val)
329 (hashq-ref bound-vars proc)))
330 (hashq-remove! bound-vars val)
331 (hashq-remove! free-vars val))))
332 gensyms vals)
333 (lset-difference eq?
334 (apply lset-union eq? body-refs var-refs)
335 gensyms)))
336
337 ((<let-values> exp body)
338 (lset-union eq? (step exp) (step body)))
339
340 ((<dynwind> winder pre body post unwinder)
341 (lset-union eq? (step winder) (step pre)
342 (step body)
343 (step post) (step unwinder)))
344
345 ((<dynlet> fluids vals body)
346 (apply lset-union eq? (step body) (map step (append fluids vals))))
347
348 ((<dynref> fluid)
349 (step fluid))
350
351 ((<dynset> fluid exp)
352 (lset-union eq? (step fluid) (step exp)))
353
354 ((<prompt> tag body handler)
355 (lset-union eq? (step tag) (step body) (step-tail handler)))
356
357 ((<abort> tag args tail)
358 (apply lset-union eq? (step tag) (step tail) (map step args)))
359
360 (else '())))
361
362 ;; allocation: sym -> {lambda -> address}
363 ;; lambda -> (labels . free-locs)
364 ;; lambda-case -> (gensym . nlocs)
365 (define allocation (make-hash-table))
366
367 (define (allocate! x proc n)
368 (define (recur y) (allocate! y proc n))
369 (record-case x
370 ((<call> proc args)
371 (apply max (recur proc) (map recur args)))
372
373 ((<primcall> args)
374 (apply max n (map recur args)))
375
376 ((<conditional> test consequent alternate)
377 (max (recur test) (recur consequent) (recur alternate)))
378
379 ((<lexical-set> exp)
380 (recur exp))
381
382 ((<module-set> exp)
383 (recur exp))
384
385 ((<toplevel-set> exp)
386 (recur exp))
387
388 ((<toplevel-define> exp)
389 (recur exp))
390
391 ((<seq> head tail)
392 (max (recur head)
393 (recur tail)))
394
395 ((<lambda> body)
396 ;; allocate closure vars in order
397 (let lp ((c (hashq-ref free-vars x)) (n 0))
398 (if (pair? c)
399 (begin
400 (hashq-set! (hashq-ref allocation (car c))
401 x
402 `(#f ,(hashq-ref assigned (car c)) . ,n))
403 (lp (cdr c) (1+ n)))))
404
405 (let ((nlocs (allocate! body x 0))
406 (free-addresses
407 (map (lambda (v)
408 (hashq-ref (hashq-ref allocation v) proc))
409 (hashq-ref free-vars x)))
410 (labels (filter cdr
411 (map (lambda (sym)
412 (cons sym (hashq-ref labels sym)))
413 (hashq-ref bound-vars x)))))
414 ;; set procedure allocations
415 (hashq-set! allocation x (cons labels free-addresses)))
416 n)
417
418 ((<lambda-case> opt kw inits gensyms body alternate)
419 (max
420 (let lp ((gensyms gensyms) (n n))
421 (if (null? gensyms)
422 (let ((nlocs (apply
423 max
424 (allocate! body proc n)
425 ;; inits not logically at the end, but they
426 ;; are the list...
427 (map (lambda (x) (allocate! x proc n)) inits))))
428 ;; label and nlocs for the case
429 (hashq-set! allocation x (cons (gensym ":LCASE") nlocs))
430 nlocs)
431 (begin
432 (hashq-set! allocation (car gensyms)
433 (make-hashq
434 proc `(#t ,(hashq-ref assigned (car gensyms)) . ,n)))
435 (lp (cdr gensyms) (1+ n)))))
436 (if alternate (allocate! alternate proc n) n)))
437
438 ((<let> gensyms vals body)
439 (let ((nmax (apply max (map recur vals))))
440 (cond
441 ;; the `or' hack
442 ((and (conditional? body)
443 (= (length gensyms) 1)
444 (let ((v (car gensyms)))
445 (and (not (hashq-ref assigned v))
446 (= (hashq-ref refcounts v 0) 2)
447 (lexical-ref? (conditional-test body))
448 (eq? (lexical-ref-gensym (conditional-test body)) v)
449 (lexical-ref? (conditional-consequent body))
450 (eq? (lexical-ref-gensym (conditional-consequent body)) v))))
451 (hashq-set! allocation (car gensyms)
452 (make-hashq proc `(#t #f . ,n)))
453 ;; the 1+ for this var
454 (max nmax (1+ n) (allocate! (conditional-alternate body) proc n)))
455 (else
456 (let lp ((gensyms gensyms) (n n))
457 (if (null? gensyms)
458 (max nmax (allocate! body proc n))
459 (let ((v (car gensyms)))
460 (hashq-set!
461 allocation v
462 (make-hashq proc
463 `(#t ,(hashq-ref assigned v) . ,n)))
464 (lp (cdr gensyms) (1+ n)))))))))
465
466 ((<letrec> gensyms vals body)
467 (let lp ((gensyms gensyms) (n n))
468 (if (null? gensyms)
469 (let ((nmax (apply max
470 (map (lambda (x)
471 (allocate! x proc n))
472 vals))))
473 (max nmax (allocate! body proc n)))
474 (let ((v (car gensyms)))
475 (hashq-set!
476 allocation v
477 (make-hashq proc
478 `(#t ,(hashq-ref assigned v) . ,n)))
479 (lp (cdr gensyms) (1+ n))))))
480
481 ((<fix> gensyms vals body)
482 (let lp ((in gensyms) (n n))
483 (if (null? in)
484 (let lp ((gensyms gensyms) (vals vals) (nmax n))
485 (cond
486 ((null? gensyms)
487 (max nmax (allocate! body proc n)))
488 ((hashq-ref labels (car gensyms))
489 ;; allocate lambda body inline to proc
490 (lp (cdr gensyms)
491 (cdr vals)
492 (record-case (car vals)
493 ((<lambda> body)
494 (max nmax (allocate! body proc n))))))
495 (else
496 ;; allocate closure
497 (lp (cdr gensyms)
498 (cdr vals)
499 (max nmax (allocate! (car vals) proc n))))))
500
501 (let ((v (car in)))
502 (cond
503 ((hashq-ref assigned v)
504 (error "fixpoint procedures may not be assigned" x))
505 ((hashq-ref labels v)
506 ;; no binding, it's a label
507 (lp (cdr in) n))
508 (else
509 ;; allocate closure binding
510 (hashq-set! allocation v (make-hashq proc `(#t #f . ,n)))
511 (lp (cdr in) (1+ n))))))))
512
513 ((<let-values> exp body)
514 (max (recur exp) (recur body)))
515
516 ((<dynwind> winder pre body post unwinder)
517 (max (recur winder) (recur pre)
518 (recur body)
519 (recur post) (recur unwinder)))
520
521 ((<dynlet> fluids vals body)
522 (apply max (recur body) (map recur (append fluids vals))))
523
524 ((<dynref> fluid)
525 (recur fluid))
526
527 ((<dynset> fluid exp)
528 (max (recur fluid) (recur exp)))
529
530 ((<prompt> tag body handler)
531 (let ((cont-var (and (lambda-case? handler)
532 (pair? (lambda-case-gensyms handler))
533 (car (lambda-case-gensyms handler)))))
534 (hashq-set! allocation x
535 (and cont-var (zero? (hashq-ref refcounts cont-var 0))))
536 (max (recur tag) (recur body) (recur handler))))
537
538 ((<abort> tag args tail)
539 (apply max (recur tag) (recur tail) (map recur args)))
540
541 (else n)))
542
543 (analyze! x #f '() #t #f)
544 (allocate! x #f 0)
545
546 allocation)
547
548 \f
549 ;;;
550 ;;; Tree analyses for warnings.
551 ;;;
552
553 (define-record-type <tree-analysis>
554 (make-tree-analysis leaf down up post init)
555 tree-analysis?
556 (leaf tree-analysis-leaf) ;; (lambda (x result env locs) ...)
557 (down tree-analysis-down) ;; (lambda (x result env locs) ...)
558 (up tree-analysis-up) ;; (lambda (x result env locs) ...)
559 (post tree-analysis-post) ;; (lambda (result env) ...)
560 (init tree-analysis-init)) ;; arbitrary value
561
562 (define (analyze-tree analyses tree env)
563 "Run all tree analyses listed in ANALYSES on TREE for ENV, using
564 `tree-il-fold'. Return TREE. The leaf/down/up procedures of each analysis are
565 passed a ``location stack', which is the stack of `tree-il-src' values for each
566 parent tree (a list); it can be used to approximate source location when
567 accurate information is missing from a given `tree-il' element."
568
569 (define (traverse proc update-locs)
570 ;; Return a tree traversing procedure that returns a list of analysis
571 ;; results prepended by the location stack.
572 (lambda (x results)
573 (let ((locs (update-locs x (car results))))
574 (cons locs ;; the location stack
575 (map (lambda (analysis result)
576 ((proc analysis) x result env locs))
577 analyses
578 (cdr results))))))
579
580 ;; Keeping/extending/shrinking the location stack.
581 (define (keep-locs x locs) locs)
582 (define (extend-locs x locs) (cons (tree-il-src x) locs))
583 (define (shrink-locs x locs) (cdr locs))
584
585 (let ((results
586 (tree-il-fold (traverse tree-analysis-leaf keep-locs)
587 (traverse tree-analysis-down extend-locs)
588 (traverse tree-analysis-up shrink-locs)
589 (cons '() ;; empty location stack
590 (map tree-analysis-init analyses))
591 tree)))
592
593 (for-each (lambda (analysis result)
594 ((tree-analysis-post analysis) result env))
595 analyses
596 (cdr results)))
597
598 tree)
599
600 \f
601 ;;;
602 ;;; Unused variable analysis.
603 ;;;
604
605 ;; <binding-info> records are used during tree traversals in
606 ;; `unused-variable-analysis'. They contain a list of the local vars
607 ;; currently in scope, and a list of locals vars that have been referenced.
608 (define-record-type <binding-info>
609 (make-binding-info vars refs)
610 binding-info?
611 (vars binding-info-vars) ;; ((GENSYM NAME LOCATION) ...)
612 (refs binding-info-refs)) ;; (GENSYM ...)
613
614 (define (gensym? sym)
615 ;; Return #t if SYM is (likely) a generated symbol.
616 (string-any #\space (symbol->string sym)))
617
618 (define unused-variable-analysis
619 ;; Report unused variables in the given tree.
620 (make-tree-analysis
621 (lambda (x info env locs)
622 ;; X is a leaf: extend INFO's refs accordingly.
623 (let ((refs (binding-info-refs info))
624 (vars (binding-info-vars info)))
625 (record-case x
626 ((<lexical-ref> gensym)
627 (make-binding-info vars (vhash-consq gensym #t refs)))
628 (else info))))
629
630 (lambda (x info env locs)
631 ;; Going down into X: extend INFO's variable list
632 ;; accordingly.
633 (let ((refs (binding-info-refs info))
634 (vars (binding-info-vars info))
635 (src (tree-il-src x)))
636 (define (extend inner-vars inner-names)
637 (fold (lambda (var name vars)
638 (vhash-consq var (list name src) vars))
639 vars
640 inner-vars
641 inner-names))
642
643 (record-case x
644 ((<lexical-set> gensym)
645 (make-binding-info vars (vhash-consq gensym #t refs)))
646 ((<lambda-case> req opt inits rest kw gensyms)
647 (let ((names `(,@req
648 ,@(or opt '())
649 ,@(if rest (list rest) '())
650 ,@(if kw (map cadr (cdr kw)) '()))))
651 (make-binding-info (extend gensyms names) refs)))
652 ((<let> gensyms names)
653 (make-binding-info (extend gensyms names) refs))
654 ((<letrec> gensyms names)
655 (make-binding-info (extend gensyms names) refs))
656 ((<fix> gensyms names)
657 (make-binding-info (extend gensyms names) refs))
658 (else info))))
659
660 (lambda (x info env locs)
661 ;; Leaving X's scope: shrink INFO's variable list
662 ;; accordingly and reported unused nested variables.
663 (let ((refs (binding-info-refs info))
664 (vars (binding-info-vars info)))
665 (define (shrink inner-vars refs)
666 (vlist-for-each
667 (lambda (var)
668 (let ((gensym (car var)))
669 ;; Don't report lambda parameters as unused.
670 (if (and (memq gensym inner-vars)
671 (not (vhash-assq gensym refs))
672 (not (lambda-case? x)))
673 (let ((name (cadr var))
674 ;; We can get approximate source location by going up
675 ;; the LOCS location stack.
676 (loc (or (caddr var)
677 (find pair? locs))))
678 (if (and (not (gensym? name))
679 (not (eq? name '_)))
680 (warning 'unused-variable loc name))))))
681 vars)
682 (vlist-drop vars (length inner-vars)))
683
684 ;; For simplicity, we leave REFS untouched, i.e., with
685 ;; names of variables that are now going out of scope.
686 ;; It doesn't hurt as these are unique names, it just
687 ;; makes REFS unnecessarily fat.
688 (record-case x
689 ((<lambda-case> gensyms)
690 (make-binding-info (shrink gensyms refs) refs))
691 ((<let> gensyms)
692 (make-binding-info (shrink gensyms refs) refs))
693 ((<letrec> gensyms)
694 (make-binding-info (shrink gensyms refs) refs))
695 ((<fix> gensyms)
696 (make-binding-info (shrink gensyms refs) refs))
697 (else info))))
698
699 (lambda (result env) #t)
700 (make-binding-info vlist-null vlist-null)))
701
702 \f
703 ;;;
704 ;;; Unused top-level variable analysis.
705 ;;;
706
707 ;; <reference-graph> record top-level definitions that are made, references to
708 ;; top-level definitions and their context (the top-level definition in which
709 ;; the reference appears), as well as the current context (the top-level
710 ;; definition we're currently in). The second part (`refs' below) is
711 ;; effectively a graph from which we can determine unused top-level definitions.
712 (define-record-type <reference-graph>
713 (make-reference-graph refs defs toplevel-context)
714 reference-graph?
715 (defs reference-graph-defs) ;; ((NAME . LOC) ...)
716 (refs reference-graph-refs) ;; ((REF-CONTEXT REF ...) ...)
717 (toplevel-context reference-graph-toplevel-context)) ;; NAME | #f
718
719 (define (graph-reachable-nodes root refs reachable)
720 ;; Add to REACHABLE the nodes reachable from ROOT in graph REFS. REFS is a
721 ;; vhash mapping nodes to the list of their children: for instance,
722 ;; ((A -> (B C)) (B -> (A)) (C -> ())) corresponds to
723 ;;
724 ;; ,-------.
725 ;; v |
726 ;; A ----> B
727 ;; |
728 ;; v
729 ;; C
730 ;;
731 ;; REACHABLE is a vhash of nodes known to be otherwise reachable.
732
733 (let loop ((root root)
734 (path vlist-null)
735 (result reachable))
736 (if (or (vhash-assq root path)
737 (vhash-assq root result))
738 result
739 (let* ((children (or (and=> (vhash-assq root refs) cdr) '()))
740 (path (vhash-consq root #t path))
741 (result (fold (lambda (kid result)
742 (loop kid path result))
743 result
744 children)))
745 (fold (lambda (kid result)
746 (vhash-consq kid #t result))
747 result
748 children)))))
749
750 (define (graph-reachable-nodes* roots refs)
751 ;; Return the list of nodes in REFS reachable from the nodes listed in ROOTS.
752 (vlist-fold (lambda (root+true result)
753 (let* ((root (car root+true))
754 (reachable (graph-reachable-nodes root refs result)))
755 (vhash-consq root #t reachable)))
756 vlist-null
757 roots))
758
759 (define (partition* pred vhash)
760 ;; Partition VHASH according to PRED. Return the two resulting vhashes.
761 (let ((result
762 (vlist-fold (lambda (k+v result)
763 (let ((k (car k+v))
764 (v (cdr k+v))
765 (r1 (car result))
766 (r2 (cdr result)))
767 (if (pred k)
768 (cons (vhash-consq k v r1) r2)
769 (cons r1 (vhash-consq k v r2)))))
770 (cons vlist-null vlist-null)
771 vhash)))
772 (values (car result) (cdr result))))
773
774 (define unused-toplevel-analysis
775 ;; Report unused top-level definitions that are not exported.
776 (let ((add-ref-from-context
777 (lambda (graph name)
778 ;; Add an edge CTX -> NAME in GRAPH.
779 (let* ((refs (reference-graph-refs graph))
780 (defs (reference-graph-defs graph))
781 (ctx (reference-graph-toplevel-context graph))
782 (ctx-refs (or (and=> (vhash-assq ctx refs) cdr) '())))
783 (make-reference-graph (vhash-consq ctx (cons name ctx-refs) refs)
784 defs ctx)))))
785 (define (macro-variable? name env)
786 (and (module? env)
787 (let ((var (module-variable env name)))
788 (and var (variable-bound? var)
789 (macro? (variable-ref var))))))
790
791 (make-tree-analysis
792 (lambda (x graph env locs)
793 ;; X is a leaf.
794 (let ((ctx (reference-graph-toplevel-context graph)))
795 (record-case x
796 ((<toplevel-ref> name src)
797 (add-ref-from-context graph name))
798 (else graph))))
799
800 (lambda (x graph env locs)
801 ;; Going down into X.
802 (let ((ctx (reference-graph-toplevel-context graph))
803 (refs (reference-graph-refs graph))
804 (defs (reference-graph-defs graph)))
805 (record-case x
806 ((<toplevel-define> name src)
807 (let ((refs refs)
808 (defs (vhash-consq name (or src (find pair? locs))
809 defs)))
810 (make-reference-graph refs defs name)))
811 ((<toplevel-set> name src)
812 (add-ref-from-context graph name))
813 (else graph))))
814
815 (lambda (x graph env locs)
816 ;; Leaving X's scope.
817 (record-case x
818 ((<toplevel-define>)
819 (let ((refs (reference-graph-refs graph))
820 (defs (reference-graph-defs graph)))
821 (make-reference-graph refs defs #f)))
822 (else graph)))
823
824 (lambda (graph env)
825 ;; Process the resulting reference graph: determine all private definitions
826 ;; not reachable from any public definition. Macros
827 ;; (syntax-transformers), which are globally bound, never considered
828 ;; unused since we can't tell whether a macro is actually used; in
829 ;; addition, macros are considered roots of the graph since they may use
830 ;; private bindings. FIXME: The `make-syntax-transformer' calls don't
831 ;; contain any literal `toplevel-ref' of the global bindings they use so
832 ;; this strategy fails.
833 (define (exported? name)
834 (if (module? env)
835 (module-variable (module-public-interface env) name)
836 #t))
837
838 (let-values (((public-defs private-defs)
839 (partition* (lambda (name)
840 (or (exported? name)
841 (macro-variable? name env)))
842 (reference-graph-defs graph))))
843 (let* ((roots (vhash-consq #f #t public-defs))
844 (refs (reference-graph-refs graph))
845 (reachable (graph-reachable-nodes* roots refs))
846 (unused (vlist-filter (lambda (name+src)
847 (not (vhash-assq (car name+src)
848 reachable)))
849 private-defs)))
850 (vlist-for-each (lambda (name+loc)
851 (let ((name (car name+loc))
852 (loc (cdr name+loc)))
853 (if (not (gensym? name))
854 (warning 'unused-toplevel loc name))))
855 unused))))
856
857 (make-reference-graph vlist-null vlist-null #f))))
858
859 \f
860 ;;;
861 ;;; Unbound variable analysis.
862 ;;;
863
864 ;; <toplevel-info> records are used during tree traversal in search of
865 ;; possibly unbound variable. They contain a list of references to
866 ;; potentially unbound top-level variables, and a list of the top-level
867 ;; defines that have been encountered.
868 (define-record-type <toplevel-info>
869 (make-toplevel-info refs defs)
870 toplevel-info?
871 (refs toplevel-info-refs) ;; ((VARIABLE-NAME . LOCATION) ...)
872 (defs toplevel-info-defs)) ;; (VARIABLE-NAME ...)
873
874 (define (goops-toplevel-definition proc args env)
875 ;; If call of PROC to ARGS is a GOOPS top-level definition, return
876 ;; the name of the variable being defined; otherwise return #f. This
877 ;; assumes knowledge of the current implementation of `define-class' et al.
878 (define (toplevel-define-arg args)
879 (match args
880 ((($ <const> _ (and (? symbol?) exp)) _)
881 exp)
882 (_ #f)))
883
884 (match proc
885 (($ <module-ref> _ '(oop goops) 'toplevel-define! #f)
886 (toplevel-define-arg args))
887 (($ <toplevel-ref> _ 'toplevel-define!)
888 ;; This may be the result of expanding one of the GOOPS macros within
889 ;; `oop/goops.scm'.
890 (and (eq? env (resolve-module '(oop goops)))
891 (toplevel-define-arg args)))
892 (_ #f)))
893
894 (define unbound-variable-analysis
895 ;; Report possibly unbound variables in the given tree.
896 (make-tree-analysis
897 (lambda (x info env locs)
898 ;; X is a leaf: extend INFO's refs accordingly.
899 (let ((refs (toplevel-info-refs info))
900 (defs (toplevel-info-defs info)))
901 (define (bound? name)
902 (or (and (module? env)
903 (module-variable env name))
904 (vhash-assq name defs)))
905
906 (record-case x
907 ((<toplevel-ref> name src)
908 (if (bound? name)
909 info
910 (let ((src (or src (find pair? locs))))
911 (make-toplevel-info (vhash-consq name src refs)
912 defs))))
913 (else info))))
914
915 (lambda (x info env locs)
916 ;; Going down into X.
917 (let* ((refs (toplevel-info-refs info))
918 (defs (toplevel-info-defs info))
919 (src (tree-il-src x)))
920 (define (bound? name)
921 (or (and (module? env)
922 (module-variable env name))
923 (vhash-assq name defs)))
924
925 (record-case x
926 ((<toplevel-set> name src)
927 (if (bound? name)
928 (make-toplevel-info refs defs)
929 (let ((src (find pair? locs)))
930 (make-toplevel-info (vhash-consq name src refs)
931 defs))))
932 ((<toplevel-define> name)
933 (make-toplevel-info (vhash-delq name refs)
934 (vhash-consq name #t defs)))
935
936 ((<call> proc args)
937 ;; Check for a dynamic top-level definition, as is
938 ;; done by code expanded from GOOPS macros.
939 (let ((name (goops-toplevel-definition proc args
940 env)))
941 (if (symbol? name)
942 (make-toplevel-info (vhash-delq name refs)
943 (vhash-consq name #t defs))
944 (make-toplevel-info refs defs))))
945 (else
946 (make-toplevel-info refs defs)))))
947
948 (lambda (x info env locs)
949 ;; Leaving X's scope.
950 info)
951
952 (lambda (toplevel env)
953 ;; Post-process the result.
954 (vlist-for-each (lambda (name+loc)
955 (let ((name (car name+loc))
956 (loc (cdr name+loc)))
957 (warning 'unbound-variable loc name)))
958 (vlist-reverse (toplevel-info-refs toplevel))))
959
960 (make-toplevel-info vlist-null vlist-null)))
961
962 \f
963 ;;;
964 ;;; Arity analysis.
965 ;;;
966
967 ;; <arity-info> records contain information about lexical definitions of
968 ;; procedures currently in scope, top-level procedure definitions that have
969 ;; been encountered, and calls to top-level procedures that have been
970 ;; encountered.
971 (define-record-type <arity-info>
972 (make-arity-info toplevel-calls lexical-lambdas toplevel-lambdas)
973 arity-info?
974 (toplevel-calls toplevel-procedure-calls) ;; ((NAME . CALL) ...)
975 (lexical-lambdas lexical-lambdas) ;; ((GENSYM . DEFINITION) ...)
976 (toplevel-lambdas toplevel-lambdas)) ;; ((NAME . DEFINITION) ...)
977
978 (define (validate-arity proc call lexical?)
979 ;; Validate the argument count of CALL, a tree-il call of
980 ;; PROC, emitting a warning in case of argument count mismatch.
981
982 (define (filter-keyword-args keywords allow-other-keys? args)
983 ;; Filter keyword arguments from ARGS and return the resulting list.
984 ;; KEYWORDS is the list of allowed keywords, and ALLOW-OTHER-KEYS?
985 ;; specified whethere keywords not listed in KEYWORDS are allowed.
986 (let loop ((args args)
987 (result '()))
988 (if (null? args)
989 (reverse result)
990 (let ((arg (car args)))
991 (if (and (const? arg)
992 (or (memq (const-exp arg) keywords)
993 (and allow-other-keys?
994 (keyword? (const-exp arg)))))
995 (loop (if (pair? (cdr args))
996 (cddr args)
997 '())
998 result)
999 (loop (cdr args)
1000 (cons arg result)))))))
1001
1002 (define (arities proc)
1003 ;; Return the arities of PROC, which can be either a tree-il or a
1004 ;; procedure.
1005 (define (len x)
1006 (or (and (or (null? x) (pair? x))
1007 (length x))
1008 0))
1009 (cond ((program? proc)
1010 (values (procedure-name proc)
1011 (map (lambda (a)
1012 (list (arity:nreq a) (arity:nopt a) (arity:rest? a)
1013 (map car (arity:kw a))
1014 (arity:allow-other-keys? a)))
1015 (program-arities proc))))
1016 ((procedure? proc)
1017 (let ((arity (procedure-minimum-arity proc)))
1018 (values (procedure-name proc)
1019 (list (list (car arity) (cadr arity) (caddr arity)
1020 #f #f)))))
1021 (else
1022 (let loop ((name #f)
1023 (proc proc)
1024 (arities '()))
1025 (if (not proc)
1026 (values name (reverse arities))
1027 (record-case proc
1028 ((<lambda-case> req opt rest kw alternate)
1029 (loop name alternate
1030 (cons (list (len req) (len opt) rest
1031 (and (pair? kw) (map car (cdr kw)))
1032 (and (pair? kw) (car kw)))
1033 arities)))
1034 ((<lambda> meta body)
1035 (loop (assoc-ref meta 'name) body arities))
1036 (else
1037 (values #f #f))))))))
1038
1039 (let ((args (call-args call))
1040 (src (tree-il-src call)))
1041 (call-with-values (lambda () (arities proc))
1042 (lambda (name arities)
1043 (define matches?
1044 (find (lambda (arity)
1045 (pmatch arity
1046 ((,req ,opt ,rest? ,kw ,aok?)
1047 (let ((args (if (pair? kw)
1048 (filter-keyword-args kw aok? args)
1049 args)))
1050 (if (and req opt)
1051 (let ((count (length args)))
1052 (and (>= count req)
1053 (or rest?
1054 (<= count (+ req opt)))))
1055 #t)))
1056 (else #t)))
1057 arities))
1058
1059 (if (not matches?)
1060 (warning 'arity-mismatch src
1061 (or name (with-output-to-string (lambda () (write proc))))
1062 lexical?)))))
1063 #t)
1064
1065 (define arity-analysis
1066 ;; Report arity mismatches in the given tree.
1067 (make-tree-analysis
1068 (lambda (x info env locs)
1069 ;; X is a leaf.
1070 info)
1071 (lambda (x info env locs)
1072 ;; Down into X.
1073 (define (extend lexical-name val info)
1074 ;; If VAL is a lambda, add NAME to the lexical-lambdas of INFO.
1075 (let ((toplevel-calls (toplevel-procedure-calls info))
1076 (lexical-lambdas (lexical-lambdas info))
1077 (toplevel-lambdas (toplevel-lambdas info)))
1078 (record-case val
1079 ((<lambda> body)
1080 (make-arity-info toplevel-calls
1081 (vhash-consq lexical-name val
1082 lexical-lambdas)
1083 toplevel-lambdas))
1084 ((<lexical-ref> gensym)
1085 ;; lexical alias
1086 (let ((val* (vhash-assq gensym lexical-lambdas)))
1087 (if (pair? val*)
1088 (extend lexical-name (cdr val*) info)
1089 info)))
1090 ((<toplevel-ref> name)
1091 ;; top-level alias
1092 (make-arity-info toplevel-calls
1093 (vhash-consq lexical-name val
1094 lexical-lambdas)
1095 toplevel-lambdas))
1096 (else info))))
1097
1098 (let ((toplevel-calls (toplevel-procedure-calls info))
1099 (lexical-lambdas (lexical-lambdas info))
1100 (toplevel-lambdas (toplevel-lambdas info)))
1101
1102 (record-case x
1103 ((<toplevel-define> name exp)
1104 (record-case exp
1105 ((<lambda> body)
1106 (make-arity-info toplevel-calls
1107 lexical-lambdas
1108 (vhash-consq name exp toplevel-lambdas)))
1109 ((<toplevel-ref> name)
1110 ;; alias for another toplevel
1111 (let ((proc (vhash-assq name toplevel-lambdas)))
1112 (make-arity-info toplevel-calls
1113 lexical-lambdas
1114 (vhash-consq (toplevel-define-name x)
1115 (if (pair? proc)
1116 (cdr proc)
1117 exp)
1118 toplevel-lambdas))))
1119 (else info)))
1120 ((<let> gensyms vals)
1121 (fold extend info gensyms vals))
1122 ((<letrec> gensyms vals)
1123 (fold extend info gensyms vals))
1124 ((<fix> gensyms vals)
1125 (fold extend info gensyms vals))
1126
1127 ((<call> proc args src)
1128 (record-case proc
1129 ((<lambda> body)
1130 (validate-arity proc x #t)
1131 info)
1132 ((<toplevel-ref> name)
1133 (make-arity-info (vhash-consq name x toplevel-calls)
1134 lexical-lambdas
1135 toplevel-lambdas))
1136 ((<lexical-ref> gensym)
1137 (let ((proc (vhash-assq gensym lexical-lambdas)))
1138 (if (pair? proc)
1139 (record-case (cdr proc)
1140 ((<toplevel-ref> name)
1141 ;; alias to toplevel
1142 (make-arity-info (vhash-consq name x toplevel-calls)
1143 lexical-lambdas
1144 toplevel-lambdas))
1145 (else
1146 (validate-arity (cdr proc) x #t)
1147 info))
1148
1149 ;; If GENSYM wasn't found, it may be because it's an
1150 ;; argument of the procedure being compiled.
1151 info)))
1152 (else info)))
1153 (else info))))
1154
1155 (lambda (x info env locs)
1156 ;; Up from X.
1157 (define (shrink name val info)
1158 ;; Remove NAME from the lexical-lambdas of INFO.
1159 (let ((toplevel-calls (toplevel-procedure-calls info))
1160 (lexical-lambdas (lexical-lambdas info))
1161 (toplevel-lambdas (toplevel-lambdas info)))
1162 (make-arity-info toplevel-calls
1163 (if (vhash-assq name lexical-lambdas)
1164 (vlist-tail lexical-lambdas)
1165 lexical-lambdas)
1166 toplevel-lambdas)))
1167
1168 (let ((toplevel-calls (toplevel-procedure-calls info))
1169 (lexical-lambdas (lexical-lambdas info))
1170 (toplevel-lambdas (toplevel-lambdas info)))
1171 (record-case x
1172 ((<let> gensyms vals)
1173 (fold shrink info gensyms vals))
1174 ((<letrec> gensyms vals)
1175 (fold shrink info gensyms vals))
1176 ((<fix> gensyms vals)
1177 (fold shrink info gensyms vals))
1178
1179 (else info))))
1180
1181 (lambda (result env)
1182 ;; Post-processing: check all top-level procedure calls that have been
1183 ;; encountered.
1184 (let ((toplevel-calls (toplevel-procedure-calls result))
1185 (toplevel-lambdas (toplevel-lambdas result)))
1186 (vlist-for-each
1187 (lambda (name+call)
1188 (let* ((name (car name+call))
1189 (call (cdr name+call))
1190 (proc
1191 (or (and=> (vhash-assq name toplevel-lambdas) cdr)
1192 (and (module? env)
1193 (false-if-exception
1194 (module-ref env name)))))
1195 (proc*
1196 ;; handle toplevel aliases
1197 (if (toplevel-ref? proc)
1198 (let ((name (toplevel-ref-name proc)))
1199 (and (module? env)
1200 (false-if-exception
1201 (module-ref env name))))
1202 proc)))
1203 (if (or (lambda? proc*) (procedure? proc*))
1204 (validate-arity proc* call (lambda? proc*)))))
1205 toplevel-calls)))
1206
1207 (make-arity-info vlist-null vlist-null vlist-null)))
1208
1209 \f
1210 ;;;
1211 ;;; `format' argument analysis.
1212 ;;;
1213
1214 (define &syntax-error
1215 ;; The `throw' key for syntax errors.
1216 (gensym "format-string-syntax-error"))
1217
1218 (define (format-string-argument-count fmt)
1219 ;; Return the minimum and maxium number of arguments that should
1220 ;; follow format string FMT (or, ahem, a good estimate thereof) or
1221 ;; `any' if the format string can be followed by any number of
1222 ;; arguments.
1223
1224 (define (drop-group chars end)
1225 ;; Drop characters from CHARS until "~END" is encountered.
1226 (let loop ((chars chars)
1227 (tilde? #f))
1228 (if (null? chars)
1229 (throw &syntax-error 'unterminated-iteration)
1230 (if tilde?
1231 (if (eq? (car chars) end)
1232 (cdr chars)
1233 (loop (cdr chars) #f))
1234 (if (eq? (car chars) #\~)
1235 (loop (cdr chars) #t)
1236 (loop (cdr chars) #f))))))
1237
1238 (define (digit? char)
1239 ;; Return true if CHAR is a digit, #f otherwise.
1240 (memq char '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))
1241
1242 (define (previous-number chars)
1243 ;; Return the previous series of digits found in CHARS.
1244 (let ((numbers (take-while digit? chars)))
1245 (and (not (null? numbers))
1246 (string->number (list->string (reverse numbers))))))
1247
1248 (let loop ((chars (string->list fmt))
1249 (state 'literal)
1250 (params '())
1251 (conditions '())
1252 (end-group #f)
1253 (min-count 0)
1254 (max-count 0))
1255 (if (null? chars)
1256 (if end-group
1257 (throw &syntax-error 'unterminated-conditional)
1258 (values min-count max-count))
1259 (case state
1260 ((tilde)
1261 (case (car chars)
1262 ((#\~ #\% #\& #\t #\_ #\newline #\( #\))
1263 (loop (cdr chars) 'literal '()
1264 conditions end-group
1265 min-count max-count))
1266 ((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\, #\: #\@)
1267 (loop (cdr chars)
1268 'tilde (cons (car chars) params)
1269 conditions end-group
1270 min-count max-count))
1271 ((#\v #\V) (loop (cdr chars)
1272 'tilde (cons (car chars) params)
1273 conditions end-group
1274 (+ 1 min-count)
1275 (+ 1 max-count)))
1276 ((#\[)
1277 (loop chars 'literal '() '()
1278 (let ((selector (previous-number params))
1279 (at? (memq #\@ params)))
1280 (lambda (chars conds)
1281 ;; end of group
1282 (let ((mins (map car conds))
1283 (maxs (map cdr conds))
1284 (sel? (and selector
1285 (< selector (length conds)))))
1286 (if (and (every number? mins)
1287 (every number? maxs))
1288 (loop chars 'literal '() conditions end-group
1289 (+ min-count
1290 (if sel?
1291 (car (list-ref conds selector))
1292 (+ (if at? 0 1)
1293 (if (null? mins)
1294 0
1295 (apply min mins)))))
1296 (+ max-count
1297 (if sel?
1298 (cdr (list-ref conds selector))
1299 (+ (if at? 0 1)
1300 (if (null? maxs)
1301 0
1302 (apply max maxs))))))
1303 (values 'any 'any))))) ;; XXX: approximation
1304 0 0))
1305 ((#\;)
1306 (if end-group
1307 (loop (cdr chars) 'literal '()
1308 (cons (cons min-count max-count) conditions)
1309 end-group
1310 0 0)
1311 (throw &syntax-error 'unexpected-semicolon)))
1312 ((#\])
1313 (if end-group
1314 (end-group (cdr chars)
1315 (reverse (cons (cons min-count max-count)
1316 conditions)))
1317 (throw &syntax-error 'unexpected-conditional-termination)))
1318 ((#\{) (if (memq #\@ params)
1319 (values min-count 'any)
1320 (loop (drop-group (cdr chars) #\})
1321 'literal '()
1322 conditions end-group
1323 (+ 1 min-count) (+ 1 max-count))))
1324 ((#\*) (if (memq #\@ params)
1325 (values 'any 'any) ;; it's unclear what to do here
1326 (loop (cdr chars)
1327 'literal '()
1328 conditions end-group
1329 (+ (or (previous-number params) 1)
1330 min-count)
1331 (+ (or (previous-number params) 1)
1332 max-count))))
1333 ((#\? #\k)
1334 ;; We don't have enough info to determine the exact number
1335 ;; of args, but we could determine a lower bound (TODO).
1336 (values 'any 'any))
1337 (else (loop (cdr chars) 'literal '()
1338 conditions end-group
1339 (+ 1 min-count) (+ 1 max-count)))))
1340 ((literal)
1341 (case (car chars)
1342 ((#\~) (loop (cdr chars) 'tilde '()
1343 conditions end-group
1344 min-count max-count))
1345 (else (loop (cdr chars) 'literal '()
1346 conditions end-group
1347 min-count max-count))))
1348 (else (error "computer bought the farm" state))))))
1349
1350 (define (const-fmt x)
1351 ;; Return the literal format pattern for X, or #f.
1352 (match x
1353 (($ <const> _ exp)
1354 exp)
1355 (($ <call> _
1356 (or ($ <toplevel-ref> _ '_) ($ <module-ref> _ '_))
1357 (($ <const> _ (and (? string?) fmt))))
1358 ;; Gettexted literals, like `(_ "foo")'.
1359 fmt)
1360 (_ #f)))
1361
1362 (define format-analysis
1363 ;; Report arity mismatches in the given tree.
1364 (make-tree-analysis
1365 (lambda (x _ env locs)
1366 ;; X is a leaf.
1367 #t)
1368
1369 (lambda (x _ env locs)
1370 ;; Down into X.
1371 (define (check-format-args args loc)
1372 (pmatch args
1373 ((,port ,fmt . ,rest)
1374 (guard (const-fmt fmt))
1375 (if (and (const? port)
1376 (not (boolean? (const-exp port))))
1377 (warning 'format loc 'wrong-port (const-exp port)))
1378 (let ((fmt (const-fmt fmt))
1379 (count (length rest)))
1380 (if (string? fmt)
1381 (catch &syntax-error
1382 (lambda ()
1383 (let-values (((min max)
1384 (format-string-argument-count fmt)))
1385 (and min max
1386 (or (and (or (eq? min 'any) (>= count min))
1387 (or (eq? max 'any) (<= count max)))
1388 (warning 'format loc 'wrong-format-arg-count
1389 fmt min max count)))))
1390 (lambda (_ key)
1391 (warning 'format loc 'syntax-error key fmt)))
1392 (warning 'format loc 'wrong-format-string fmt))))
1393 ((,port ,fmt . ,rest)
1394 (if (and (const? port)
1395 (not (boolean? (const-exp port))))
1396 (warning 'format loc 'wrong-port (const-exp port)))
1397 ;; Warn on non-literal format strings, unless they refer to a
1398 ;; lexical variable named "fmt".
1399 (if (record-case fmt
1400 ((<lexical-ref> name)
1401 (not (eq? name 'fmt)))
1402 (else #t))
1403 (warning 'format loc 'non-literal-format-string)))
1404 (else
1405 (warning 'format loc 'wrong-num-args (length args)))))
1406
1407 (define (check-simple-format-args args loc)
1408 ;; Check the arguments to the `simple-format' procedure, which is
1409 ;; less capable than that of (ice-9 format).
1410
1411 (define allowed-chars
1412 '(#\A #\S #\a #\s #\~ #\%))
1413
1414 (define (format-chars fmt)
1415 (let loop ((chars (string->list fmt))
1416 (result '()))
1417 (match chars
1418 (()
1419 (reverse result))
1420 ((#\~ opt rest ...)
1421 (loop rest (cons opt result)))
1422 ((_ rest ...)
1423 (loop rest result)))))
1424
1425 (match args
1426 ((port ($ <const> _ (? string? fmt)) _ ...)
1427 (let ((opts (format-chars fmt)))
1428 (or (every (cut memq <> allowed-chars) opts)
1429 (begin
1430 (warning 'format loc 'simple-format fmt
1431 (find (negate (cut memq <> allowed-chars)) opts))
1432 #f))))
1433 ((port (($ <const> _ '_) fmt) args ...)
1434 (check-simple-format-args `(,port ,fmt ,args) loc))
1435 (_ #t)))
1436
1437 (define (resolve-toplevel name)
1438 (and (module? env)
1439 (false-if-exception (module-ref env name))))
1440
1441 (match x
1442 (($ <call> src ($ <toplevel-ref> _ name) args)
1443 (let ((proc (resolve-toplevel name)))
1444 (if (or (and (eq? proc (@ (guile) simple-format))
1445 (check-simple-format-args args
1446 (or src (find pair? locs))))
1447 (eq? proc (@ (ice-9 format) format)))
1448 (check-format-args args (or src (find pair? locs))))))
1449 (($ <call> src ($ <module-ref> _ '(ice-9 format) 'format) args)
1450 (check-format-args args (or src (find pair? locs))))
1451 (($ <call> src ($ <module-ref> _ '(guile)
1452 (or 'format 'simple-format))
1453 args)
1454 (and (check-simple-format-args args
1455 (or src (find pair? locs)))
1456 (check-format-args args (or src (find pair? locs)))))
1457 (_ #t))
1458 #t)
1459
1460 (lambda (x _ env locs)
1461 ;; Up from X.
1462 #t)
1463
1464 (lambda (_ env)
1465 ;; Post-processing.
1466 #t)
1467
1468 #t))