1 // Copyright 2018 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.
5 // Package analysisutil defines various helper functions
6 // used by two or more packages beneath go/analysis.
18 // Format returns a string representation of the expression.
19 func Format(fset *token.FileSet, x ast.Expr) string {
21 printer.Fprint(&b, fset, x)
25 // HasSideEffects reports whether evaluation of e has side effects.
26 func HasSideEffects(info *types.Info, e ast.Expr) bool {
28 ast.Inspect(e, func(node ast.Node) bool {
29 switch n := node.(type) {
31 typVal := info.Types[n.Fun]
34 // Type conversion, which is safe.
35 case typVal.IsBuiltin():
36 // Builtin func, conservatively assumed to not
41 // A non-builtin func or method call.
42 // Conservatively assume that all of them have
43 // side effects for now.
48 if n.Op == token.ARROW {
58 // Unparen returns e with any enclosing parentheses stripped.
59 func Unparen(e ast.Expr) ast.Expr {
61 p, ok := e.(*ast.ParenExpr)
69 // ReadFile reads a file and adds it to the FileSet
70 // so that we can report errors against it using lineStart.
71 func ReadFile(fset *token.FileSet, filename string) ([]byte, *token.File, error) {
72 content, err := ioutil.ReadFile(filename)
76 tf := fset.AddFile(filename, -1, len(content))
77 tf.SetLinesForContent(content)
78 return content, tf, nil
81 // LineStart returns the position of the start of the specified line
82 // within file f, or NoPos if there is no line of that number.
83 func LineStart(f *token.File, line int) token.Pos {
84 // Use binary search to find the start offset of this line.
86 // TODO(adonovan): eventually replace this function with the
87 // simpler and more efficient (*go/token.File).LineStart, added
91 max := f.Size() // exclusive
93 offset := (min + max) / 2
95 posn := f.Position(pos)
96 if posn.Line == line {
97 return pos - (token.Pos(posn.Column) - 1)
104 if posn.Line < line {
112 // Imports returns true if path is imported by pkg.
113 func Imports(pkg *types.Package, path string) bool {
114 for _, imp := range pkg.Imports() {
115 if imp.Path() == path {