Debian Codegraph @

gopls/internal/analysis/yield/yield.go

raw symbols SCIP
1 // Copyright 2026 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package yield
6
7 // TODO(adonovan): also check for inefficient code using this pattern:
8 //
9 // for x := range seq {
10 // if !yield(x) {
11 // break
12 // }
13 // }
14 //
15 // which should be entirely rewritten as
16 //
17 // seq(yield)
18 //
19 // to avoid unnecessary range desugaring and chains of dynamic calls.
20
21 import (
22 "cmp"
23 _ "embed"
24 "fmt"
25 "go/ast"
26 "go/constant"
27 "go/token"
28 "go/types"
29 "iter"
30 "math/bits"
31 "slices"
32
33 "golang.org/x/tools/go/analysis"
34 "golang.org/x/tools/go/analysis/passes/buildssa"
35 "golang.org/x/tools/go/analysis/passes/inspect"
36 "golang.org/x/tools/go/ast/inspector"
37 "golang.org/x/tools/go/ssa"
38 "golang.org/x/tools/gopls/internal/util/moremaps"
39 "golang.org/x/tools/gopls/internal/util/safetoken"
40 "golang.org/x/tools/internal/analysis/analyzerutil"
41 "golang.org/x/tools/internal/flow"
42 "golang.org/x/tools/internal/typesinternal"
43 )
44
45 // This analyzer uses a classical dataflow analysis to track the set
46 // of program points that may be reached after a specific yield() call
47 // must have returned false. It uses the [flow] framework to compute a
48 // fixed point over the SSA control-flow graph. The lattice value,
49 // [stateSet], represents a set of facts about the conditions under
50 // which the current program point _may_ be reached after yield
51 // returns false. The conditions are the known truth or falsehood of
52 // selected local Boolean SSA values, specifically constants, yield
53 // calls, negations, and phis. Values are merged when their conditions
54 // are equal, or when a stronger condition makes a weaker one
55 // redundant.
56 //
57 // (An earlier implementation used only sparse dataflow analysis but
58 // had a number of false positives due to loss of precision when
59 // control flow joins were materialized as boolean values.)
60 //
61 // Note that this is a "may" dataflow analysis: it reports when a
62 // yield function _may_ be called again without a positive intervening
63 // check, but it is possible that the check is beyond the ability of
64 // the representation to detect, perhaps involving sophisticated use
65 // of booleans, indirect state (not in SSA registers), or multiple
66 // flow paths some of which are infeasible.
67 //
68 // A "must" analysis (which would report when a second yield call can
69 // only be reached after failing the boolean check) would be too
70 // conservative. In particular, the most common mistake is to forget
71 // to check the boolean at all.
72 //
73 // The analysis ignores 'go' and 'defer' statements.
74
75 //go:embed doc.go
76 var doc string
77
78 var Analyzer = &analysis.Analyzer{
79 Name: "yield",
80 Doc: analyzerutil.MustExtractDoc(doc, "yield"),
81 Requires: []*analysis.Analyzer{inspect.Analyzer, buildssa.Analyzer},
82 Run: run,
83 URL: "https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/yield",
84 }
85
86 func run(pass *analysis.Pass) (any, error) {
87 // It is not strictly necessary that an iterator reference
88 // iter.Seq{,2}, but it is overwhelmingly the usual case.
89 // Skip any package that does not.
90 if !typesinternal.Imports(pass.Pkg, "iter") {
91 return nil, nil
92 }
93
94 // Find position of each syntactic yield call.
95 // We assume each yield function is named "yield".
96 var (
97 yieldCalls = make(map[token.Pos]*ast.CallExpr) // keyed by CallExpr.Lparen.
98 inspector = pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
99 )
100 for curCall := range inspector.Root().Preorder((*ast.CallExpr)(nil)) {
101 call := curCall.Node().(*ast.CallExpr)
102 if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "yield" {
103 if sig, ok := pass.TypesInfo.TypeOf(id).(*types.Signature); ok &&
104 sig.Params().Len() < 3 &&
105 sig.Results().Len() == 1 &&
106 types.Identical(sig.Results().At(0).Type(), types.Typ[types.Bool]) {
107 yieldCalls[call.Lparen] = call
108 }
109 }
110 }
111
112 // Common case: nothing to do.
113 if len(yieldCalls) == 0 {
114 return nil, nil
115 }
116
117 callSyntax := func(call *ssa.Call) *ast.CallExpr {
118 return yieldCalls[call.Pos()]
119 }
120
121 // Study the control flow using SSA.
122 buildssa := pass.ResultOf[buildssa.Analyzer].(*buildssa.SSA)
123 for _, fn := range buildssa.SrcFuncs {
124 run1(pass, callSyntax, fn)
125 }
126
127 return nil, nil
128 }
129
130 func run1(pass *analysis.Pass, callSyntax func(call *ssa.Call) *ast.CallExpr, fn *ssa.Function) {
131 // Find SSA instruction of each yield call.
132 ssaYieldCalls := make(map[*ssa.Call]bool)
133 for _, b := range fn.Blocks {
134 for _, instr := range b.Instrs {
135 if call, ok := instr.(*ssa.Call); ok && callSyntax(call) != nil {
136 ssaYieldCalls[call] = true
137 }
138 }
139 }
140 if len(ssaYieldCalls) == 0 {
141 return
142 }
143 isYieldCall := func(v ssa.Value) bool {
144 call, ok := v.(*ssa.Call)
145 return ok && ssaYieldCalls[call]
146 }
147
148 numb := make(numbering)
149
150 // Compute the dataflow solution.
151 initial := map[int]stateSet{0: nil} // on entry, no states of interest
152 result := flow.Forward[lattice](fnGraph{fn}, initial, func(fromID, toID int, in stateSet) stateSet {
153 // The transfer function computes the effect on the abstract
154 // state of flow along the CFG edge from --> to,
155 // including the effects from the 'from' block itself.
156 // and the prefix of phis in the 'to' block.
157 //
158 // In effect, the block's state in the framework
159 // corresponds to the point after its prefix of phis.
160 var (
161 from = fn.Blocks[fromID]
162 to = fn.Blocks[toID]
163 out = in // (do not mutate in)
164 )
165
166 for _, instr := range from.Instrs {
167 switch instr := instr.(type) {
168 case *ssa.Call:
169 if isYieldCall(instr) {
170 out = out.yieldCall(numb, instr)
171 }
172
173 case *ssa.UnOp:
174 if instr.Op == token.NOT {
175 out = out.not(numb, instr)
176 }
177
178 case *ssa.If:
179 out = out.if_(numb, instr.Cond, to == from.Succs[0])
180 }
181 }
182
183 // Process phis in 'to' block.
184 if i := slices.Index(to.Preds, from); i >= 0 {
185 for _, instr := range to.Instrs {
186 if phi, ok := instr.(*ssa.Phi); ok {
187 out = out.phi(numb, phi, phi.Edges[i])
188 }
189 }
190 }
191
192 // Opt: avoid renormalizing 'in' if unchanged.
193 if len(out) > 0 && !sameSlice(out, in) {
194 out = normalize(out)
195 }
196
197 return out
198 })
199
200 // Gather the problematic calls.
201 type problem struct{ first, later *ssa.Call }
202 var problems []problem
203 for i, b := range fn.Blocks {
204 in := result.In(i)
205 out := slices.Clone(in)
206 for _, instr := range b.Instrs {
207 if call, ok := instr.(*ssa.Call); ok && isYieldCall(call) {
208 for _, s := range out {
209 problems = append(problems, problem{first: s.yield, later: call})
210 }
211 // Apply intra-block transfer function,
212 // in case there are yield calls in sequence.
213 out = out.yieldCall(numb, call)
214 }
215 }
216 }
217
218 // Sort, since source order differs from block order,
219 // and for each 'first', we want the earliest 'later' in the source.
220 slices.SortFunc(problems, func(x, y problem) int {
221 if d := cmp.Compare(x.first.Pos(), y.first.Pos()); d != 0 {
222 return d
223 }
224 return cmp.Compare(x.later.Pos(), y.later.Pos())
225 })
226
227 // Report a diagnostic for each problematic 'first' call.
228 for _, p := range problems {
229 if !moremaps.Delete(ssaYieldCalls, p.first) {
230 continue // already reported
231 }
232
233 var where string
234 var related []analysis.RelatedInformation
235 if p.later != p.first {
236 otherLine := safetoken.StartPosition(pass.Fset, p.later.Pos()).Line
237 where = fmt.Sprintf("(on L%d) ", otherLine)
238 laterCall := callSyntax(p.later)
239 related = []analysis.RelatedInformation{{
240 Pos: laterCall.Pos(),
241 End: laterCall.End(),
242 Message: "other call here",
243 }}
244 }
245
246 firstCall := callSyntax(p.first)
247 pass.Report(analysis.Diagnostic{
248 Pos: firstCall.Pos(),
249 End: firstCall.End(),
250 Message: fmt.Sprintf("yield may be called again %safter returning false", where),
251 Related: related,
252 })
253 }
254 }
255
256 // A numbering maps SSA values to small nonnegative integers.
257 type numbering map[ssa.Value]int
258
259 // number returns the sequence of number for value v.
260 func (n numbering) number(v ssa.Value) int {
261 i, ok := n[v]
262 if !ok {
263 i = len(n)
264 n[v] = i
265 }
266 return i
267 }
268
269 // -- lattice --
270
271 type lattice struct{}
272
273 var _ flow.Semilattice[stateSet] = lattice{}
274
275 // Ident returns the identity element of the lattice, an empty stateSet.
276 func (lattice) Ident() stateSet { return nil }
277
278 // Equals reports whether two stateSets are equivalent.
279 func (lattice) Equals(a, b stateSet) bool {
280 return slices.EqualFunc(a, b, state.equal)
281 }
282
283 // Merge combines two stateSets into a minimal unified set, dropping subsets.
284 // The result is normalized even if the arguments are not.
285 func (lattice) Merge(a, b stateSet) stateSet {
286 return normalize(slices.Concat(a, b))
287 }
288
289 // normalize puts the stateSet in normal form, destructively.
290 func normalize(ss stateSet) stateSet {
291 // We define a total order of states in the set so
292 // that set equality is slice equality.
293 // States are ordered by four keys in order:
294 // - yield call (since this is cheaper than mask.len);
295 // - mask.len (number of conditions), smallest first,
296 // so that the later merging step can eliminate
297 // narrow conditions for a given yield call in
298 // favor of broader ones;
299 // - mask bit pattern
300 // - senses bit pattern
301 // The latter two are essentially arbitrary ways
302 // to ensure a total order.
303 slices.SortFunc(ss, func(x, y state) int {
304 if x.yield != y.yield {
305 return cmp.Compare(x.yield.Pos(), y.yield.Pos()) // must be non-zero
306 }
307 if d := cmp.Compare(x.mask.len(), y.mask.len()); d != 0 {
308 return d
309 }
310 if d := x.mask.cmp(&y.mask); d != 0 {
311 return d
312 }
313 // We rely on senses having no stray (unmasked) bits.
314 if d := x.senses.cmp(&y.senses); d != 0 {
315 return d
316 }
317 return 0
318 })
319
320 // Discard empty states, or states that are stricter
321 // than (and thus redundant wrt) ones we already have.
322 //
323 // This is quadratic in the number of analytically distinct
324 // control states, which is related to the number of yield
325 // calls, the number of control paths that differ in their
326 // treatement of yield results, and the number of phis.
327 // But n is typically tiny.
328 out := ss[:0]
329 for _, s := range ss {
330 if !s.mask.empty() && !slices.ContainsFunc(out, s.stricter) {
331 out = append(out, s)
332 }
333 }
334 return out
335 }
336
337 // -- stateSet transfer (pure) functions --
338
339 // stateSet is the dataflow fact associated with each block edge.
340 //
341 // Conceptually it is a map from a specific yield call to an
342 // "antichain", a set of partially ordered states such that none
343 // subsumes another (similar to DNF). Though specialized
344 // representations exist (e.g. BDDs), a slice is fine in practice.
345 //
346 // The states in the set are totally ordered (somewhat arbitrarily)
347 // by [normalize] so that state set equality is slice equality.
348 type stateSet []state
349
350 // yieldCall defines the transfer function for a yield call.
351 func (in stateSet) yieldCall(n numbering, call *ssa.Call) (out stateSet) {
352 callnum := n.number(call)
353
354 s := state{yield: call}
355 s.mask.set(callnum, true)
356 s.senses.set(callnum, false) // analysis presumes each yield call returns false
357 return append(slices.Clip(in), s)
358 }
359
360 // not defines the transfer function for a negation.
361 func (in stateSet) not(n numbering, not *ssa.UnOp) (out stateSet) {
362 xnum := n.number(not.X)
363 notnum := n.number(not)
364 for _, s := range in {
365 if s.mask.get(xnum) {
366 s = s.update(notnum, true, !s.senses.get(xnum))
367 } else {
368 s = s.update(notnum, false, false) // clear stale fact
369 }
370 out = append(out, s)
371 }
372 return out
373 }
374
375 // phi defines the transfer function for a phi node for the incoming edge value val.
376 func (in stateSet) phi(n numbering, phi *ssa.Phi, val ssa.Value) (out stateSet) {
377 phinum := n.number(phi)
378 if c, ok := val.(*ssa.Const); ok && c.Value != nil && c.Value.Kind() == constant.Bool {
379 sense := constant.BoolVal(c.Value)
380 // phi's value is a constant (sense).
381 for _, s := range in {
382 s = s.update(phinum, true, sense)
383 out = append(out, s)
384 }
385 } else {
386 // phi's value comes from predecessor, val.
387 valnum := n.number(val)
388 for _, s := range in {
389 if s.mask.get(valnum) {
390 s = s.update(phinum, true, s.senses.get(valnum))
391 } else {
392 s = s.update(phinum, false, false) // clear stale fact
393 }
394 out = append(out, s)
395 }
396 }
397 return out
398 }
399
400 // if_ defines the transfer function for a conditional branch.
401 func (in stateSet) if_(n numbering, cond ssa.Value, sense bool) (out stateSet) {
402 // Strip off any negations to get to the root fact.
403 for {
404 unop, ok := cond.(*ssa.UnOp)
405 if !(ok && unop.Op == token.NOT) {
406 break
407 }
408 sense = !sense
409 cond = unop.X
410 }
411
412 condnum := n.number(cond)
413 for _, s := range in {
414 if s.mask.get(condnum) && s.senses.get(condnum) != sense {
415 // Infeasible edge; discard this state.
416 continue
417 }
418 out = append(out, s)
419 }
420 return out
421 }
422
423 // -- state --
424
425 // state represents an execution path defined by a set of boolean conditions.
426 // It tracks the original yield call that could be violated if this state's conditions are met.
427 // Conceptually, the conditions are a mapping from ssa.Value to boolean sense.
428 // Concretely, SSA values are sequentially numbered (see [numbering]) as they are encountered,
429 // and these numbers identify values.
430 //
431 // mask is the set of map keys; senses is the boolean sense of each value.
432 // It is an invariant that senses is a subset of mask.
433 type state struct {
434 yield *ssa.Call // yield call that would be violated if the conditions are not met
435 mask bitset // tracks which values have conditions
436 senses bitset // tracks the boolean condition (sense) of each value
437 }
438
439 // equal reports whether x and y are the same state.
440 func (x state) equal(y state) bool {
441 return x.yield == y.yield &&
442 x.mask.equal(&y.mask) &&
443 x.senses.equalMasked(&y.senses, &x.mask)
444 }
445
446 // stricter reports whether x is a stricter (more specific) state than y.
447 func (x state) stricter(y state) bool {
448 return x.yield == y.yield &&
449 y.mask.subsetOf(&x.mask) &&
450 y.senses.equalMasked(&x.senses, &y.mask)
451 }
452
453 // update returns a copy of the state with the specified value's condition updated.
454 func (s state) update(num int, mask, sense bool) state {
455 s.mask = s.mask.clone()
456 s.senses = s.senses.clone()
457 s.mask.set(num, mask)
458 s.senses.set(num, sense)
459 return s
460 }
461
462 // -- SSA CFG as graph.Graph --
463
464 // fnGraph adapts an [ssa.Function] to the [graph.Graph] interface
465 // required by the flow analysis framework.
466 // Nodes are labelled by their block indices and connected by the
467 // successor relation.
468 //
469 // TODO(adonovan): move to ssa package?
470 type fnGraph struct {
471 fn *ssa.Function
472 }
473
474 // Nodes returns an iterator over the basic block indices.
475 func (g fnGraph) Nodes() iter.Seq[int] {
476 return func(yield func(int) bool) {
477 for i := range g.fn.Blocks {
478 if !yield(i) {
479 return
480 }
481 }
482 }
483 }
484
485 // NumNodes returns the number of basic blocks in the graph.
486 func (g fnGraph) NumNodes() int { return len(g.fn.Blocks) }
487
488 // Out returns an iterator over the successor block indices of a given node.
489 func (g fnGraph) Out(node int) iter.Seq[int] {
490 return func(yield func(int) bool) {
491 for _, succ := range g.fn.Blocks[node].Succs {
492 if !yield(succ.Index) {
493 return
494 }
495 }
496 }
497 }
498
499 // -- bitset --
500
501 // bitset is a set of non-negative integers.
502 // It uses space proportional to its largest element.
503 //
504 // The zero value is a ready-to-use empty set.
505 // Bitsets, like slices, have hybrid value/reference semantics.
506 // Do not mutate copies; use [bitset.clone] before [bitset.set].
507 //
508 // bitsets are comparable (see [bitset.equal]) and totally ordered (see [bitset.cmp]).
509 type bitset struct {
510 limbs []uint64 // bit vector; last limb is nonzero
511 }
512
513 // empty reports whether the set is empty.
514 func (b *bitset) empty() bool {
515 return len(b.limbs) == 0
516 }
517
518 // set inserts or removes i from the set.
519 func (b *bitset) set(i int, sense bool) {
520 // Grow if needed.
521 idx := int(i / 64)
522 if idx >= len(b.limbs) {
523 if !sense {
524 return // clearing nonexistent bit
525 }
526 b.limbs = slices.Grow(b.limbs, idx-len(b.limbs)+1)[:idx+1]
527 }
528
529 bit := uint64(1) << (i % 64)
530 if sense {
531 // set
532 b.limbs[idx] |= bit
533 } else {
534 // clear
535 b.limbs[idx] &^= bit
536
537 // Remove any trailing zero limbs.
538 if b.limbs[idx] == 0 {
539 n := len(b.limbs)
540 for n > 0 && b.limbs[n-1] == 0 {
541 n--
542 }
543 b.limbs = b.limbs[:n]
544 }
545 }
546 }
547
548 func (b *bitset) limb(i int) uint64 {
549 if i < len(b.limbs) {
550 return b.limbs[i]
551 }
552 return 0
553 }
554
555 // get reports whether the set contains i.
556 func (b *bitset) get(i int) bool {
557 return b.limb(i/64)&(1<<(i%64)) != 0
558 }
559
560 // clone returns a copy of the bitset.
561 func (b *bitset) clone() bitset {
562 return bitset{limbs: slices.Clone(b.limbs)}
563 }
564
565 // equal reports whether two sets contain the same elements.
566 func (b *bitset) equal(other *bitset) bool {
567 return slices.Equal(b.limbs, other.limbs)
568 }
569
570 // equalMasked reports whether b&mask equals other&mask.
571 func (b *bitset) equalMasked(other, mask *bitset) bool {
572 // Above n words, both operands when masked are effectively zero.
573 n := min(len(mask.limbs), max(len(b.limbs), len(other.limbs)))
574 for i, m := range mask.limbs[:n] {
575 if b.limb(i)&m != other.limb(i)&m {
576 return false
577 }
578 }
579 return true
580 }
581
582 // cmp returns the signum of the comparison b against other.
583 func (b *bitset) cmp(other *bitset) int {
584 if d := cmp.Compare(len(b.limbs), len(other.limbs)); d != 0 {
585 return d
586 }
587 for i := len(b.limbs) - 1; i >= 0; i-- {
588 if d := cmp.Compare(b.limbs[i], other.limbs[i]); d != 0 {
589 return d
590 }
591 }
592 return 0
593 }
594
595 // subsetOf reports whether other contains all of b's elements.
596 func (b *bitset) subsetOf(other *bitset) bool {
597 for i, w1 := range b.limbs {
598 if w1&other.limb(i) != w1 {
599 return false
600 }
601 }
602 return true
603 }
604
605 // len returns the number of elements of the set.
606 func (b *bitset) len() int {
607 var n int
608 for _, v := range b.limbs {
609 n += bits.OnesCount64(v)
610 }
611 return n
612 }
613
614 // sameSlice reports whether the corresponding elements
615 // of two slices are identical variables.
616 func sameSlice[T any](x, y []T) bool {
617 return len(x) == len(y) && (len(x) == 0 || &x[0] == &y[0])
618 }