packages

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 23, 2020 License: MPL-2.0, MPL-2.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// LoadSyntax approximates the deprecated tools/go/packages.LoadSyntax mode.
	LoadSyntax = std_packages.NeedName |
		std_packages.NeedFiles |
		std_packages.NeedImports |
		std_packages.NeedTypes |
		std_packages.NeedTypesInfo |
		std_packages.NeedSyntax

	// StdNeedMin is the current lowest tools/go/packages.Need* constant value.
	StdNeedMin = std_packages.NeedName

	// StdNeedMax is the current highest tools/go/packages.Need* constant value.
	StdNeedMax = std_packages.NeedTypesSizes
)
View Source
const (
	// BlankIdNamePrefix is used to build names for blank identifiers.
	//
	// Format: "<BlankIdNamePrefix><per-file zero-indexed pos #><GlobalIdSeparator><per-GenDecl zero-indexed pos #><GlobalIdSeparator><file absolute path>"
	//
	// It supports cases such as indexing the types used by interface assertions.
	BlankIdNamePrefix = "_"
)
View Source
const (
	GlobalIdSeparator = "."
)
View Source
const (
	// InitIdNamePrefix is used to build identifier names for init functions.
	//
	// Format: "<InitIdNamePrefix><GlobalIdSeparator><file absolute path>"
	//
	// It supports cases such as indexing the nodes used by a given init function.
	InitIdNamePrefix = "init"
)

Variables

This section is empty.

Functions

func DirImportPath added in v0.1.1

func DirImportPath(modImportPath, modRootDir, pkgDir string) (importPath string, _ error)

DirImportPath returns the package dir's import path based on its relative location to the module root.

func GlobalIdNameBase

func GlobalIdNameBase(idName GlobalIdName) string

func LoadModeString

func LoadModeString(m std_packages.LoadMode) string

func NeedSatisfied

func NeedSatisfied(needer, satisfier std_packages.LoadMode) bool

NeedSatisfied returns true if the "needer" mode's enabled bits are also enabled in the "satisifier" mode, where the satisfier can provide an exact or superset of what's needed.

If the needer has no enabled bits, true is returned.

func NewCacheKey

func NewCacheKey(cfg *Config, pattern string) (key string)

func NewInitIdName

func NewInitIdName(filename string) string

func ParseInitIdName

func ParseInitIdName(name string) (filename string)

func StdSdump

func StdSdump(p *std_packages.Package, indentTabs int) string

func StdlibDir

func StdlibDir(p string) string

func TrimVendorPathPrefix

func TrimVendorPathPrefix(importPath string) string

TrimVendorPathPrefix trims "path/to/vendor/repo/user/proj" to "repo/user/proj".

Types

type AssignPos

type AssignPos int

AssignPos describes where an identifier is used in an assignment.

const (
	// NonAssignUsage indicates the identifier was not used in an assignment.
	NonAssignUsage AssignPos = iota

	// LhsAssignUsage indicates the identifier was used on the left-hand side of an assignment.
	LhsAssignUsage

	// HhsAssignUsage indicates the identifier was used on the right-hand side of an assignment.
	RhsAssignUsage
)

type BlankId

type BlankId struct {
	// Filename identifies the source file of the node.
	Filename string

	// FilePos uniquely identifes the node within its file.
	//
	// It is 0-indexed and based on a counter of the occurence of blank identifiers within the file.
	FilePos int

	// GenDeclPos uniquely identifes the node within its parent ast.GenDecl node.
	//
	// It is 0-indexed and based on a counter of the occurence of blank identifiers within the ast.GenDecl.
	GenDeclPos int
}

BlankId describes the location of a blank identifier ("_").

func NewBlankId

func NewBlankId(filename string, filePos, genDeclPos int) *BlankId

func NewBlankIdFromString

func NewBlankIdFromString(s string) (id *BlankId, err error)

func (*BlankId) String

func (i *BlankId) String() string

type Cache

type Cache struct {
	// Enabled is true if Cache.data reads and writes should be performed. If false, full queries always occur.
	Enabled bool

	// OnHit is called for each hit processed by LoadImportPath/LoadDir.
	OnHit OnHitFunc

	// OnMiss is called for each hit processed by LoadImportPath/LoadDir.
	OnMiss OnMissFunc
	// contains filtered or unexported fields
}

Cache serves x/tools/go/packages.Load queries via methods like LoadImportPath which write to a cache shared by all query methods.

func NewCache

func NewCache() *Cache

func (*Cache) Data

func (c *Cache) Data() ImportIdx

func (*Cache) LoadDir

func (c *Cache) LoadDir(cfg *Config, dir string) (PkgsByName, []error)

LoadDir performs a single-directory query.

It adds NeedName|NeedFiles to all Config.Mode values in order to index the returned map.

