1 ;;; TREE-IL -> GLIL compiler
3 ;; Copyright (C) 2001, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
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.
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.
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
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
35 unused-variable-analysis
36 unused-toplevel-analysis
37 unbound-variable-analysis
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.
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:
49 ;; (lambda (a) a) ; a will be local
50 ;; `a' is local to the procedure.
52 ;; (lambda (a) (lambda () a))
53 ;; `a' is local to the outer procedure, but a closure variable with
54 ;; respect to the inner procedure.
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.
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:
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
80 ;; -> (let ((a x)) (if a a (let ((b y)) (if b b z))))
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.
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.
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
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
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.
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!
112 ;; The return value of `analyze-lexicals' is a hash table, the
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.
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.
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
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.
139 ;; sym -> {lambda -> address}
140 ;; lambda -> (labels . free-locs)
141 ;; lambda-case -> (gensym . nlocs)
142 ;; prompt -> escape-only?
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.
149 (define (make-hashq k v)
150 (let ((res (make-hash-table)))
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
171 (define labels (make-hash-table))
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
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))
184 (apply lset-union eq? (step-tail-call proc args)
188 (apply lset-union eq? (map step args)))
190 ((<conditional> test consequent alternate)
191 (lset-union eq? (step test) (step-tail consequent) (step-tail alternate)))
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)))
199 (let lp ((c (lambda-body p)))
200 (and c (lambda-case? c)
202 ;; for now prohibit optional &
203 ;; keyword arguments; can relax this
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))
214 ((<lexical-set> gensym exp)
215 (hashq-set! assigned gensym #t)
216 (hashq-set! labels gensym #f)
217 (lset-adjoin eq? (step exp) gensym))
222 ((<toplevel-set> exp)
225 ((<toplevel-define> exp)
229 (lset-union eq? (step head) (step-tail tail)))
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)
239 ((<lambda-case> opt kw inits gensyms body alternate)
240 (hashq-set! bound-vars proc
241 (append (reverse gensyms) (hashq-ref bound-vars proc)))
246 (apply lset-union eq? (map step inits))
249 (if alternate (step-tail alternate) '())))
251 ((<let> gensyms vals body)
252 (hashq-set! bound-vars proc
253 (append (reverse gensyms) (hashq-ref bound-vars proc)))
255 (apply lset-union eq? (step-tail body) (map step vals))
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)
263 (apply lset-union eq? (step-tail body) (map step vals))
266 ((<fix> gensyms vals body)
267 ;; Try to allocate these procedures as labels.
268 (for-each (lambda (sym val) (hashq-set! labels sym val))
270 (hashq-set! bound-vars proc
271 (append (reverse gensyms) (hashq-ref bound-vars proc)))
272 ;; Step into subexpressions.
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.)
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)
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)))
296 (for-each (lambda (sym)
297 (if (hashq-ref labels sym)
299 (hashq-set! labels sym #f)
300 (delabel-dependents! sym))))
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)))
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)))
319 ;; Now lift bound variables with label-allocated lambdas to the
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.
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))))
334 (apply lset-union eq? body-refs var-refs)
337 ((<let-values> exp body)
338 (lset-union eq? (step exp) (step body)))
340 ((<dynwind> winder pre body post unwinder)
341 (lset-union eq? (step winder) (step pre)
343 (step post) (step unwinder)))
345 ((<dynlet> fluids vals body)
346 (apply lset-union eq? (step body) (map step (append fluids vals))))
351 ((<dynset> fluid exp)
352 (lset-union eq? (step fluid) (step exp)))
354 ((<prompt> tag body handler)
355 (lset-union eq? (step tag) (step body) (step-tail handler)))
357 ((<abort> tag args tail)
358 (apply lset-union eq? (step tag) (step tail) (map step args)))
362 ;; allocation: sym -> {lambda -> address}
363 ;; lambda -> (labels . free-locs)
364 ;; lambda-case -> (gensym . nlocs)
365 (define allocation (make-hash-table))
367 (define (allocate! x proc n)
368 (define (recur y) (allocate! y proc n))
371 (apply max (recur proc) (map recur args)))
374 (apply max n (map recur args)))
376 ((<conditional> test consequent alternate)
377 (max (recur test) (recur consequent) (recur alternate)))
385 ((<toplevel-set> exp)
388 ((<toplevel-define> exp)
396 ;; allocate closure vars in order
397 (let lp ((c (hashq-ref free-vars x)) (n 0))
400 (hashq-set! (hashq-ref allocation (car c))
402 `(#f ,(hashq-ref assigned (car c)) . ,n))
403 (lp (cdr c) (1+ n)))))
405 (let ((nlocs (allocate! body x 0))
408 (hashq-ref (hashq-ref allocation v) proc))
409 (hashq-ref free-vars x)))
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)))
418 ((<lambda-case> opt kw inits gensyms body alternate)
420 (let lp ((gensyms gensyms) (n n))
424 (allocate! body proc n)
425 ;; inits not logically at the end, but they
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))
432 (hashq-set! allocation (car gensyms)
434 proc `(#t ,(hashq-ref assigned (car gensyms)) . ,n)))
435 (lp (cdr gensyms) (1+ n)))))
436 (if alternate (allocate! alternate proc n) n)))
438 ((<let> gensyms vals body)
439 (let ((nmax (apply max (map recur vals))))
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)))
456 (let lp ((gensyms gensyms) (n n))
458 (max nmax (allocate! body proc n))
459 (let ((v (car gensyms)))
463 `(#t ,(hashq-ref assigned v) . ,n)))
464 (lp (cdr gensyms) (1+ n)))))))))
466 ((<letrec> gensyms vals body)
467 (let lp ((gensyms gensyms) (n n))
469 (let ((nmax (apply max
471 (allocate! x proc n))
473 (max nmax (allocate! body proc n)))
474 (let ((v (car gensyms)))
478 `(#t ,(hashq-ref assigned v) . ,n)))
479 (lp (cdr gensyms) (1+ n))))))
481 ((<fix> gensyms vals body)
482 (let lp ((in gensyms) (n n))
484 (let lp ((gensyms gensyms) (vals vals) (nmax n))
487 (max nmax (allocate! body proc n)))
488 ((hashq-ref labels (car gensyms))
489 ;; allocate lambda body inline to proc
492 (record-case (car vals)
494 (max nmax (allocate! body proc n))))))
499 (max nmax (allocate! (car vals) proc n))))))
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
509 ;; allocate closure binding
510 (hashq-set! allocation v (make-hashq proc `(#t #f . ,n)))
511 (lp (cdr in) (1+ n))))))))
513 ((<let-values> exp body)
514 (max (recur exp) (recur body)))
516 ((<dynwind> winder pre body post unwinder)
517 (max (recur winder) (recur pre)
519 (recur post) (recur unwinder)))
521 ((<dynlet> fluids vals body)
522 (apply max (recur body) (map recur (append fluids vals))))
527 ((<dynset> fluid exp)
528 (max (recur fluid) (recur exp)))
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))))
538 ((<abort> tag args tail)
539 (apply max (recur tag) (recur tail) (map recur args)))
543 (analyze! x #f '() #t #f)
550 ;;; Tree analyses for warnings.
553 (define-record-type <tree-analysis>
554 (make-tree-analysis leaf down up post init)
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
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."
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.
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))
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))
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))
593 (for-each (lambda (analysis result)
594 ((tree-analysis-post analysis) result env))
602 ;;; Unused variable analysis.
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)
611 (vars binding-info-vars) ;; ((GENSYM NAME LOCATION) ...)
612 (refs binding-info-refs)) ;; (GENSYM ...)
614 (define (gensym? sym)
615 ;; Return #t if SYM is (likely) a generated symbol.
616 (string-any #\space (symbol->string sym)))
618 (define unused-variable-analysis
619 ;; Report unused variables in the given tree.
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)))
626 ((<lexical-ref> gensym)
627 (make-binding-info vars (vhash-consq gensym #t refs)))
630 (lambda (x info env locs)
631 ;; Going down into X: extend INFO's variable list
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))
644 ((<lexical-set> gensym)
645 (make-binding-info vars (vhash-consq gensym #t refs)))
646 ((<lambda-case> req opt inits rest kw gensyms)
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))
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)
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.
678 (if (and (not (gensym? name))
680 (warning 'unused-variable loc name))))))
682 (vlist-drop vars (length inner-vars)))
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.
689 ((<lambda-case> gensyms)
690 (make-binding-info (shrink gensyms refs) refs))
692 (make-binding-info (shrink gensyms refs) refs))
694 (make-binding-info (shrink gensyms refs) refs))
696 (make-binding-info (shrink gensyms refs) refs))
699 (lambda (result env) #t)
700 (make-binding-info vlist-null vlist-null)))
704 ;;; Unused top-level variable analysis.
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)
715 (defs reference-graph-defs) ;; ((NAME . LOC) ...)
716 (refs reference-graph-refs) ;; ((REF-CONTEXT REF ...) ...)
717 (toplevel-context reference-graph-toplevel-context)) ;; NAME | #f
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
731 ;; REACHABLE is a vhash of nodes known to be otherwise reachable.
733 (let loop ((root root)
736 (if (or (vhash-assq root path)
737 (vhash-assq root 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))
745 (fold (lambda (kid result)
746 (vhash-consq kid #t result))
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)))
759 (define (partition* pred vhash)
760 ;; Partition VHASH according to PRED. Return the two resulting vhashes.
762 (vlist-fold (lambda (k+v result)
768 (cons (vhash-consq k v r1) r2)
769 (cons r1 (vhash-consq k v r2)))))
770 (cons vlist-null vlist-null)
772 (values (car result) (cdr result))))
774 (define unused-toplevel-analysis
775 ;; Report unused top-level definitions that are not exported.
776 (let ((add-ref-from-context
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)
785 (define (macro-variable? name env)
787 (let ((var (module-variable env name)))
788 (and var (variable-bound? var)
789 (macro? (variable-ref var))))))
792 (lambda (x graph env locs)
794 (let ((ctx (reference-graph-toplevel-context graph)))
796 ((<toplevel-ref> name src)
797 (add-ref-from-context graph name))
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)))
806 ((<toplevel-define> name src)
808 (defs (vhash-consq name (or src (find pair? locs))
810 (make-reference-graph refs defs name)))
811 ((<toplevel-set> name src)
812 (add-ref-from-context graph name))
815 (lambda (x graph env locs)
816 ;; Leaving X's scope.
819 (let ((refs (reference-graph-refs graph))
820 (defs (reference-graph-defs graph)))
821 (make-reference-graph refs defs #f)))
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)
835 (module-variable (module-public-interface env) name)
838 (let-values (((public-defs private-defs)
839 (partition* (lambda (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)
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))))
857 (make-reference-graph vlist-null vlist-null #f))))
861 ;;; Unbound variable analysis.
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)
871 (refs toplevel-info-refs) ;; ((VARIABLE-NAME . LOCATION) ...)
872 (defs toplevel-info-defs)) ;; (VARIABLE-NAME ...)
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)
880 ((($ <const> _ (and (? symbol?) exp)) _)
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
890 (and (eq? env (resolve-module '(oop goops)))
891 (toplevel-define-arg args)))
894 (define unbound-variable-analysis
895 ;; Report possibly unbound variables in the given tree.
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)))
907 ((<toplevel-ref> name src)
910 (let ((src (or src (find pair? locs))))
911 (make-toplevel-info (vhash-consq name src refs)
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)))
926 ((<toplevel-set> name src)
928 (make-toplevel-info refs defs)
929 (let ((src (find pair? locs)))
930 (make-toplevel-info (vhash-consq name src refs)
932 ((<toplevel-define> name)
933 (make-toplevel-info (vhash-delq name refs)
934 (vhash-consq name #t defs)))
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
942 (make-toplevel-info (vhash-delq name refs)
943 (vhash-consq name #t defs))
944 (make-toplevel-info refs defs))))
946 (make-toplevel-info refs defs)))))
948 (lambda (x info env locs)
949 ;; Leaving X's scope.
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))))
960 (make-toplevel-info vlist-null vlist-null)))
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
971 (define-record-type <arity-info>
972 (make-arity-info toplevel-calls lexical-lambdas toplevel-lambdas)
974 (toplevel-calls toplevel-procedure-calls) ;; ((NAME . CALL) ...)
975 (lexical-lambdas lexical-lambdas) ;; ((GENSYM . DEFINITION) ...)
976 (toplevel-lambdas toplevel-lambdas)) ;; ((NAME . DEFINITION) ...)
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.
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)
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))
1000 (cons arg result)))))))
1002 (define (arities proc)
1003 ;; Return the arities of PROC, which can be either a tree-il or a
1006 (or (and (or (null? x) (pair? x))
1009 (cond ((program? proc)
1010 (values (procedure-name proc)
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))))
1017 (let ((arity (procedure-minimum-arity proc)))
1018 (values (procedure-name proc)
1019 (list (list (car arity) (cadr arity) (caddr arity)
1022 (let loop ((name #f)
1026 (values name (reverse arities))
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)))
1034 ((<lambda> meta body)
1035 (loop (assoc-ref meta 'name) body arities))
1037 (values #f #f))))))))
1039 (let ((args (call-args call))
1040 (src (tree-il-src call)))
1041 (call-with-values (lambda () (arities proc))
1042 (lambda (name arities)
1044 (find (lambda (arity)
1046 ((,req ,opt ,rest? ,kw ,aok?)
1047 (let ((args (if (pair? kw)
1048 (filter-keyword-args kw aok? args)
1051 (let ((count (length args)))
1054 (<= count (+ req opt)))))
1060 (warning 'arity-mismatch src
1061 (or name (with-output-to-string (lambda () (write proc))))
1065 (define arity-analysis
1066 ;; Report arity mismatches in the given tree.
1068 (lambda (x info env locs)
1071 (lambda (x info env locs)
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)))
1080 (make-arity-info toplevel-calls
1081 (vhash-consq lexical-name val
1084 ((<lexical-ref> gensym)
1086 (let ((val* (vhash-assq gensym lexical-lambdas)))
1088 (extend lexical-name (cdr val*) info)
1090 ((<toplevel-ref> name)
1092 (make-arity-info toplevel-calls
1093 (vhash-consq lexical-name val
1098 (let ((toplevel-calls (toplevel-procedure-calls info))
1099 (lexical-lambdas (lexical-lambdas info))
1100 (toplevel-lambdas (toplevel-lambdas info)))
1103 ((<toplevel-define> name exp)
1106 (make-arity-info toplevel-calls
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
1114 (vhash-consq (toplevel-define-name x)
1118 toplevel-lambdas))))
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))
1127 ((<call> proc args src)
1130 (validate-arity proc x #t)
1132 ((<toplevel-ref> name)
1133 (make-arity-info (vhash-consq name x toplevel-calls)
1136 ((<lexical-ref> gensym)
1137 (let ((proc (vhash-assq gensym lexical-lambdas)))
1139 (record-case (cdr proc)
1140 ((<toplevel-ref> name)
1141 ;; alias to toplevel
1142 (make-arity-info (vhash-consq name x toplevel-calls)
1146 (validate-arity (cdr proc) x #t)
1149 ;; If GENSYM wasn't found, it may be because it's an
1150 ;; argument of the procedure being compiled.
1155 (lambda (x info env locs)
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)
1168 (let ((toplevel-calls (toplevel-procedure-calls info))
1169 (lexical-lambdas (lexical-lambdas info))
1170 (toplevel-lambdas (toplevel-lambdas info)))
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))
1181 (lambda (result env)
1182 ;; Post-processing: check all top-level procedure calls that have been
1184 (let ((toplevel-calls (toplevel-procedure-calls result))
1185 (toplevel-lambdas (toplevel-lambdas result)))
1188 (let* ((name (car name+call))
1189 (call (cdr name+call))
1191 (or (and=> (vhash-assq name toplevel-lambdas) cdr)
1194 (module-ref env name)))))
1196 ;; handle toplevel aliases
1197 (if (toplevel-ref? proc)
1198 (let ((name (toplevel-ref-name proc)))
1201 (module-ref env name))))
1203 (if (or (lambda? proc*) (procedure? proc*))
1204 (validate-arity proc* call (lambda? proc*)))))
1207 (make-arity-info vlist-null vlist-null vlist-null)))
1211 ;;; `format' argument analysis.
1214 (define &syntax-error
1215 ;; The `throw' key for syntax errors.
1216 (gensym "format-string-syntax-error"))
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
1224 (define (drop-group chars end)
1225 ;; Drop characters from CHARS until "~END" is encountered.
1226 (let loop ((chars chars)
1229 (throw &syntax-error 'unterminated-iteration)
1231 (if (eq? (car chars) end)
1233 (loop (cdr chars) #f))
1234 (if (eq? (car chars) #\~)
1235 (loop (cdr chars) #t)
1236 (loop (cdr chars) #f))))))
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)))
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))))))
1248 (let loop ((chars (string->list fmt))
1257 (throw &syntax-error 'unterminated-conditional)
1258 (values min-count max-count))
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 #\, #\: #\@)
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
1277 (loop chars 'literal '() '()
1278 (let ((selector (previous-number params))
1279 (at? (memq #\@ params)))
1280 (lambda (chars conds)
1282 (let ((mins (map car conds))
1283 (maxs (map cdr conds))
1285 (< selector (length conds)))))
1286 (if (and (every number? mins)
1287 (every number? maxs))
1288 (loop chars 'literal '() conditions end-group
1291 (car (list-ref conds selector))
1295 (apply min mins)))))
1298 (cdr (list-ref conds selector))
1302 (apply max maxs))))))
1303 (values 'any 'any))))) ;; XXX: approximation
1307 (loop (cdr chars) 'literal '()
1308 (cons (cons min-count max-count) conditions)
1311 (throw &syntax-error 'unexpected-semicolon)))
1314 (end-group (cdr chars)
1315 (reverse (cons (cons min-count max-count)
1317 (throw &syntax-error 'unexpected-conditional-termination)))
1318 ((#\{) (if (memq #\@ params)
1319 (values min-count 'any)
1320 (loop (drop-group (cdr chars) #\})
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
1328 conditions end-group
1329 (+ (or (previous-number params) 1)
1331 (+ (or (previous-number params) 1)
1334 ;; We don't have enough info to determine the exact number
1335 ;; of args, but we could determine a lower bound (TODO).
1337 (else (loop (cdr chars) 'literal '()
1338 conditions end-group
1339 (+ 1 min-count) (+ 1 max-count)))))
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))))))
1350 (define (const-fmt x)
1351 ;; Return the literal format pattern for X, or #f.
1356 (or ($ <toplevel-ref> _ '_) ($ <module-ref> _ '_))
1357 (($ <const> _ (and (? string?) fmt))))
1358 ;; Gettexted literals, like `(_ "foo")'.
1362 (define format-analysis
1363 ;; Report arity mismatches in the given tree.
1365 (lambda (x _ env locs)
1369 (lambda (x _ env locs)
1371 (define (check-format-args args loc)
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)))
1381 (catch &syntax-error
1383 (let-values (((min max)
1384 (format-string-argument-count fmt)))
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)))))
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)))
1403 (warning 'format loc 'non-literal-format-string)))
1405 (warning 'format loc 'wrong-num-args (length args)))))
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).
1411 (define allowed-chars
1412 '(#\A #\S #\a #\s #\~ #\%))
1414 (define (format-chars fmt)
1415 (let loop ((chars (string->list fmt))
1421 (loop rest (cons opt result)))
1423 (loop rest result)))))
1426 ((port ($ <const> _ (? string? fmt)) _ ...)
1427 (let ((opts (format-chars fmt)))
1428 (or (every (cut memq <> allowed-chars) opts)
1430 (warning 'format loc 'simple-format fmt
1431 (find (negate (cut memq <> allowed-chars)) opts))
1433 ((port (($ <const> _ '_) fmt) args ...)
1434 (check-simple-format-args `(,port ,fmt ,args) loc))
1437 (define (resolve-toplevel name)
1439 (false-if-exception (module-ref env name))))
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))
1454 (and (check-simple-format-args args
1455 (or src (find pair? locs)))
1456 (check-format-args args (or src (find pair? locs)))))
1460 (lambda (x _ env locs)