edgeaffine.go raw

   1  package loader
   2  
   3  import (
   4  	"fmt"
   5  	"go/ast"
   6  	"go/token"
   7  	"go/types"
   8  	"sort"
   9  )
  10  
  11  // checkEdgeAffinity enforces the declared pair's affineness (docs/memory-model.md
  12  // section 4, D19 rule 4): an Edge owns one pair of rings and one pair of
  13  // handles, so it has one owner and moves ONCE. It may be
  14  //
  15  //   - passed to a spawn (the move),
  16  //   - returned from a function (the move out of the frame),
  17  //   - read through its fields (e.Send, e.Recv),
  18  //   - addressed by the declaration's __edgealloc call.
  19  //
  20  // Everything else is a copy: `e2 := e1`, `f(e1)` for a non-spawn f, storing it
  21  // in a struct, slice or channel. Two spawns of one Edge are the same fault in
  22  // the other direction: the pair's handles would have two children.
  23  //
  24  // It runs after the final type-check, on the lowered AST (the declaration is
  25  // already `var p Edge[...]; ... __edgealloc(&p, &c, ...)`), so the vars that
  26  // hold a pair are exactly the Edge-typed definitions.
  27  func checkEdgeAffinity(files []*ast.File, info *types.Info, fset *token.FileSet) []error {
  28  	edges := map[types.Object]bool{}
  29  	for _, obj := range info.Defs {
  30  		if obj == nil {
  31  			continue
  32  		}
  33  		if !isEdgeObjectType(obj.Type()) {
  34  			continue
  35  		}
  36  		if v, ok := obj.(*types.Var); ok && v.IsField() {
  37  			continue
  38  		}
  39  		edges[obj] = true
  40  	}
  41  	if len(edges) == 0 {
  42  		return nil
  43  	}
  44  
  45  	// Parent links let the use-site judge reach the enclosing expression
  46  	// without threading context through every walk.
  47  	parents := map[ast.Node]ast.Node{}
  48  	for _, f := range files {
  49  		var stack []ast.Node
  50  		ast.Inspect(f, func(n ast.Node) bool {
  51  			if n == nil {
  52  				stack = stack[:len(stack)-1]
  53  				return true
  54  			}
  55  			if len(stack) > 0 {
  56  				parents[n] = stack[len(stack)-1]
  57  			}
  58  			stack = append(stack, n)
  59  			return true
  60  		})
  61  	}
  62  
  63  	moved := map[types.Object]ast.Node{}
  64  	var errs []error
  65  	fail := func(pos token.Pos, format string, args ...any) {
  66  		errs = append(errs, fmt.Errorf("%s: %s", fset.Position(pos), fmt.Sprintf(format, args...)))
  67  	}
  68  
  69  	for id, obj := range info.Uses {
  70  		if !edges[obj] {
  71  			continue
  72  		}
  73  		switch p := parents[id].(type) {
  74  		case *ast.SelectorExpr:
  75  			// e.Send / e.Recv: the pair is read, not copied.
  76  			if p.X == id {
  77  				continue
  78  			}
  79  			fail(id.Pos(), "an Edge cannot be copied; pass it to one spawn or return it")
  80  		case *ast.UnaryExpr:
  81  			// &p in the declaration's __edgealloc call.
  82  			if p.Op == token.AND && p.X == id {
  83  				continue
  84  			}
  85  			fail(id.Pos(), "an Edge cannot be copied; pass it to one spawn or return it")
  86  		case *ast.ReturnStmt:
  87  			// The move out of the frame.
  88  			continue
  89  		case *ast.AssignStmt:
  90  			// The LHS of an assignment reuses the name; the RHS would be a copy
  91  			// and falls here too, so only the LHS is permitted.
  92  			isLHS := false
  93  			for _, l := range p.Lhs {
  94  				if l == id {
  95  					isLHS = true
  96  					break
  97  				}
  98  			}
  99  			if isLHS {
 100  				continue
 101  			}
 102  			// `_ = e` discards the value: no second owner is created.
 103  			if len(p.Lhs) == 1 {
 104  				if blank, ok := p.Lhs[0].(*ast.Ident); ok && blank.Name == "_" {
 105  					continue
 106  				}
 107  			}
 108  			fail(id.Pos(), "an Edge cannot be copied; pass it to one spawn or return it")
 109  		case *ast.CallExpr:
 110  			if isSpawnCall(p, info) && len(p.Args) > 1 && containsExpr(p.Args[1:], id) {
 111  				if prev, ok := moved[obj]; ok {
 112  					fail(id.Pos(), "this Edge was already passed to spawn at %s; a pair has one child", fset.Position(prev.Pos()))
 113  					continue
 114  				}
 115  				moved[obj] = id
 116  				continue
 117  			}
 118  			fail(id.Pos(), "an Edge cannot be copied; pass it to one spawn or return it")
 119  		case *ast.DeclStmt, *ast.ValueSpec, *ast.Field:
 120  			// Declaration, not a use.
 121  			continue
 122  		default:
 123  			fail(id.Pos(), "an Edge cannot be copied; pass it to one spawn or return it")
 124  		}
 125  	}
 126  
 127  	sort.Slice(errs, func(i, j int) bool { return errs[i].Error() < errs[j].Error() })
 128  	return errs
 129  }
 130  
 131  // isEdgeObjectType reports whether t is the builtin Edge instantiation.
 132  func isEdgeObjectType(t types.Type) bool {
 133  	if t == nil {
 134  		return false
 135  	}
 136  	n, ok := t.(*types.Named)
 137  	if !ok || n.Obj() == nil || n.Obj().Pkg() != nil {
 138  		return false
 139  	}
 140  	return n.Obj().Name() == "Edge"
 141  }
 142  
 143  // isSpawnCall reports whether call invokes the predeclared spawn builtin.
 144  func isSpawnCall(call *ast.CallExpr, info *types.Info) bool {
 145  	id, ok := call.Fun.(*ast.Ident)
 146  	if !ok {
 147  		return false
 148  	}
 149  	obj := info.Uses[id]
 150  	if obj == nil {
 151  		obj = info.Defs[id]
 152  	}
 153  	if b, ok := obj.(*types.Builtin); ok {
 154  		return b.Name() == "spawn"
 155  	}
 156  	if f, ok := obj.(*types.Func); ok {
 157  		return f.Name() == "spawn" && f.Parent() == types.Universe
 158  	}
 159  	return false
 160  }
 161  
 162  func containsExpr(list []ast.Expr, n ast.Node) bool {
 163  	for _, e := range list {
 164  		if e == n {
 165  			return true
 166  		}
 167  	}
 168  	return false
 169  }
 170