It does not support Config.Tests because test x/tools/go/packages.Load does not support direct queries for "_test" packages, even with Config.Tests enabled. (Instead, the query must specify the implementation's import path or the file directory containing both packages.)

func (*Cache) LoadDirs

func (c *Cache) LoadDirs(cfg *Config, dirs ...string) (_ DirPkgs, errs []error)

LoadDirs performs a query for the packages in one or more directories.

It adds NeedName|NeedFiles to all Config.Mode values in order to index the returned map.

func (*Cache) LoadImportPath

func (c *Cache) LoadImportPath(cfg *Config, importPath string) (*Package, []error)

LoadImportPath performs a single-package query.

It adds NeedName|NeedFiles to all Config.Mode values in order to index the returned map.

It does not support Config.Tests because test x/tools/go/packages.Load does not support direct queries for "_test" packages, even with Config.Tests enabled. (Instead, the query must specify the implementation's import path or the file directory containing both packages.)

func (*Cache) LoadImportPathWithBuild

func (c *Cache) LoadImportPathWithBuild(importPath, srcDir string, mode build.ImportMode) (PkgsByName, error)

LoadImportPathWithBuild uses go/build to generate the Package instead of x/tools/go/packages.

Its main benefit over x/tools/go/packages is non-recursive queries, i.e. abiility to find the package's imported paths without also finding the latter's imported paths and so on. Elements of x/tools/go/packages.Package.Imports only contain the PkgPath field.

If the import path selects a standard library, only these fields populated: Dir (if go/build provides it), Goroot, ImportPaths (if mode provides them), PkgPath, and Name.

func (*Cache) LoadImportPaths

func (c *Cache) LoadImportPaths(cfg *Config, _importPaths ...string) (loaded PkgsByImportPath, errs []error)

LoadImportPaths is the more generic method behind LoadImportPath and LoadDir queries which reads from the cache, performs the actual x/tools/go/packages.Load query, and writes to the cache.

It adds NeedName|NeedFiles to all Config.Mode values in order to index the returned map.

func (*Cache) String

func (c *Cache) String() string

type CacheHit

type CacheHit struct {
	// Key is the NewCacheKey value used in the query.
	Key string

	// Mode is the value used in the past query which populated the cached Package.
	//
	// It is a PkgIdx map key.
	Mode std_packages.LoadMode

	// Package is the cached query result.
	Value CacheValue
}

CacheHit describes the query and cached data.

type CacheMiss

type CacheMiss struct {
	// Key is the NewCacheKey value used in the query.
	Key string

	// Mode is the value used in the current query.
	Mode std_packages.LoadMode
}

CacheMiss describes the query.

type CacheValue

type CacheValue struct {
	*Package

	// WriteId is the value of Cache.writeId at creation time.
	WriteId int

	// Hits is a counter.
	Hits int
}

type Config

type Config struct {
	*std_packages.Config
}

func NewConfig

func NewConfig(cfg *std_packages.Config) *Config

func (*Config) Copy

func (c *Config) Copy() *Config

type DirGlobalIdNodes

type DirGlobalIdNodes map[string]PkgGlobalIdNodes

DirGlobalIdNodes holds a Node for each of a package's identifiers.

It is indexed by directory absolute path.

func (DirGlobalIdNodes) SortedDirs

func (n DirGlobalIdNodes) SortedDirs() []string

SortedDirs returns the map's keys in sorted order.

type DirGlobalIdShadows

type DirGlobalIdShadows map[string]PkgGlobalIdShadows

DirGlobalIdShadows holds Shadow values in each directory which contains at least one global function/method containing at least one shadow.

It is indexed by directory absolute path.

type DirImportPaths

type DirImportPaths map[string]PkgImportPaths

DirImportPaths holds directories' per-file import path sets.

It is indexed by directory absolute paths.

type DirImports

type DirImports map[string]PkgImports

DirImports describes the packages imported by all files in a directory.

It is indexed by directory absolute path.

type DirPkgs

type DirPkgs map[string]PkgsByName

DirPkgs indexes the packages found in directories by their absolute paths.

type FileGlobalIdShadows

type FileGlobalIdShadows map[string]Shadows

FileGlobalIdShadows holds Shadow values in each file which contains at least one global function/method containing at least one shadow.

It is indexed by file absolute paths.

type FileImportPaths

type FileImportPaths map[string]*cage_strings.Set

FileImportPaths holds paths imported by a single file.

It is indexed by file absolute paths.

type FileImports

type FileImports map[string]PathImport

FileImports describes the packages imported by a file.

It is indexed by source file absolute path.

If x/tools/go/packages.NeedSyntax, the filenames will instead be directory names because the former are not available. Also, Import.UsedName may be inaccurate because the ast.ImportSpec values were not available.

type FileNodes

type FileNodes map[string]Node

FileNodes holds Node values indexed by file absolute paths.

type FilePkgs

type FilePkgs map[string]*Package

FilePkgs holds Package values indexed by file absolute paths.

type FuncDeclShadows

type FuncDeclShadows map[*ast.Ident]FuncDeclWithShadow

type FuncDeclWithShadow

type FuncDeclWithShadow struct {
	// Name is the function/method name. Method names take this form: "<type name>.<method name>".
	Name string
}

FuncDeclWithShadow describes a function/method declaration which contains a parameter and/or receiver identifier which shadows the name of a global.

type GlobalId

type GlobalId struct {
	// Filename is the absolute path to the source file which declared the identifier.
	Filename string

	// PkgName is the package name as declared in the source file which declared the identifier.
	PkgName string

	// PkgPath is the package's import path.
	PkgPath string

	// Name is the global's name.
	Name GlobalIdName
}

func NewGlobalId

func NewGlobalId(pkgPath, pkgName, filename, idName GlobalIdName) GlobalId

func (GlobalId) BaseName

func (i GlobalId) BaseName() string

BaseName returns the right-most section of a Name value, e.g. variable or method name.

It will return an empty string if used on identifiers of init functions and blank identifiers.

func (GlobalId) Dir

func (i GlobalId) Dir() string

func (GlobalId) MethodType

func (i GlobalId) MethodType() string

func (GlobalId) String

func (i GlobalId) String() string

type GlobalIdList

type GlobalIdList struct {
	// contains filtered or unexported fields
}

func NewGlobalIdList

func NewGlobalIdList() *GlobalIdList

func (*GlobalIdList) Add

func (l *GlobalIdList) Add(i ...GlobalId) *GlobalIdList

func (*GlobalIdList) Copy

func (l *GlobalIdList) Copy() *GlobalIdList

Copy returns a shallow copy.

func (*GlobalIdList) Len

func (l *GlobalIdList) Len() int

Len implements sort.Interface.

func (*GlobalIdList) Less

func (l *GlobalIdList) Less(i, j int) bool

Less implements sort.Interface.

func (*GlobalIdList) SortedSlice

func (l *GlobalIdList) SortedSlice() []GlobalId

func (*GlobalIdList) Swap

func (l *GlobalIdList) Swap(i, j int)

Swap implements sort.Interface.

type GlobalIdName

type GlobalIdName = string

GlobalIdName identifies global entities.

Identifier names take these forms:

<const/var/func ast.Ident.Name>
<type name>.<field/method ast.Ident.Name>
init.<source file absolute path>

type GlobalInAstNode

type GlobalInAstNode struct {
	// Ast is the identifier of the global's name.
	Ast ast.Node

	// BlankIdAssignPos is the position of the global in a blank identifier assignment, if applicable.
	BlankIdAssignPos AssignPos
}

GlobalInAstNode describes a global found during an ast.Inspect of an ast.Node.

type GlobalNode

type GlobalNode struct {
	Id          GlobalId
	InspectInfo NodeInspectInfo
}

type GlobalNodes

type GlobalNodes map[ast.Node]IdToGlobalNode

GlobalNodes holds one GlobalNode per identifier declared by the ast.Node.

GenDecl is an example of an ast.Node which can declare multiple identifiers, e.g. types declared in a "type (...)" block. In such examples we store those identifiers in a group in order to support use cases like AST rewriting, specifically node removal, which may require more than simply remove an ast.Ident from the tree but instead modifying and replacing the GenDecl as a whole.

type GlobalRef

type GlobalRef struct {
	// Name is from the global's declaration node.
	Name *ast.Ident

	// Parent is the ast.GenDecl/ast.FuncDecl which contains the Name node.
	Parent ast.Node

	// IsType is true if the global defines/declares a type.
	IsType bool

	// Types holds the declaration-name nodes of inspected types on which the global directly depends.
	//
	// For example, if the global defines a struct, then it will include the inspected types
	// of the fields.
	Types []*ast.Ident
}

GlobalRef describes a global node which is referred to by another, identically named node.

Example:

// ...

type A struct {
  b B
  c C
}
func main() { _ = A{} }

The GlobalRef for the "A" in main would describe the global it refers to, the "A" from `type struct A`. GlobalRef.Types would include the B and C types. IsType would equal true. And Parent would be the ast.GenDecl which contains the type declaration in the syntax tree.

type IdFilenames

type IdFilenames map[string]string

IdFilenames holds file absolute paths.

It is indexed by global identifer name.

type IdToGlobalNode

type IdToGlobalNode map[string]GlobalNode

IdToGlobalNode indexes GlobalNode values by the associated GlobalNode.Id.Name string.

func (IdToGlobalNode) GetByBaseName

func (i IdToGlobalNode) GetByBaseName(name string) *GlobalNode

type IdToNode

type IdToNode map[GlobalIdName]Node

IdToNode holds a Node associated with an identifier.

It is indexed by the global's name (as declared in the source file).

func (IdToNode) Contains

func (m IdToNode) Contains(id string) bool

func (IdToNode) SortedIds

func (m IdToNode) SortedIds() []string

type IdUsedByNode

type IdUsedByNode struct {
	// BlankIdAssignPos describes where the identifier was used in a blank identifier assignment.
	// If it was not found in such an assignment, the value will be NonAssignUsage.
	//
	// It is only populated by full-node queries. Otherwise the value is always NonAssignUsage.
	BlankIdAssignPos AssignPos

	// Name identifies a global ast.Ident.
	Name GlobalIdName

	// IdentInfo describes the identifier itself, the global identifier to which the former refers
	// (which in declarations will be the same node, and the direct/transitive type dependencies.
	IdentInfo *IdentInfo
}

IdUsedByNode describes an identifier found by WalkIdsUsedByNode.

func (IdUsedByNode) Dir

func (i IdUsedByNode) Dir() string

func (IdUsedByNode) GlobalId

func (i IdUsedByNode) GlobalId() GlobalId

type IdUsedByNodeWalkFunc

type IdUsedByNodeWalkFunc func(IdUsedByNode)

IdUsedByNodeWalkFunc defines the input function to WalkIdsUsedByNode.

type IdentContext

type IdentContext struct {
	// ImportQuals holds import paths, indexed by the ast.Ident of the field
	// in a "<import name>.<field>" ast.SelectorExpr.
	ImportQuals map[*ast.Ident]string
}

IdentContext holds contextual details about ast.Ident nodes in the file.

It complement details provided by go/types, such as the package path of an ast.Ident's import name qualifier.

func NewIdentContext

func NewIdentContext(f *ast.File) *IdentContext

NewIdentContext returns contextual details about ast.Ident nodes in the file.

type IdentDecl

type IdentDecl struct {
	// Name is the subject identifier.
	Name *ast.Ident

	// Kind indicates what was declared: const, function, type, or var.
	Kind IdentDeclKind

	// Parent is the parent ast.GenDecl/ast.FuncDecl of the subject identifier.
	Parent ast.Node

	// SpecType is the type expression explicitly selected syntactically to the right
	// of the identifier, inferred from its const iota group, or inferred from the
	// value assigned to it.
	SpecType ast.Expr
}

IdentInfo provides additional information about an ast.Ident node's declaration.

func NewIdentDecl

func NewIdentDecl(parent ast.Node, name *ast.Ident, specType ast.Expr, declKind IdentDeclKind) *IdentDecl

NewIdentDecl creates a new declaration instance and initializes the SpecTypeName and SpecTypeQualifier fields from the input (const/type/var) type expressions.

type IdentDeclKind

type IdentDeclKind string

IdentDeclKind describes the kind of identifier an ast.Ident represents.

const (
	// IdentDeclFunc labels an ast.Ident found in a function declaration.
	IdentDeclFunc IdentDeclKind = "function"

	// IdentDeclValue labels an ast.Ident found in a const/var declaration.
	IdentDeclValue IdentDeclKind = "value"

	// IdentDeclType labels an ast.Ident found in a type declaration.
	IdentDeclType IdentDeclKind = "type"

	// IdentDeclStructField labels an ast.Ident found in a struct field declaration.
	IdentDeclStructField IdentDeclKind = "field"
)

type IdentInfo

type IdentInfo struct {
	// Name is a copy of ast.Ident.Name.
	Name string

	// PkgName is the declared name of the package which contains  he node.
	PkgName string

	// PkgPath is the path of the package which contains the node.
	PkgPath string

	// Position provides source-file location details about the node.
	Position token.Position

	// IsTypeDecl is true if the node names a new type.
	IsTypeDecl bool

	// GlobalRef belongs to the global ast.Ident to which subject node ast.Ident refers.
	GlobalRef *IdentInfo

	// Type provides the node's direct type dependencies on inspected packages.
	//
	// The IdentInfo.Types elements type chains to determine all underlying types which
	// were also loaded by the same Inspector instance.
	//
	// Given "const C T = V", C's IdentInfo.Types would have one element because T is the
	// only direct/initial link in C's type chain.
	//
	// Given "type T1 func(T2, T3)", T2's IdentInfo.Types would have two elements because
	// T2 and T3 are both direct/initial links.
	//
	// If the node is just a use/reference of a type, rather than the declaration, then Type
	// will include the declaration.
	//
	// If the node is a struct field/method, then Type will include the struct type in addition
	// to the types directly used by the individual field/method.
	//
	// TypesString can assist with printing the type chains.
	Types IdentInfoSlice

	// IsCycle is true if the IdentInfo represents the start of a type dependency cycle.
	IsCycle bool
}

IdentInfo provides details about an ast.Ident node loaded by an Inspector.

If it is located in an IdentInfo.Types slice, then it describes the node which declares a type dependency of the subject IdentInfo.

If it is located in an IdentInfo.Types slice, it may also represent the start of a type dependency cycle. In that case, a minimal subset of the fields will be populated in addition to IsCycle: Name, PkgName, and PkgPath. For example, in `type A struct { next *A }`, the Types slice for the declaration node will contain "itself" as a dependency due to the field of the same type. But to avoid infinite walks, the IdentInfo which represents the start of the cycle will have the traits described earlier and no Types elements of its own.

func NewIdentInfo

func NewIdentInfo(i *Inspector, ident *ast.Ident) (*IdentInfo, error)

NewIndentInfo provides location and type information about ast.Ident nodes in inspected packages which declare, or refer to, globals of inspected packages.

IdentInfo will be nil for struct field names in type/struct-literal declarations, but non-nil for inspected type identifiers used in the declarations. IdentInfo will be nil for function/method parameter names, but non-nil for the type identifiers. IdentInfo will be nil for function/method return value names, but non-nil for the type identifiers.

IdentInfo.Types will be non-nil when the node is a const/type/var and the type was declared in an inspected package.

IdentInfo.GlobalRef will be nil in all type chains.

func NewIdentInfoCycle added in v0.1.1

func NewIdentInfoCycle(pkgPath, pkgName, idName string) *IdentInfo

NewIdentInfoCycle creates a value for use in an IdentInfo.Types slice which represents the start of a type dependency cycle.

func (*IdentInfo) Id

func (i *IdentInfo) Id() string

Id returns a string which uniquely identifies the ast.Ident in a build.

Use it instead of IdShort if the absolute path to the source file is necessary.

func (*IdentInfo) IdShort added in v0.1.1

func (i *IdentInfo) IdShort() string

Id returns a string which uniquely identifies the ast.Ident in a build.

Use it instead of Id the absolute path to the source file is unnecessary.

func (*IdentInfo) InspectTypes

func (i *IdentInfo) InspectTypes(fn func(info *IdentInfo, depth int))

InspectTypes traverses the node's type dependencies in depth-first order.

func (*IdentInfo) TypesString

func (i *IdentInfo) TypesString(indent string) string

TypesString returns a tree-like string with all direct/transitive dependencies listed one per line.

Each line is prefixed with a number of the input indentation string equal to the current recursion level.

func (*IdentInfo) UniqueTypes added in v0.1.1

func (i *IdentInfo) UniqueTypes() (s IdentInfoSlice)

UniqueTypes returns the node's unique direct/transitive type dependencies.

type IdentInfoSlice

type IdentInfoSlice []*IdentInfo

func (*IdentInfoSlice) Copy added in v0.1.1

func (t *IdentInfoSlice) Copy() IdentInfoSlice

func (*IdentInfoSlice) Len

func (t *IdentInfoSlice) Len() int

func (*IdentInfoSlice) Less

func (t *IdentInfoSlice) Less(i, j int) bool

func (*IdentInfoSlice) Swap

func (t *IdentInfoSlice) Swap(i, j int)

type Import

type Import struct {
	// Dir is the absolute path of the source directory.
	Dir string

	// DeclName is the package name from the package clause.
	DeclName string

	// UsedName is the package name used in the importer file.
	//
	// By default it will equal DeclName unless initialized by a New* function which
	// has that information, or updated via SetUsedName (e.g. with an ast.ImportSpec.Name.Name).
	UsedName string

	// Path is the import path.
	Path string
}

func NewImportFromPkg

func NewImportFromPkg(p *Package) Import

NewImportFromPkg returns an Import initialized from a golang.org/x/tools/go/packages.Package.

func (*Import) SetUsedName

func (i *Import) SetUsedName(name string)

func (Import) String

func (i Import) String() string

type ImportIdx

type ImportIdx map[string]PkgIdx

ImportIdx provides the first-level index based on import paths.

type ImportList

type ImportList struct {
	// contains filtered or unexported fields
}

func NewImportList

func NewImportList() *ImportList

func (*ImportList) Add

func (l *ImportList) Add(i Import)

func (*ImportList) Copy

func (l *ImportList) Copy() *ImportList

Copy returns a shallow copy.

func (*ImportList) Get

func (l *ImportList) Get(p string) *Import

func (*ImportList) Has

func (l *ImportList) Has(p string) bool

func (*ImportList) Len

func (l *ImportList) Len() int

Len implements sort.Interface.

func (*ImportList) Less

func (l *ImportList) Less(i, j int) bool

Less implements sort.Interface.

func (*ImportList) Paths

func (l *ImportList) Paths() (p []string)

func (*ImportList) Pop

func (l *ImportList) Pop() (i Import)

func (*ImportList) SortedSlice

func (l *ImportList) SortedSlice() []Import

func (*ImportList) Swap

func (l *ImportList) Swap(i, j int)

Swap implements sort.Interface.

type ImportPathGlobalIdNodes

type ImportPathGlobalIdNodes map[string]IdToNode

ImportPathGlobalIdNodes holds a Node for each of a package's identifiers.

It is indexed by import paths.

type InspectFunc

type InspectFunc func(n ast.Node, i NodeInspectInfo) bool

type Inspector

type Inspector struct {
	// BlankImports indexes `import _ "path/to/pkg"` occurrences.
	//
	// It is only populated if the query config includes x/tools/go/packages.NeedSyntax because
	// access to ast.ImportSpec nodes is required to know the import names.
	BlankImports DirImportPaths

	// DotImports indexes `import . "path/to/pkg"` occurrence.
	//
	// It is only populated if the query config includes x/tools/go/packages.NeedSyntax because
	// access to ast.ImportSpec nodes is required to know the import names.
	DotImports DirImportPaths

	// FuncDeclShadows indexes function/method declaration info by parameter and/or receiver identifiers.
	//
	// It supports queries to check if an ast.Ident in a declaration is known to shadow a global.
	FuncDeclShadows FuncDeclShadows

	// FileNodes holds the ast.Node of each file in discovered packages.
	FileNodes FileNodes

	// FilePkgs holds the Package of each file in discovered packages.
	FilePkgs FilePkgs

	// FileSet is the source file set that was parsed as a group during Inspect.
	FileSet *token.FileSet

	// GlobalIdNodes is first indexed by input directory names and then package names at the second level.
	//
	// It provides hierarchical access to the ast.Node of all global identifiers found during PreInspect.
	//
	// Unlike firstPassGlobalIdNames, it includes type methods using the format "<type name>.<method name>".
	//
	// Its leaf Node values may hold types such as ast.GenDecl. Therefore multiple FileNodes keys may
	// return the same Node value.
	//
	// GenDecl is an example of an ast.Node which can declare multiple identifiers, e.g. types
	// declared in a "type (...)" block. In such examples we store those identifiers in a group
	// in order to support use cases like AST rewriting, specifically node removal, which may
	// require more than simply remove an ast.Ident from the tree but instead modifying and
	// replacing the GenDecl as a whole.
	GlobalIdNodes DirGlobalIdNodes

	// ImportPathGlobalIdNodes holds the same node inventory as GlobalIdNodes but indexed by import path
	// instead of dir and package name.
	//
	// It supports cases such as verifying that a global identifier name exists in a package.
	ImportPathGlobalIdNodes ImportPathGlobalIdNodes

	// GlobalIdShadows is first indexed by input directory names and then package names at the second level.
	GlobalIdShadows DirGlobalIdShadows

	// GoFiles holds the files found in each input directory.
	GoFiles dirFiles

	// StdImports indexes Import values for standard library packages directly/transitively imported by
	// directories passed to NewInspector.
	//
	// If x/tools/go/packages.NeedSyntax, the filenames will instead be directory names because the former
	// are not available. Also, Import.UsedName may be inaccurate because the ast.ImportSpec values
	// were not available.
	//
	// Its Import values do not intersect with NonStdImports.
	StdImports DirImports

	// NonStdImports indexes Import values for packages declared in directories passed to NewInspector,
	// or directly/transitively imported by packages in those directories.
	//
	// If x/tools/go/packages.NeedSyntax, the filenames will instead be directory names because the former
	// are not available. Also, Import.UsedName may be inaccurate because the ast.ImportSpec values
	// were not available.
	//
	// Its Import values do not intersect with StdImports.
	NonStdImports DirImports

	// ImportPathToPkg is indexes packages import path.
	ImportPathToPkg map[string]*Package

	// pkgs describes the packages declared in each input directory.
	Pkgs DirPkgs

	// GlobalNodes holds details about AST nodes found in the global scope.
	GlobalNodes GlobalNodes

	// GlobalIdFilenames holds the filename of each global identifier declaration.
	GlobalIdFilenames PkgFilenames

	// UnsupportedTraits holds detected code traits which are not supported and may
	// cause the inspection results to be incorrect/incomplete.
	//
	// Instances of these traits are collected, instead of emitted in errors, to allow the
	// client to decide how to proceed based on its own needs.
	UnsupportedTraits []UnsupportedTrait
	// contains filtered or unexported fields
}

func NewInspector

func NewInspector(loadConfig *Config, dirs ...string) *Inspector

NewInspector analyzes the packages found in the input directories.

func (*Inspector) AddDir

func (i *Inspector) AddDir(dirs ...string) bool

AddDir appends the list of directories initialized by NewInspector.

It returns true if at least one input directory is new/unique to the list.

It supports incremental expansion of results, such as GlobalIdNodes, after additional Inspect calls.

func (*Inspector) BlankImportsInFile

func (i *Inspector) BlankImportsInFile(dir, pkgName, file string) *cage_strings.Set

func (*Inspector) DotImportsInFile

func (i *Inspector) DotImportsInFile(dir, pkgName, file string) *cage_strings.Set

func (*Inspector) FindAstNode

func (i *Inspector) FindAstNode(n ast.Node) (_ *Package, _ *ast.File, filename string)

FindAstNode returns location details about the package/file which contains the node.

func (*Inspector) FindGenDeclIdent

func (i *Inspector) FindGenDeclIdent(g *ast.GenDecl, identName string) *IdentDecl

FindGenDeclIdent searches for an ast.Ident declaration with the input name.

If the name is not found, the returned ast.Ident pointer is nil.

func (*Inspector) FindGlobalInAstNode

func (i *Inspector) FindGlobalInAstNode(node ast.Node, idName GlobalIdName) (queue []GlobalInAstNode, _ error)

func (*Inspector) FindPkgGlobal

func (i *Inspector) FindPkgGlobal(pkgPath, idName GlobalIdName) (identDecl *IdentDecl)

FindPkgGlobal returns the ast.FuncDecl or ast.GenDecl which contains the global's declaration and an IdentDecl which further describes the latter.

func (*Inspector) FindPos

func (i *Inspector) FindPos(query token.Pos) (*Package, token.Position)

FindPos returns location details of the token.Pos.

func (*Inspector) FuncDeclTypeNames

func (i *Inspector) FuncDeclTypeNames(n *ast.FuncDecl) []*ast.Ident

FuncDeclTypeNames returns each type name ast.Ident found in the declaration which refers to a global of an inspected package.

func (*Inspector) GenDeclSpecTypeNames

func (i *Inspector) GenDeclSpecTypeNames(t ast.Expr) []*ast.Ident

GenDeclSpecTypeNames returns each type name ast.Ident found in the declaration which refers to a global of an inspected package.

func (*Inspector) GlobalIdNode

func (i *Inspector) GlobalIdNode(dir, pkgName, idName GlobalIdName) (Node, error)

GlobalIdNode returns the associated Node.

func (*Inspector) GlobalIdsUsedByGlobal

func (i *Inspector) GlobalIdsUsedByGlobal(dir, pkgName, idName GlobalIdName) (usedMap map[string]IdUsedByNode, errs []error)

GlobalIdsUsedByGlobal returns the set of global identifiers used by the target global node.

The set is indexed by GlobalId.String() values.

func (*Inspector) GlobalImportPaths

func (i *Inspector) GlobalImportPaths(f *ast.File) []string

GlobalImportPaths returns all import paths of packages whose globals were imported into the file via dot- or non-blank-named import. It returns the path count.

func (*Inspector) GlobalRefsInNode

func (i *Inspector) GlobalRefsInNode(subject ast.Node) (idents []*ast.Ident)

GlobalRefsInNode returns all ast.Ident nodes, found in the subject node's AST, which refer to another identifier in the global scope.

func (*Inspector) IdentContext

func (i *Inspector) IdentContext(f *ast.File) *IdentContext

IdentContext returns the IdentContext of the input file.

func (*Inspector) IdentObjectOf

func (i *Inspector) IdentObjectOf(pkgPath string, file *ast.File, ident *ast.Ident) (_ types.Object, typePkgPath, typeName string)

IdentObjectOf searches for the inspected-type details of an ast.Ident, evaluating its own package/file and also the packages imported into file.

func (*Inspector) Inspect

func (i *Inspector) Inspect() []error

Inspect analyzes the packages in the directories passed to NewInspector, populates records such as GlobalIdNodes, and returns errors such as unsupported identifier shadowing.

func (*Inspector) NodeToFilename

func (i *Inspector) NodeToFilename(n ast.Node) string

func (*Inspector) NodeToString

func (i *Inspector) NodeToString(n ast.Node) string

func (*Inspector) PackagesUsedByNode

func (i *Inspector) PackagesUsedByNode(dir, pkgName string, nodes ...ast.Node) (pkgsByName map[string]PackageUsedByNode, pkgsByPath map[string]PackageUsedByNode, errs []error)

PackagesUsedByNode returns the set of packages, indexed by import name, used in the input nodes.

func (*Inspector) Reset

func (i *Inspector) Reset(dirs ...string) *Inspector

Reset is equivalent to NewInspector except that the package caches are retained.

func (*Inspector) ResolveGlobalRef added in v0.1.1

func (i *Inspector) ResolveGlobalRef(identPkg *Package, identFile *ast.File, ident *ast.Ident, declPkgPath string) (*GlobalRef, error)

ResolveGlobalRef returns details about the global to which the input ast.Ident refers.

func (*Inspector) SearchDotImportedGlobals

func (i *Inspector) SearchDotImportedGlobals(file *ast.File, identName string) (match *Package)

SearchDotImportedGlobals returns the dot-imported package which exports an identifier with the input name.

If the identifier is not found in any of the packages, both return values will be nil.

func (*Inspector) SetPackageCache

func (i *Inspector) SetPackageCache(c *Cache) *Inspector

func (*Inspector) WalkGlobalIdsUsedByGlobal

func (i *Inspector) WalkGlobalIdsUsedByGlobal(dir, pkgName, idName GlobalIdName, walkFn IdUsedByNodeWalkFunc) (errs []error)

WalkGlobalIdsUsedByGlobal provides walkFn with every global identifier used in the target global node.

func (*Inspector) WalkIdsUsedByGlobal

func (i *Inspector) WalkIdsUsedByGlobal(dir, pkgName, idName GlobalIdName, walkFn IdUsedByNodeWalkFunc) (errs []error)

WalkIdsUsedByGlobal provides walkFn with every identifier used in the target node.

type Node

type Node struct {
	Ast         ast.Node
	InspectInfo NodeInspectInfo
}

type NodeInspectInfo

type NodeInspectInfo struct {
	Dirname     string
	Filename    string
	GlobalScope bool

	// GlobalFuncName is name of the node's parent function or method.
	GlobalFuncName string

	// GlobalTypeName is name of the node's parent `type` declration.
	//
	// It differs from GlobalMethodTypeName which is only for method body nodes.
	GlobalTypeName string

	// InitFuncPos is -1 if the node is not an init function, otherwise it is the 0-indexed position
	// in the file among the other init functions (if any).
	InitFuncPos int

	PkgName string
	PkgPath string

	// IotaValuedNames holds the names of identifers in an ast.GenDecl which are iota-valued constants.
	IotaValuedNames *cage_strings.Set

	// NonStdImports is a copy of Inspector.NonStdImports[NodeInspectInfo.Dirname][NodeInspectInfo.PkgName].
	//
	// It is indexed by import paths.
	NonStdImports map[string]Import

	// MethodType holds the name of the parent type for all nodes inside a method body.
	//
	// If differs from the GlobalTypeName which is only for nodes in a `type` declaration.
	GlobalMethodTypeName string
}

func NewNodeInspectInfo

func NewNodeInspectInfo() NodeInspectInfo

type OnHitFunc

type OnHitFunc func(CacheHit)

OnHitFunc receives information about Cache hits.

type OnMissFunc

type OnMissFunc func(CacheMiss)

OnMissFunc receives information about Cache misses.

type Package

type Package struct {
	*std_packages.Package

	// Dir is derived from x/tools/go/packages.Package.GoFiles[0]
	Dir string

	// FileToName provides a mapping from ast.File pointers, returned by Load*, to the source filenames.
	FileToName map[*ast.File]string

	ImportPaths *cage_strings.Set

	// ImportPathToDir maps import paths to absolute paths of source directories.
	ImportPathToDir map[string]string

	// Goroot is true if the package is located under GOROOT.
	Goroot bool

	// Vendor is true if the package is located under a vendor directory.
	Vendor bool
}

func (*Package) IdentTypesObj

func (p *Package) IdentTypesObj(ident *ast.Ident) types.Object

type PackageUsedByNode

type PackageUsedByNode struct {
	Name string
	Path string
}

PackageUsedByNode describes an package found by PackagesUsedByNode

Other details, like the dependent nodes, may be added later as needed.

type PackageUsedByNodeWalkFunc

type PackageUsedByNodeWalkFunc func(PackageUsedByNode)

PackageUsedByNodeWalkFunc receives one PackageUsedByNode per discovered dependency.

type PathImport

type PathImport map[string]Import

PathImport describes a package imported by a file.

It is indexed by import path.

type PkgFilenames

type PkgFilenames map[string]IdFilenames

PkgFilenames holds per-package global identifier filenames.

It is indexed by import paths.

type PkgGlobalIdNodes

type PkgGlobalIdNodes map[string]IdToNode

PkgGlobalIdNodes holds a Node for each of a package's identifiers.

It is indexed by package name (as declared in the source file).

func (PkgGlobalIdNodes) SortedPkgNames

func (n PkgGlobalIdNodes) SortedPkgNames() []string

SortedPkgNames returns the map's keys in sorted order.

type PkgGlobalIdShadows

type PkgGlobalIdShadows map[string]FileGlobalIdShadows

PkgGlobalIdShadows holds Shadow values in each package which contains at least one global function/method containing at least one shadow.

It is indexed by package name (as declared in the source file).

type PkgIdx

type PkgIdx map[std_packages.LoadMode]CacheValue

PkgIdx provides the second-level and final index based on LoadMode values. Any LoadMode key which can satisfy the query's bit flags, either exactly or as a superset, contains a cached Package with sufficient data for the query.

type PkgImportPaths

type PkgImportPaths map[string]FileImportPaths

PkgImportPaths holds packages' per-file import path sets.

It is indexed by package name (as declared in the source file).

type PkgImports

type PkgImports map[string]FileImports

PkgImports describes the packages imported by another package.

It is indexed by package name (as declared in the source file).

type PkgsByImportPath

type PkgsByImportPath PkgsByString

PkgsByImportPath indexes packages by import paths.

func LoadWithConfig

func LoadWithConfig(cfg *Config, patterns ...string) (pkgMap PkgsByImportPath, errs []error)

LoadWithConfig wraps x/tools/go/packages.Load to address some common-case needs such as returning all encountered errors and all available package information.

The packages returned are indexed by the import path of the package.

The errors returned will include all x/tools/go/packages.Package.[]Errors, if any, each wrapped with a message indicating its origin package. In that event, the Package map is also returned from which the same per-Package errors are available.

func (PkgsByImportPath) SortedPkgPaths

func (p PkgsByImportPath) SortedPkgPaths() []string

SortedPkgPaths returns the map's keys in sorted order.

type PkgsByName

type PkgsByName PkgsByString

PkgsByName indexes packages by names as they appear in the package clause.

func (PkgsByName) SortedPkgNames

func (p PkgsByName) SortedPkgNames() []string

SortedPkgNames returns the map's keys in sorted order.

type PkgsByString

type PkgsByString map[string]*Package

PkgsByString indexes packages by a string key such as import path.

type Shadows

type Shadows map[string]*cage_strings.Set

Shadows contains the names of global identifiers which are shadowed in a global function/method.

It is indexed by names of of global functions/methods.

type TraitType

type TraitType string
const (
	// TraitDotImport rationale:
	//
	// It's unknown whether their usage is common enough to justify updating the
	// global-usage-related code to ensure that if there a package which is imported
	// only for initialization, then ensure its globals and also its transitive dependencies
	// are all inspected.
	TraitDotImport TraitType = "dot import name"

	// TraitDuplicateImport rationale:
	//
	// Allowing duplicates would complicate import pruning which follows global declaration pruning
	// because the usage of all import names would need to be tracked, and only the ast.ImportSpec
	// referring to the unused import name(s) would be eligible for pruning. Also, this trait
	// is reasonably considered lint and a potential source of bugs.
	TraitDuplicateImport TraitType = "multiple imports with the same path"
)

type UnsupportedTrait

type UnsupportedTrait struct {
	// Type identifies the trait, e.g. blank identifier.
	Type TraitType

	// FileOrDir is the site's filename if possible, otherwise its directory.
	FileOrDir string

	// PkgPath is the site's import path
	PkgPath string

	// Msg provides additional detail specific to the trait.
	Msg string
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL