github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/codegen/loaderx/eval.go (about)

     1  package loaderx
     2  
     3  import (
     4  	"bytes"
     5  	"go/ast"
     6  	"go/format"
     7  	"go/token"
     8  	"go/types"
     9  )
    10  
    11  func StringifyAst(fset *token.FileSet, node ast.Node) string {
    12  	buf := bytes.Buffer{}
    13  	if err := format.Node(&buf, fset, node); err != nil {
    14  		panic(err)
    15  	}
    16  	return buf.String()
    17  }
    18  
    19  func MustEvalExpr(fileSet *token.FileSet, pkg *types.Package, expr ast.Expr) types.TypeAndValue {
    20  	if expr == nil {
    21  		return types.TypeAndValue{
    22  			Type: types.Typ[types.UntypedNil],
    23  		}
    24  	}
    25  
    26  	if ident, ok := expr.(*ast.Ident); ok && ident.Name == "nil" {
    27  		return types.TypeAndValue{
    28  			Type: types.Typ[types.UntypedNil],
    29  		}
    30  	}
    31  
    32  	code := StringifyAst(fileSet, expr)
    33  	tv, err := types.Eval(fileSet, pkg, expr.Pos(), code)
    34  	if err != nil {
    35  		panic(err)
    36  	}
    37  	return tv
    38  }