Documentation
¶
Overview ¶
Package astutil provides shared AST/type helper functions used by linters.
Index ¶
- func AddImportEdit(pass *analysis.Pass, file *ast.File, pkg string) (analysis.TextEdit, bool)
- func AsStringsMethodCall(pass *analysis.Pass, expr ast.Expr, methodName string) (*ast.CallExpr, bool)
- func BuildContainsFix(expr *ast.BinaryExpr, pkgText, sText, subText string, negated bool, ...) []analysis.SuggestedFix
- func CallQualifierText(fset *token.FileSet, call *ast.CallExpr) string
- func CalledOSFunc(pass *analysis.Pass, call *ast.CallExpr, allowedNames ...string) (*types.Func, bool)
- func ConstIntValue(pass *analysis.Pass, expr ast.Expr) (int64, bool)
- func ContextContextType(pass *analysis.Pass) types.Type
- func ContextParamName(pass *analysis.Pass, fn *ast.FuncType) (string, bool)
- func CountPkgUsesInFile(pass *analysis.Pass, file *ast.File, pkgPath string) int
- func EnclosingFuncType(node ast.Node) *ast.FuncType
- func FileForPos(files []*ast.File, pos token.Pos) *ast.File
- func FlipComparisonOp(op token.Token) token.Token
- func HasConstantStringArg(pass *analysis.Pass, call *ast.CallExpr, argIdx int) bool
- func HasOverlappingComment(files []*ast.File, start, end token.Pos) bool
- func ImportSpecLineRange(fset *token.FileSet, spec *ast.ImportSpec) (token.Pos, token.Pos)
- func ImportedAs(file *ast.File, info *types.Info, importPath string) (string, bool)
- func Inspector(pass *analysis.Pass) (*inspector.Inspector, error)
- func IsByteSlice(pass *analysis.Pass, expr ast.Expr) bool
- func IsByteSliceConversion(pass *analysis.Pass, conv *ast.CallExpr) bool
- func IsFmtErrorf(pass *analysis.Pass, call *ast.CallExpr) bool
- func IsGoOrDeferClosure(funcLitCur inspector.Cursor) bool
- func IsInInitFunction(cur inspector.Cursor) bool
- func IsLocalObject(obj types.Object) bool
- func IsPkgSelector(pass *analysis.Pass, sel *ast.SelectorExpr, pkgPath string) bool
- func IsRegexpCompileCall(pass *analysis.Pass, call *ast.CallExpr, names ...string) bool
- func IsStringLiteral(expr ast.Expr) bool
- func IsStringType(pass *analysis.Pass, expr ast.Expr) bool
- func NodeText(fset *token.FileSet, node ast.Node) string
- func NormalizeComparisonOperands(pass *analysis.Pass, expr *ast.BinaryExpr, methodName string) (left, right ast.Expr, flipped bool)
- func QualifierShadowed(pkg *types.Package, pos token.Pos, name, importPath string) bool
- func RemoveImportEdit(fset *token.FileSet, file *ast.File, pkg string) (analysis.TextEdit, bool)
- func RhsExprForIndex(rhs []ast.Expr, idx int) (ast.Expr, bool)
- func Root(pass *analysis.Pass) (inspector.Cursor, error)
- func StringLitValue(expr ast.Expr) (string, bool)
- func SwapImportEdits(fset *token.FileSet, file *ast.File, addPkg, removePkg string) []analysis.TextEdit
- func SwapPkgImportEdits(pass *analysis.Pass, file *ast.File, addPkg, removePkg string, ...) ([]analysis.TextEdit, bool)
- func UniverseErrorInterface() *types.Interface
- func UnwrapParenExpr(expr ast.Expr) ast.Expr
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddImportEdit ¶ added in v0.83.3
AddImportEdit returns a TextEdit that inserts an import for pkg into file, choosing the least-invasive insertion point: append to an existing grouped block, convert a single non-grouped import to a grouped block, or insert a standalone declaration after the package name.
func AsStringsMethodCall ¶ added in v0.82.10
func AsStringsMethodCall(pass *analysis.Pass, expr ast.Expr, methodName string) (*ast.CallExpr, bool)
AsStringsMethodCall returns the *ast.CallExpr if expr is a call to the named method on the "strings" package (e.g. "Index" or "Count").
func BuildContainsFix ¶ added in v0.82.10
func BuildContainsFix(expr *ast.BinaryExpr, pkgText, sText, subText string, negated bool, fixMessage string) []analysis.SuggestedFix
BuildContainsFix builds the suggested fix rewriting a comparison to strings.Contains. fixMessage is used as the SuggestedFix.Message field so callers can identify the rewritten function (e.g. "Index" vs "Count").
func CallQualifierText ¶ added in v0.82.10
CallQualifierText returns the source text of the package qualifier in a selector call such as pkg.Method(...). For example, for strings.Index(...) it returns "strings" (or the local alias when the import is aliased). Returns "" if call.Fun is not a *ast.SelectorExpr.
func CalledOSFunc ¶ added in v0.82.3
func CalledOSFunc(pass *analysis.Pass, call *ast.CallExpr, allowedNames ...string) (*types.Func, bool)
CalledOSFunc reports whether call resolves to a function in package os. If allowedNames are provided, the function name must match one of them.
func ConstIntValue ¶ added in v0.82.10
ConstIntValue returns the integer constant value of expr, if it is a constant integer.
func ContextContextType ¶ added in v0.82.3
ContextContextType returns the types.Type for context.Context, or nil if the context package is not imported.
func ContextParamName ¶ added in v0.82.3
ContextParamName returns the name of the first context.Context parameter in fn, and true, or "", false if none exists.
func CountPkgUsesInFile ¶ added in v0.83.3
CountPkgUsesInFile returns the number of times the package at pkgPath is referenced as a selector base within file (e.g. each "fmt.X" call counts as one use of the "fmt" package).
func EnclosingFuncType ¶ added in v0.82.3
EnclosingFuncType extracts a function type from a FuncDecl or FuncLit node.
func FileForPos ¶ added in v0.83.3
FileForPos returns the *ast.File from files that contains pos, or nil if not found. It is used by linters that need the enclosing file of a node when only the pass.Files slice is available.
func FlipComparisonOp ¶ added in v0.82.3
FlipComparisonOp returns the comparison operator with left and right operands swapped.
func HasConstantStringArg ¶ added in v0.87.1
HasConstantStringArg reports whether the argument at argIdx of call is a compile-time constant string, such as a string literal, a const identifier, or an expression built entirely from constants (e.g. concatenation of string literals/consts). Non-constant expressions such as fmt.Sprintf results, concatenation involving variables, or function parameters return false.
func HasOverlappingComment ¶ added in v0.82.13
HasOverlappingComment reports whether any comment group in files overlaps the half-open range [start, end). This is used by linters to suppress a SuggestedFix when a comment inside the to-be-replaced span would otherwise be silently discarded by the autofix tool.
func ImportSpecLineRange ¶ added in v0.83.3
ImportSpecLineRange returns the [start, end) byte range that covers the entire source line of spec — including any leading whitespace and the trailing newline. It uses the token.File's line table so it works correctly regardless of indentation style.
func ImportedAs ¶ added in v0.82.10
ImportedAs returns the local binding name for importPath in file along with whether the import exists. When the import has an explicit alias (Name != nil), the alias is returned. Otherwise info.Implicits is consulted to obtain the *types.PkgName that the type-checker created for the import; its Name() method returns the package's declared name, which may differ from the last path segment for versioned modules (e.g. "github.com/foo/v2" declares package "foo"). info may be nil as a fallback, in which case the last path segment is used. The special aliases "." and "_" are returned as-is for callers to handle. Import path literals are decoded with strconv.Unquote so both double-quoted and raw (backtick) spellings are matched correctly.
func Inspector ¶ added in v0.79.4
Inspector extracts the *inspector.Inspector from pass.ResultOf. It returns an error if the result has an unexpected type.
func IsByteSlice ¶ added in v0.82.12
IsByteSlice reports whether expr has underlying type []byte ([]uint8).
func IsByteSliceConversion ¶ added in v0.82.12
IsByteSliceConversion reports whether conv is a []byte or []uint8 conversion expression.
func IsFmtErrorf ¶
IsFmtErrorf reports whether call is a call to fmt.Errorf (including aliases).
func IsGoOrDeferClosure ¶ added in v0.82.3
IsGoOrDeferClosure reports whether the FuncLit at funcLitCur is the direct callee of a go or defer statement, handling parenthesized forms like defer (func(){})().
func IsInInitFunction ¶ added in v0.87.1
IsInInitFunction reports whether cur is inside a top-level init() function. Only top-level (no receiver) init functions are recognized; methods named init are ordinary methods and are not exempt. A node whose innermost enclosing function is a literal (e.g. a goroutine started from init) is not considered to be in init.
func IsLocalObject ¶
IsLocalObject reports whether obj is a local (non-package-scope) object.
func IsPkgSelector ¶ added in v0.80.5
IsPkgSelector reports whether sel is a selector on an imported package with the given import path.
func IsRegexpCompileCall ¶ added in v0.87.1
IsRegexpCompileCall reports whether call is a call to one of the named functions on the standard "regexp" package. The package identity is resolved via the type checker so aliased imports are handled and local identifiers named "regexp" do not produce false positives.
func IsStringLiteral ¶
IsStringLiteral reports whether expr is a string literal.
func IsStringType ¶ added in v0.82.12
IsStringType reports whether expr has underlying type string (or a named string type).
func NormalizeComparisonOperands ¶ added in v0.87.1
func NormalizeComparisonOperands(pass *analysis.Pass, expr *ast.BinaryExpr, methodName string) (left, right ast.Expr, flipped bool)
NormalizeComparisonOperands returns (left, right) such that left is the operand holding the strings.<methodName> call. When the call is on the right side of expr the operands are swapped and flipped is true. Both operands are unwrapped of any redundant parentheses before the check. If neither operand is the target strings call, the original left/right order is preserved.
func QualifierShadowed ¶ added in v0.82.10
QualifierShadowed reports whether name cannot safely be used as a qualifier for importPath at pos. It returns true when:
- a local variable or parameter named name is in scope at pos, or
- name is bound to a *types.PkgName for a different import path.
Either case means that emitting "name.Foo" at pos would not resolve to the intended package. Call this before emitting a fix that uses name as a package qualifier to ensure the qualifier resolves to the expected import and not to a local variable, a parameter, or an unrelated package import.
func RemoveImportEdit ¶ added in v0.83.3
RemoveImportEdit returns a TextEdit that removes the import of pkg from file's import section. For an ungrouped or sole-spec grouped declaration the entire decl is removed; for a multi-spec grouped block only the spec line is deleted using line-boundary positions from fset to handle any indentation.
func RhsExprForIndex ¶
RhsExprForIndex returns the RHS expression mapped to idx when available. When rhs has a single expression, only idx==0 is considered mapped.
func Root ¶ added in v0.82.2
Root extracts the inspector root cursor from pass.ResultOf. It returns an error if the inspect result has an unexpected type.
func StringLitValue ¶ added in v0.87.1
StringLitValue returns the unquoted string value of a string-literal AST node.
func SwapImportEdits ¶ added in v0.83.3
func SwapImportEdits(fset *token.FileSet, file *ast.File, addPkg, removePkg string) []analysis.TextEdit
SwapImportEdits returns the TextEdits that simultaneously add addPkg and remove removePkg from file's import section. Three structural cases are handled:
- single ungrouped import removePkg → replaced with import addPkg
- grouped block with only removePkg → replaced with import addPkg
- grouped block with removePkg + others → insert addPkg, delete removePkg line
func SwapPkgImportEdits ¶ added in v0.87.1
func SwapPkgImportEdits(pass *analysis.Pass, file *ast.File, addPkg, removePkg string, removeOrphaned bool) ([]analysis.TextEdit, bool)
SwapPkgImportEdits returns the TextEdits that add addPkg to file and, when removeOrphaned is true, remove the now-unused removePkg import. The second return value reports whether an import change was required; it is false only when addPkg is already imported and removeOrphaned is false. A required change may still yield no edits when the import section cannot be rewritten, so callers must not assume a non-empty slice when it is true.
func UniverseErrorInterface ¶ added in v0.87.1
UniverseErrorInterface returns the built-in error interface type, or nil if it cannot be resolved from types.Universe.
Types ¶
This section is empty.