Skip to content

refactor: moves code related to AST from rule.utils into astutils package #1380

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 76 additions & 1 deletion internal/astutils/ast_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@
package astutils

import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"regexp"
"slices"
)

Expand Down Expand Up @@ -78,9 +82,80 @@ func getFieldTypeName(typ ast.Expr) string {
}
}

// IsStringLiteral returns true if the given expression is a string literal, false otherwise
// IsStringLiteral returns true if the given expression is a string literal, false otherwise.
func IsStringLiteral(e ast.Expr) bool {
sl, ok := e.(*ast.BasicLit)

return ok && sl.Kind == token.STRING
}

// IsCgoExported returns true if the given function declaration is exported as Cgo function, false otherwise.
func IsCgoExported(f *ast.FuncDecl) bool {
if f.Recv != nil || f.Doc == nil {
return false
}

cgoExport := regexp.MustCompile(fmt.Sprintf("(?m)^//export %s$", regexp.QuoteMeta(f.Name.Name)))
for _, c := range f.Doc.List {
if cgoExport.MatchString(c.Text) {
return true
}
}
return false
}

// IsIdent returns true if the given expression is the identifier with name ident, false otherwise.
func IsIdent(expr ast.Expr, ident string) bool {
id, ok := expr.(*ast.Ident)
return ok && id.Name == ident
}

// IsPkgDotName returns true if the given expression is a selector expression of the form <pkg>.<name>, false otherwise.
func IsPkgDotName(expr ast.Expr, pkg, name string) bool {
sel, ok := expr.(*ast.SelectorExpr)
return ok && IsIdent(sel.X, pkg) && IsIdent(sel.Sel, name)
}

// PickNodes yields a list of nodes by picking them from a sub-ast with root node n.
// Nodes are selected by applying the selector function
func PickNodes(n ast.Node, selector func(n ast.Node) bool) []ast.Node {
var result []ast.Node

if n == nil {
return result
}

onSelect := func(n ast.Node) {
result = append(result, n)
}
p := picker{selector: selector, onSelect: onSelect}
ast.Walk(p, n)
return result
}

type picker struct {
selector func(n ast.Node) bool
onSelect func(n ast.Node)
}

func (p picker) Visit(node ast.Node) ast.Visitor {
if p.selector == nil {
return nil
}

if p.selector(node) {
p.onSelect(node)
}

return p
}

var gofmtConfig = &printer.Config{Tabwidth: 8}

// GoFmt returns a string representation of an AST subtree.
func GoFmt(x any) string {
buf := bytes.Buffer{}
fs := token.NewFileSet()
gofmtConfig.Fprint(&buf, fs, x)
return buf.String()
}
5 changes: 3 additions & 2 deletions rule/atomic.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"go/token"
"go/types"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -76,9 +77,9 @@ func (w atomic) Visit(node ast.Node) ast.Visitor {
broken := false

if uarg, ok := arg.(*ast.UnaryExpr); ok && uarg.Op == token.AND {
broken = gofmt(left) == gofmt(uarg.X)
broken = astutils.GoFmt(left) == astutils.GoFmt(uarg.X)
} else if star, ok := left.(*ast.StarExpr); ok {
broken = gofmt(star.X) == gofmt(arg)
broken = astutils.GoFmt(star.X) == astutils.GoFmt(arg)
}

if broken {
Expand Down
3 changes: 2 additions & 1 deletion rule/confusing_naming.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"
"sync"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -190,7 +191,7 @@ func (w *lintConfusingNames) Visit(n ast.Node) ast.Visitor {
// Exclude naming warnings for functions that are exported to C but
// not exported in the Go API.
// See https://github.com/golang/lint/issues/144.
if ast.IsExported(v.Name.Name) || !isCgoExported(v) {
if ast.IsExported(v.Name.Name) || !astutils.IsCgoExported(v) {
checkMethodName(getStructName(v.Recv), v.Name, w)
}
case *ast.TypeSpec:
Expand Down
3 changes: 2 additions & 1 deletion rule/confusing_results.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rule
import (
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand All @@ -28,7 +29,7 @@ func (*ConfusingResultsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fai

lastType := ""
for _, result := range funcDecl.Type.Results.List {
resultTypeName := gofmt(result.Type)
resultTypeName := astutils.GoFmt(result.Type)

if resultTypeName == lastType {
failures = append(failures, lint.Failure{
Expand Down
3 changes: 2 additions & 1 deletion rule/constant_logical_expr.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"go/ast"
"go/token"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -40,7 +41,7 @@ func (w *lintConstantLogicalExpr) Visit(node ast.Node) ast.Visitor {
return w
}

subExpressionsAreNotEqual := gofmt(n.X) != gofmt(n.Y)
subExpressionsAreNotEqual := astutils.GoFmt(n.X) != astutils.GoFmt(n.Y)
if subExpressionsAreNotEqual {
return w // nothing to say
}
Expand Down
5 changes: 3 additions & 2 deletions rule/context_as_argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"go/ast"
"strings"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand All @@ -28,7 +29,7 @@ func (r *ContextAsArgumentRule) Apply(file *lint.File, _ lint.Arguments) []lint.
// Flag any that show up after the first.
isCtxStillAllowed := true
for _, arg := range fnArgs {
argIsCtx := isPkgDot(arg.Type, "context", "Context")
argIsCtx := astutils.IsPkgDotName(arg.Type, "context", "Context")
if argIsCtx && !isCtxStillAllowed {
failures = append(failures, lint.Failure{
Node: arg,
Expand All @@ -40,7 +41,7 @@ func (r *ContextAsArgumentRule) Apply(file *lint.File, _ lint.Arguments) []lint.
break // only flag one
}

typeName := gofmt(arg.Type)
typeName := astutils.GoFmt(arg.Type)
// a parameter of type context.Context is still allowed if the current arg type is in the allow types LookUpTable
_, isCtxStillAllowed = r.allowTypes[typeName]
}
Expand Down
11 changes: 2 additions & 9 deletions rule/context_keys_type.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"go/ast"
"go/types"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -51,15 +52,7 @@ func (w lintContextKeyTypes) Visit(n ast.Node) ast.Visitor {

func checkContextKeyType(w lintContextKeyTypes, x *ast.CallExpr) {
f := w.file
sel, ok := x.Fun.(*ast.SelectorExpr)
if !ok {
return
}
pkg, ok := sel.X.(*ast.Ident)
if !ok || pkg.Name != "context" {
return
}
if sel.Sel.Name != "WithValue" {
if !astutils.IsPkgDotName(x.Fun, "context", "WithValue") {
return
}

Expand Down
3 changes: 2 additions & 1 deletion rule/datarace.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -111,7 +112,7 @@ func (w lintFunctionForDataRaces) Visit(node ast.Node) ast.Visitor {
return ok
}

ids := pick(funcLit.Body, selectIDs)
ids := astutils.PickNodes(funcLit.Body, selectIDs)
for _, id := range ids {
id := id.(*ast.Ident)
_, isRangeID := w.rangeIDs[id.Obj]
Expand Down
5 changes: 3 additions & 2 deletions rule/defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -106,7 +107,7 @@ func (w lintDeferRule) Visit(node ast.Node) ast.Visitor {
w.newFailure("return in a defer function has no effect", n, 1.0, lint.FailureCategoryLogic, deferOptionReturn)
}
case *ast.CallExpr:
isCallToRecover := isIdent(n.Fun, "recover")
isCallToRecover := astutils.IsIdent(n.Fun, "recover")
switch {
case !w.inADefer && isCallToRecover:
// func fn() { recover() }
Expand All @@ -122,7 +123,7 @@ func (w lintDeferRule) Visit(node ast.Node) ast.Visitor {
}
return nil // no need to analyze the arguments of the function call
case *ast.DeferStmt:
if isIdent(n.Call.Fun, "recover") {
if astutils.IsIdent(n.Call.Fun, "recover") {
// defer recover()
//
// confidence is not truly 1 because this could be in a correctly-deferred func,
Expand Down
4 changes: 2 additions & 2 deletions rule/enforce_map_style.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -101,8 +102,7 @@ func (r *EnforceMapStyleRule) Apply(file *lint.File, _ lint.Arguments) []lint.Fa
return true
}

ident, ok := v.Fun.(*ast.Ident)
if !ok || ident.Name != "make" {
if !astutils.IsIdent(v.Fun, "make") {
return true
}

Expand Down
9 changes: 5 additions & 4 deletions rule/enforce_repeated_arg_type_style.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -130,8 +131,8 @@ func (r *EnforceRepeatedArgTypeStyleRule) Apply(file *lint.File, _ lint.Argument
if fn.Type.Params != nil {
var prevType ast.Expr
for _, field := range fn.Type.Params.List {
prevTypeStr := gofmt(prevType)
currentTypeStr := gofmt(field.Type)
prevTypeStr := astutils.GoFmt(prevType)
currentTypeStr := astutils.GoFmt(field.Type)
if currentTypeStr == prevTypeStr {
failures = append(failures, lint.Failure{
Confidence: 1,
Expand Down Expand Up @@ -163,8 +164,8 @@ func (r *EnforceRepeatedArgTypeStyleRule) Apply(file *lint.File, _ lint.Argument
if fn.Type.Results != nil {
var prevType ast.Expr
for _, field := range fn.Type.Results.List {
prevTypeStr := gofmt(prevType)
currentTypeStr := gofmt(field.Type)
prevTypeStr := astutils.GoFmt(prevType)
currentTypeStr := astutils.GoFmt(field.Type)
if field.Names != nil && currentTypeStr == prevTypeStr {
failures = append(failures, lint.Failure{
Confidence: 1,
Expand Down
4 changes: 2 additions & 2 deletions rule/enforce_slice_style.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -117,8 +118,7 @@ func (r *EnforceSliceStyleRule) Apply(file *lint.File, _ lint.Arguments) []lint.
return true
}

ident, ok := v.Fun.(*ast.Ident)
if !ok || ident.Name != "make" {
if !astutils.IsIdent(v.Fun, "make") {
return true
}

Expand Down
3 changes: 2 additions & 1 deletion rule/error_naming.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"go/token"
"strings"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -56,7 +57,7 @@ func (w lintErrors) Visit(_ ast.Node) ast.Visitor {
if !ok {
continue
}
if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") {
if !astutils.IsPkgDotName(ce.Fun, "errors", "New") && !astutils.IsPkgDotName(ce.Fun, "fmt", "Errorf") {
continue
}

Expand Down
5 changes: 3 additions & 2 deletions rule/error_return.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package rule
import (
"go/ast"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand All @@ -21,15 +22,15 @@ func (*ErrorReturnRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure
}

funcResults := funcDecl.Type.Results.List
isLastResultError := isIdent(funcResults[len(funcResults)-1].Type, "error")
isLastResultError := astutils.IsIdent(funcResults[len(funcResults)-1].Type, "error")
if isLastResultError {
continue
}

// An error return parameter should be the last parameter.
// Flag any error parameters found before the last.
for _, r := range funcResults[:len(funcResults)-1] {
if isIdent(r.Type, "error") {
if astutils.IsIdent(r.Type, "error") {
failures = append(failures, lint.Failure{
Category: lint.FailureCategoryStyle,
Confidence: 0.9,
Expand Down
5 changes: 3 additions & 2 deletions rule/errorf.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"strings"

"github.com/mgechev/revive/internal/astutils"
"github.com/mgechev/revive/lint"
)

Expand Down Expand Up @@ -47,7 +48,7 @@ func (w lintErrorf) Visit(n ast.Node) ast.Visitor {
if !ok || len(ce.Args) != 1 {
return w
}
isErrorsNew := isPkgDot(ce.Fun, "errors", "New")
isErrorsNew := astutils.IsPkgDotName(ce.Fun, "errors", "New")
var isTestingError bool
se, ok := ce.Fun.(*ast.SelectorExpr)
if ok && se.Sel.Name == "Error" {
Expand All @@ -60,7 +61,7 @@ func (w lintErrorf) Visit(n ast.Node) ast.Visitor {
}
arg := ce.Args[0]
ce, ok = arg.(*ast.CallExpr)
if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") {
if !ok || !astutils.IsPkgDotName(ce.Fun, "fmt", "Sprintf") {
return w
}
errorfPrefix := "fmt"
Expand Down
Loading