It looks like you're trying to create your own AST, as the right side of the expression you've given doesn't seem like a variable, otherwise I assume it as a struct. However, that's doesn't make sense too, since it'd be literally illogical to put a field named red in a struct named color. It also seems like you're trying to access a variable of a package but that also wouldn't work because lowercased first letter means that that the entity is unexported.
Leaving all them aside, I wrote a little snippet just to abide by the conditions you've listed.
- shape variable has the color attribute.
- color variable has red attribute.
https://play.golang.org/p/gIpctQ1XSgT, I adapted it just for a single line and panicked whenever conditions aren't met for brevity. Feel free to adjust it on your needs.
package main
import (
"go/ast"
"go/format"
"go/parser"
"go/token"
"os"
)
func main() {
expr, err := parser.ParseExpr("shape.color==color.red")
if err != nil {
panic(err)
}
// Checking if the expression was binary.
bExpr, ok := expr.(*ast.BinaryExpr)
if !ok {
panic("expr is not a binary expr.")
}
// If the operation is not “==”, die.
if bExpr.Op != token.EQL {
panic("the op should have been ==.")
}
// Left must be a selector expr, meaning followed with a selector which is “dot” in this case.
left, ok := bExpr.X.(*ast.SelectorExpr)
if !ok {
panic("left should have been a selector expr.")
}
// Same as above.
right, ok := bExpr.Y.(*ast.SelectorExpr)
if !ok {
panic("right should have been a selector expr.")
}
// Checking for attributes.
if left.Sel.Name != "color" {
panic("left should have had a color attr.")
}
// Same as above.
if right.Sel.Name != "red" {
panic("right should have had a red attr.")
}
// Then we finally gofmt the code and print it to stdout.
if err := format.Node(os.Stdout, token.NewFileSet(), expr); err != nil {
panic(err)
}
}