1
0
mirror of https://github.com/golang/go synced 2024-11-26 10:28:19 -07:00

[dev.regabi] cmd/compile: add SameSource, Uses, and DeclaredBy helpers

Currently, because we use the same *Name to represent both declaration
and uses of an object, it's ambiguous what "n1 == n2" means when
comparing two Node values. It can mean any of: Are these the same
syntactic element? Is n1 a use of declared variable n2? Are n1 and n2
both uses of the same declared variable?

We'd like to introduce a new IdentExpr node to replace use of Name
within the AST, but that means those three cases need to be handled
differently. The first case needs to stay "n1 == n2", but the other
cases need to become "n1.Name() == n2" and "n1.Name() == n2.Name()",
respectively. ("n1.Name() == n2.Name()" also currently works for the
second case, but eventually we'll want to get rid of the Name.Name
method.)

This CL introduces helper functions SameSource and Uses to handle
these cases. It also introduces DeclaredBy, which is another somewhat
common case that the next CL introduces uses of.

Passes buildall w/ toolstash -cmp.

Updates #42990.

Change-Id: Ia816c124446e9067645d5820a8163f295968794f
Reviewed-on: https://go-review.googlesource.com/c/go/+/275305
Reviewed-by: Russ Cox <rsc@golang.org>
Trust: Matthew Dempsky <mdempsky@google.com>
This commit is contained in:
Matthew Dempsky 2020-12-03 16:52:45 -08:00
parent 5dbd2e8e44
commit d9cb84c84b

View File

@ -297,6 +297,43 @@ func (n *Name) SetVal(v constant.Value) {
n.val = v
}
// SameSource reports whether two nodes refer to the same source
// element.
//
// It exists to help incrementally migrate the compiler towards
// allowing the introduction of IdentExpr (#42990). Once we have
// IdentExpr, it will no longer be safe to directly compare Node
// values to tell if they refer to the same Name. Instead, code will
// need to explicitly get references to the underlying Name object(s),
// and compare those instead.
//
// It will still be safe to compare Nodes directly for checking if two
// nodes are syntactically the same. The SameSource function exists to
// indicate code that intentionally compares Nodes for syntactic
// equality as opposed to code that has yet to be updated in
// preparation for IdentExpr.
func SameSource(n1, n2 Node) bool {
return n1 == n2
}
// Uses reports whether expression x is a (direct) use of the given
// variable.
func Uses(x Node, v *Name) bool {
if v == nil || v.Op() != ONAME {
base.Fatalf("RefersTo bad Name: %v", v)
}
return x.Op() == ONAME && x.Name() == v
}
// DeclaredBy reports whether expression x refers (directly) to a
// variable that was declared by the given statement.
func DeclaredBy(x, stmt Node) bool {
if stmt == nil {
base.Fatalf("DeclaredBy nil")
}
return x.Op() == ONAME && SameSource(x.Name().Defn, stmt)
}
// The Class of a variable/function describes the "storage class"
// of a variable or function. During parsing, storage classes are
// called declaration contexts.