| 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 excfg constructs control-flow graphs of statements and expressions in |
| 6 | // a Go function, including intra-expression control flow. |
| 7 | package excfg |
| 8 | |
| 9 | import ( |
| 10 | "go/ast" |
| 11 | "go/token" |
| 12 | "iter" |
| 13 | "slices" |
| 14 | "sync" |
| 15 | |
| 16 | "golang.org/x/tools/go/cfg" |
| 17 | "golang.org/x/tools/internal/graph" |
| 18 | ) |
| 19 | |
| 20 | // CFG is a control flow graph over [ast.Node]s, including control flow within |
| 21 | // expressions. Beyond the statement-level control flow represented by |
| 22 | // [cfg.CFG], this graph contains a separate block for every statement, every |
| 23 | // call (even within an expression), and for each branch of short-circuiting |
| 24 | // operators. |
| 25 | // |
| 26 | // AST nodes that purely affect control flow may not appear in any block. For |
| 27 | // example, in "if x && y { ... }", neither the "if" statement nor the "&&" node |
| 28 | // will appear, as both are translated into pure control flow. |
| 29 | // |
| 30 | // CFG implements graph.Graph[int] and is a compact graph. |
| 31 | type CFG struct { |
| 32 | Blocks []*Block |
| 33 | |
| 34 | Fset *token.FileSet |
| 35 | |
| 36 | subexprs struct { |
| 37 | once sync.Once |
| 38 | m [][]*Block // Indexed by ExBlock.Index |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // NumNodes returns the number of blocks in c. |
| 43 | func (c *CFG) NumNodes() int { |
| 44 | return len(c.Blocks) |
| 45 | } |
| 46 | |
| 47 | // Nodes yields the indexes of all blocks in c. This is simply the sequence [0, NumNodes()). |
| 48 | func (c *CFG) Nodes() iter.Seq[int] { |
| 49 | return func(yield func(int) bool) { |
| 50 | for i := range c.Blocks { |
| 51 | if !yield(i) { |
| 52 | break |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // Out yields the indexes of the successors of block. |
| 59 | func (c *CFG) Out(block int) iter.Seq[int] { |
| 60 | return func(yield func(int) bool) { |
| 61 | for _, succ := range c.Blocks[block].Succs { |
| 62 | if !yield(int(succ.Index)) { |
| 63 | break |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | func (c *CFG) IsCompact() bool { |
| 70 | return true |
| 71 | } |
| 72 | |
| 73 | var _ graph.Graph[int] = (*CFG)(nil) |
| 74 | |
| 75 | type Block struct { |
| 76 | Kind ExKind |
| 77 | |
| 78 | // Node is a statement, expression, or ast.ValueSpec. |
| 79 | // |
| 80 | // An expression may contain sub-expressions computed in preceding blocks of |
| 81 | // type ExKindBool and ExKindCall. Each sub-expression block is used by |
| 82 | // exactly one other block, though that block may not be an immediate |
| 83 | // successor. All sub-expressions must be used at the end of an ExKindStmt |
| 84 | // or ExKindIf block. A sub-expression block will have a lower Index than |
| 85 | // the block that consumes the sub-expression. |
| 86 | Node ast.Node |
| 87 | |
| 88 | // Succs is a list of successor nodes. The length and interpretation of this |
| 89 | // depends on Kind. |
| 90 | Succs []*Block |
| 91 | |
| 92 | // Use is set to the block that consumes the value of this sub-expression |
| 93 | // block. Only set for ExKindSubExpr and ExKindBool. |
| 94 | Use *Block |
| 95 | |
| 96 | // Index is the index of this block in ExCFG.Blocks. |
| 97 | Index int32 |
| 98 | |
| 99 | // CFGBlock is the index of the cfg.Block this expression block was derived |
| 100 | // from. |
| 101 | CFGBlock int32 |
| 102 | |
| 103 | succs [2]*Block // Storage for Succs |
| 104 | } |
| 105 | |
| 106 | type ExKind int8 |
| 107 | |
| 108 | //go:generate stringer -type ExKind . |
| 109 | |
| 110 | const ( |
| 111 | ExKindInvalid ExKind = iota |
| 112 | |
| 113 | // An ExKindStmt ExBlock is a statement, expression, or ValueSpec with no |
| 114 | // value. It has 0 or 1 successors. It consumes any preceding sub-expression |
| 115 | // values. |
| 116 | ExKindStmt |
| 117 | |
| 118 | // An ExKindIf ExBlock is a boolean-typed expression that branches to one of |
| 119 | // two successors. Like ExKindStmt, it consumes any preceding |
| 120 | // sub-expressions. Successor 0 is the true branch and successor 1 is the |
| 121 | // false branch. |
| 122 | ExKindIf |
| 123 | |
| 124 | // An ExKindSubExpr ExBlock is a sub-expression whose value is used as part |
| 125 | // of another ExBlock. It has exactly one successor. |
| 126 | ExKindSubExpr |
| 127 | |
| 128 | // An ExKindBool ExBlock is a sub-expression whose value is used as part of |
| 129 | // another ExBlock, like ExKindSubExpr, but it branches to two successors |
| 130 | // based on the value of the sub-expression. Successor 0 is the true branch |
| 131 | // and successor 1 is the false branch. |
| 132 | ExKindBool |
| 133 | ) |
| 134 | |
| 135 | func New(cfg *cfg.CFG, fset *token.FileSet) *CFG { |
| 136 | eb := builder{ |
| 137 | entry: make([]*Block, len(cfg.Blocks)), |
| 138 | } |
| 139 | |
| 140 | // Allocate "placeholder" ExBlocks for each cfg.Block. We often need to |
| 141 | // record a successor that hasn't yet been converted to an ExBlock, so we |
| 142 | // use these placeholders for this and resolve them at the end. |
| 143 | placeholders := make([]Block, len(cfg.Blocks)) |
| 144 | for i := range placeholders { |
| 145 | placeholders[i].CFGBlock = int32(i) |
| 146 | placeholders[i].Index = -1 // Indicates a placeholder |
| 147 | eb.entry[i] = &placeholders[i] |
| 148 | } |
| 149 | |
| 150 | // Convert each cfg.Block into one or more ExBlocks. |
| 151 | // |
| 152 | // We do this backwards so that successor blocks are usually already visited |
| 153 | // and we can link them up eagerly. |
| 154 | for _, b := range slices.Backward(cfg.Blocks) { |
| 155 | if b.Live { |
| 156 | eb.visitBlock(b) |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | // Put blocks in forward order. |
| 161 | eb.assertReverse() |
| 162 | slices.Reverse(eb.blocks) |
| 163 | for i, b := range eb.blocks { |
| 164 | b.Index = int32(i) |
| 165 | } |
| 166 | |
| 167 | // Resolve placeholder blocks. |
| 168 | for _, b := range eb.blocks { |
| 169 | for i, succ := range b.Succs { |
| 170 | if succ.Index == -1 { |
| 171 | b.Succs[i] = eb.entry[succ.CFGBlock] |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | return &CFG{Blocks: eb.blocks, Fset: fset} |
| 177 | } |
| 178 | |
| 179 | // Subexprs returns the preceding sub-expression blocks consumed by b. This is |
| 180 | // the inverse of [Block.Use]. The slice is in ast.Inspect order for b.Node. |
| 181 | func (g *CFG) Subexprs(b *Block) []*Block { |
| 182 | g.subexprs.once.Do(func() { |
| 183 | // Count how many back-references we need. |
| 184 | n := make([]int, 1+len(g.Blocks)) |
| 185 | for _, b := range g.Blocks { |
| 186 | if b.Use != nil { |
| 187 | n[1+b.Use.Index]++ |
| 188 | } |
| 189 | } |
| 190 | // Convert n from a count to an index. |
| 191 | for i := 1; i < len(n); i++ { |
| 192 | n[i] += n[i-1] |
| 193 | } |
| 194 | // Allocate a single block and slice it up. |
| 195 | allSubexprs := make([]*Block, n[len(n)-1]) |
| 196 | g.subexprs.m = make([][]*Block, len(g.Blocks)) |
| 197 | for i := range g.subexprs.m { |
| 198 | g.subexprs.m[i] = allSubexprs[n[i]:n[i+1]] |
| 199 | } |
| 200 | // Collect back-references. |
| 201 | for _, b := range g.Blocks { |
| 202 | if b.Use != nil { |
| 203 | allSubexprs[n[b.Use.Index]] = b |
| 204 | n[b.Use.Index]++ |
| 205 | } |
| 206 | } |
| 207 | }) |
| 208 | return g.subexprs.m[b.Index] |
| 209 | } |
| 210 | |
| 211 | type builder struct { |
| 212 | blocks []*Block |
| 213 | |
| 214 | // Map from cfg.Block.Index to the entry ExBlock. Initially, this is |
| 215 | // populated with placeholder blocks that can be used in ExBlock.Succs. Once |
| 216 | // all blocks have been visited, they should all be replaced with actual |
| 217 | // ExBlocks, and NewExCFG will replace references to the placeholders. |
| 218 | entry []*Block |
| 219 | |
| 220 | // cfgBlock is the cfg.Block we're currently translating. |
| 221 | cfgBlock *cfg.Block |
| 222 | |
| 223 | // For the most part, we build the block list in reverse so that successors |
| 224 | // are almost always already available. However, at the bottom of the |
| 225 | // recursive process we use ast.Inspect, we forces us to build it in forward |
| 226 | // order. Hence, we track whether we're in "reverse" or "forward" mode and |
| 227 | // when we exit forward mode, we reverse the forward part of the block list. |
| 228 | // Finally, at the very end of traversal, we reverse the entire block list |
| 229 | // into forward order. We never enter reverse mode from forward mode, so all |
| 230 | // remains linear time with simple tracking. |
| 231 | |
| 232 | // forwardStart is in the index into blocks of the start of a forward region. |
| 233 | forwardStart int |
| 234 | // forwardDepth is the recursive depth of forward regions. |
| 235 | forwardDepth int |
| 236 | } |
| 237 | |
| 238 | func (eb *builder) assertReverse() { |
| 239 | if eb.forwardDepth != 0 { |
| 240 | panic("unexpected reverse operation in forward region") |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | func (eb *builder) enterForward() { |
| 245 | if eb.forwardDepth == 0 { |
| 246 | eb.forwardStart = len(eb.blocks) |
| 247 | } |
| 248 | eb.forwardDepth++ |
| 249 | } |
| 250 | |
| 251 | func (eb *builder) exitForward() { |
| 252 | eb.forwardDepth-- |
| 253 | if eb.forwardDepth == 0 { |
| 254 | // Put forward region into reverse order. |
| 255 | slices.Reverse(eb.blocks[eb.forwardStart:]) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | func (eb *builder) visitBlock(cb *cfg.Block) { |
| 260 | eb.cfgBlock = cb |
| 261 | |
| 262 | var next *Block |
| 263 | if len(cb.Succs) > 0 { |
| 264 | next = eb.entry[cb.Succs[0].Index] |
| 265 | } |
| 266 | isIf := len(cb.Succs) == 2 |
| 267 | for _, node := range slices.Backward(cb.Nodes) { |
| 268 | eb.assertReverse() |
| 269 | |
| 270 | if isIf { |
| 271 | next = eb.visitCond(node.(ast.Expr), next, eb.entry[cb.Succs[1].Index]) |
| 272 | isIf = false |
| 273 | } else { |
| 274 | nodeEntry, nodeExit := eb.visitNode(ExKindStmt, node) |
| 275 | if next != nil { |
| 276 | nodeExit.Succs = nodeExit.succs[:1] |
| 277 | nodeExit.Succs[0] = next |
| 278 | } |
| 279 | next = nodeEntry |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | eb.entry[cb.Index] = next |
| 284 | } |
| 285 | |
| 286 | // visitNode traverses a statement or expression node. It creates a sub-graph of |
| 287 | // one or more blocks to compute root and returns the entry and exit blocks of |
| 288 | // that subgraph. The type of the exit block is set to kind. The caller must set |
| 289 | // the successors of the exit block. |
| 290 | func (eb *builder) visitNode(kind ExKind, root ast.Node) (entry, exit *Block) { |
| 291 | eb.enterForward() |
| 292 | defer eb.exitForward() |
| 293 | |
| 294 | entryI := len(eb.blocks) |
| 295 | block := &Block{Kind: kind, Node: root, CFGBlock: eb.cfgBlock.Index} |
| 296 | |
| 297 | preds := make([]**Block, 0, 3) |
| 298 | // link connects a subgraph of blocks by connecting the previous exit block |
| 299 | // to entry and recording the new exit block's successors that should be set |
| 300 | // to the next entry block. This is necessary because we're processing |
| 301 | // nodes in forward order here, so successors must be back-patched. |
| 302 | link := func(entry *Block, exitSuccs ...**Block) { |
| 303 | for _, pred := range preds { |
| 304 | *pred = entry |
| 305 | } |
| 306 | preds = append(preds[:0], exitSuccs...) |
| 307 | } |
| 308 | |
| 309 | // Traverse root in pre-order, stopping at any sub-expressions that affect |
| 310 | // control flow to create blocks for those sub-expressions. |
| 311 | ast.Inspect(root, func(n ast.Node) bool { |
| 312 | switch n := n.(type) { |
| 313 | case *ast.FuncLit: |
| 314 | // The body of the function literal is not part of the control flow. |
| 315 | return false |
| 316 | |
| 317 | case *ast.BinaryExpr: |
| 318 | switch n.Op { |
| 319 | case token.LAND: |
| 320 | xin, xout := eb.visitNode(ExKindBool, n.X) |
| 321 | yin, yout := eb.visitNode(ExKindSubExpr, n.Y) |
| 322 | |
| 323 | xout.Use, yout.Use = block, block |
| 324 | |
| 325 | xout.Succs = xout.succs[:2] |
| 326 | xout.Succs[0] = yin // If true, evaluate Y. |
| 327 | |
| 328 | yout.Succs = yout.succs[:1] |
| 329 | |
| 330 | // x && y will produce: |
| 331 | // |
| 332 | // x |
| 333 | // / \ |
| 334 | // y \ |
| 335 | // \ / |
| 336 | // (x && y) |
| 337 | link(xin, &xout.succs[1], &yout.succs[0]) |
| 338 | |
| 339 | return false |
| 340 | |
| 341 | case token.LOR: |
| 342 | xin, xout := eb.visitNode(ExKindBool, n.X) |
| 343 | yin, yout := eb.visitNode(ExKindSubExpr, n.Y) |
| 344 | |
| 345 | xout.Use, yout.Use = block, block |
| 346 | |
| 347 | xout.Succs = xout.succs[:2] |
| 348 | xout.Succs[1] = yin // If false, evaluate Y. |
| 349 | |
| 350 | yout.Succs = yout.succs[:1] |
| 351 | |
| 352 | link(xin, &xout.succs[0], &yout.succs[0]) |
| 353 | |
| 354 | return false |
| 355 | } |
| 356 | |
| 357 | case *ast.CallExpr: |
| 358 | // f() + g() + h() has an AST like |
| 359 | // |
| 360 | // + |
| 361 | // / \ |
| 362 | // f() \ |
| 363 | // + |
| 364 | // / \ |
| 365 | // g() h() |
| 366 | // |
| 367 | // Because of the traversal order, we'll produce a linkage like |
| 368 | // |
| 369 | // f() => g() => h() => root + |
| 370 | if n != root { |
| 371 | in, out := eb.visitNode(ExKindSubExpr, n) |
| 372 | out.Use = block |
| 373 | out.Succs = out.succs[:1] |
| 374 | link(in, &out.succs[0]) |
| 375 | return false |
| 376 | } |
| 377 | } |
| 378 | return true |
| 379 | }) |
| 380 | |
| 381 | link(block) |
| 382 | eb.blocks = append(eb.blocks, block) |
| 383 | return eb.blocks[entryI], block |
| 384 | } |
| 385 | |
| 386 | func (eb *builder) visitCond(n ast.Expr, tSucc, fSucc *Block) (entry *Block) { |
| 387 | eb.assertReverse() |
| 388 | |
| 389 | switch n := n.(type) { |
| 390 | case *ast.ParenExpr: |
| 391 | return eb.visitCond(n.X, tSucc, fSucc) |
| 392 | |
| 393 | case *ast.UnaryExpr: |
| 394 | if n.Op == token.NOT { |
| 395 | return eb.visitCond(n.X, fSucc, tSucc) |
| 396 | } |
| 397 | |
| 398 | case *ast.BinaryExpr: |
| 399 | switch n.Op { |
| 400 | case token.LAND: |
| 401 | y := eb.visitCond(n.Y, tSucc, fSucc) |
| 402 | x := eb.visitCond(n.X, y, fSucc) |
| 403 | return x |
| 404 | case token.LOR: |
| 405 | y := eb.visitCond(n.Y, tSucc, fSucc) |
| 406 | x := eb.visitCond(n.X, tSucc, y) |
| 407 | return x |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | entry, exit := eb.visitNode(ExKindIf, n) |
| 412 | exit.Succs = exit.succs[:2] |
| 413 | exit.Succs[0] = tSucc |
| 414 | exit.Succs[1] = fSucc |
| 415 | return entry |
| 416 | } |