Skip to content
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
68 changes: 49 additions & 19 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,29 +385,44 @@ func GetPkgAbsPath(pkgPath string) (string, error) {
return absPath, nil
}

// ConcatString recursively concatenates strings from a binary expression
func ConcatString(n *ast.BinaryExpr) (string, bool) {
var s string
// sub expressions are found in X object, Y object is always last BasicLit
if rightOperand, ok := n.Y.(*ast.BasicLit); ok {
if str, err := GetString(rightOperand); err == nil {
s = str + s
}
} else {
// ConcatString recursively concatenates constant strings from an expression
// if the entire chain is fully constant-derived (using TryResolve).
// Returns the concatenated string and true if successful.
func ConcatString(expr ast.Expr, ctx *Context) (string, bool) {
if expr == nil || !TryResolve(expr, ctx) {
return "", false
}
if leftOperand, ok := n.X.(*ast.BinaryExpr); ok {
if recursion, ok := ConcatString(leftOperand); ok {
s = recursion + s
}
} else if leftOperand, ok := n.X.(*ast.BasicLit); ok {
if str, err := GetString(leftOperand); err == nil {
s = str + s

var build strings.Builder
var traverse func(ast.Expr) bool
traverse = func(e ast.Expr) bool {
switch node := e.(type) {
case *ast.BasicLit:
if str, err := GetString(node); err == nil {
build.WriteString(str)
return true
}
return false
case *ast.Ident:
values := GetIdentStringValuesRecursive(node)
for _, v := range values {
build.WriteString(v)
}
return len(values) > 0
case *ast.BinaryExpr:
if node.Op != token.ADD {
return false
}
return traverse(node.X) && traverse(node.Y)
default:
return false
}
} else {
return "", false
}
return s, true

if traverse(expr) {
return build.String(), true
}
return "", false
}

// FindVarIdentities returns array of all variable identities in a given binary expression
Expand Down Expand Up @@ -574,3 +589,18 @@ func CLIBuildTags(buildTags []string) []string {

return buildFlags
}

// ContainingFile returns the *ast.File from ctx.PkgFiles that contains the given node.
// Returns nil if not found (shouldn't happen for nodes from the analyzed package).
func ContainingFile(n ast.Node, ctx *Context) *ast.File {
if n == nil {
return nil
}
pos := n.Pos()
for _, f := range ctx.PkgFiles {
if f.Pos() <= pos && pos < f.End() {
return f
}
}
return nil
}
Loading
Loading