scanner

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2025 License: MIT Imports: 13 Imported by: 9

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ResolutionPathKey = resolutionPathKey{}
	LoggerKey         = loggerKey{}
	InspectKey        = inspectKey{}
)

Public context keys to be used by packages like goscan.

Functions

This section is empty.

Types

type ConstantInfo

type ConstantInfo struct {
	Name       string
	FilePath   string // Added: Absolute path to the file where this const is defined
	Doc        string
	Type       *FieldType // Changed from string to *FieldType
	Value      string
	RawValue   string   // The raw, unquoted string value, if the constant is a string.
	IsExported bool     // Added to indicate if the constant is exported
	Node       ast.Node // Added: AST node for position, if needed, though FilePath is primary
	ConstVal   constant.Value
	IotaValue  int // The value of iota for the spec this constant was in.
	ValExpr    ast.Expr
}

ConstantInfo represents a single top-level constant declaration.

type ExternalTypeOverride

type ExternalTypeOverride map[string]*TypeInfo

ExternalTypeOverride defines a mapping from a fully qualified type name (e.g., "time.Time") to a pre-defined TypeInfo struct. This allows users to provide a "synthetic" type definition for certain types, bypassing the need for the scanner to parse them from source. This is particularly useful for standard library types that can cause issues when scanned from within a test binary, or for any type where manual definition is preferred. The key is the fully qualified type name (ImportPath + "." + TypeName). The value is a pointer to a scanner.TypeInfo struct that defines the type.

type FieldInfo

type FieldInfo struct {
	Name       string
	Doc        string
	Type       *FieldType
	Tag        string
	Embedded   bool
	IsExported bool // True if the field is exported (starts with an uppercase letter).
}

FieldInfo represents a single field in a struct or a parameter/result in a function.

func (*FieldInfo) TagValue

func (fi *FieldInfo) TagValue(tagName string) string

TagValue extracts the value associated with the given tagName from the struct tag. If the tag value contains a comma (e.g., "name,omitempty"), only the part before the comma is returned. Returns an empty string if the tag is not present or malformed.

type FieldType

type FieldType struct {
	Name         string       `json:"name"`
	PkgName      string       `json:"pkgName,omitempty"` // e.g., "json", "models"
	MapKey       *FieldType   `json:"mapKey,omitempty"`  // For map types
	Elem         *FieldType   `json:"elem,omitempty"`    // For slice, map, pointer, array types
	IsPointer    bool         `json:"isPointer,omitempty"`
	IsSlice      bool         `json:"isSlice,omitempty"`
	IsMap        bool         `json:"isMap,omitempty"`
	IsTypeParam  bool         `json:"isTypeParam,omitempty"`  // True if this FieldType refers to a type parameter
	IsConstraint bool         `json:"isConstraint,omitempty"` // True if this FieldType represents a type constraint
	TypeArgs     []*FieldType `json:"typeArgs,omitempty"`     // For instantiated generic types, e.g., T in List[T]

	Definition         *TypeInfo `json:"-"` // Caches the resolved type definition. Avoid cyclic JSON.
	IsResolvedByConfig bool      `json:"isResolvedByConfig,omitempty"`
	IsBuiltin          bool      `json:"isBuiltin,omitempty"`

	// Resolver, FullImportPath, and TypeName are used for on-demand package scanning.
	// They are exported to allow consumers of the library to construct a resolvable
	// FieldType manually, for instance when parsing type information from an
	// annotation rather than from a Go AST node.
	Resolver       PackageResolver `json:"-"` // For lazy-loading the type definition.
	FullImportPath string          `json:"-"` // Full import path of the type, e.g., "example.com/project/models".
	TypeName       string          `json:"-"` // The name of the type within its package, e.g., "User".
	CurrentPkg     *PackageInfo    `json:"-"` // Reference to the package where this type is used.
}

FieldType represents the type of a field.

func (*FieldType) Resolve

func (ft *FieldType) Resolve(ctx context.Context) (*TypeInfo, error)

func (*FieldType) SetResolver

func (ft *FieldType) SetResolver(r PackageResolver)

SetResolver is a test helper to overwrite the internal resolver.

func (*FieldType) String

func (ft *FieldType) String() string

String returns the Go string representation of the field type. e.g., "*pkgname.MyType", "[]string", "map[string]int", "MyType[string]"

type FunctionInfo

type FunctionInfo struct {
	Name       string           `json:"name"`
	FilePath   string           `json:"filePath"`
	Doc        string           `json:"doc,omitempty"`
	Receiver   *FieldInfo       `json:"receiver,omitempty"`
	TypeParams []*TypeParamInfo `json:"typeParams,omitempty"` // For generic functions
	Parameters []*FieldInfo     `json:"parameters,omitempty"`
	Results    []*FieldInfo     `json:"results,omitempty"`
	IsVariadic bool             `json:"isVariadic,omitempty"`
	AstDecl    *ast.FuncDecl    `json:"-"` // Avoid cyclic JSON.
}

FunctionInfo represents a single top-level function or method declaration.

type InterfaceInfo

type InterfaceInfo struct {
	Methods []*MethodInfo
}

InterfaceInfo represents an interface type.

type Kind

type Kind int

Kind defines the category of a type definition.

const (
	StructKind Kind = iota
	AliasKind
	FuncKind
	InterfaceKind
)

type MethodInfo

type MethodInfo struct {
	Name       string
	Parameters []*FieldInfo
	Results    []*FieldInfo
}

MethodInfo represents a single method in an interface.

type Overlay

type Overlay map[string][]byte

Overlay provides a way to replace the contents of a file with alternative content. The key is either a project-relative path (from the module root) or a Go package path concatenated with a file name.

type PackageImports

type PackageImports struct {
	Name        string
	ImportPath  string
	Imports     []string
	FileImports map[string][]string // file path -> import paths
}

PackageImports holds the minimal information about a package's direct imports.

type PackageInfo

type PackageInfo struct {
	Name       string
	Path       string
	ImportPath string // Added: Canonical import path of the package
	ModulePath string // The go module path this package belongs to.
	ModuleDir  string // The absolute path to the module's root directory
	Files      []string
	Types      []*TypeInfo
	Constants  []*ConstantInfo
	Variables  []*VariableInfo
	Functions  []*FunctionInfo
	Fset       *token.FileSet       // Added: Fileset for position information
	AstFiles   map[string]*ast.File // Added: Parsed AST for each file
	// contains filtered or unexported fields
}

PackageInfo holds all the extracted information from a single package.

func (*PackageInfo) Lookup

func (p *PackageInfo) Lookup(name string) *TypeInfo

Lookup finds a type by name in the package.

type PackageResolver

type PackageResolver interface {
	ScanPackageByImport(ctx context.Context, importPath string) (*PackageInfo, error)
}

PackageResolver is an interface that can resolve an import path to a package definition. It is implemented by the top-level typescanner.Scanner to enable lazy, cached lookups.

type Scanner

type Scanner struct {
	ExternalTypeOverrides ExternalTypeOverride
	Overlay               Overlay
	// contains filtered or unexported fields
}

Scanner parses Go source files within a package.

func New

func New(fset *token.FileSet, overrides ExternalTypeOverride, overlay Overlay, modulePath string, moduleRootDir string, resolver PackageResolver, inspect bool, logger *slog.Logger) (*Scanner, error)

New creates a new Scanner.

func (*Scanner) BuildImportLookup added in v0.0.2

func (s *Scanner) BuildImportLookup(file *ast.File) map[string]string

BuildImportLookup creates a map of local import names to their full package paths.

func (*Scanner) FileSet added in v0.0.2

func (s *Scanner) FileSet() *token.FileSet

FileSet returns the underlying token.FileSet used by the scanner.

func (*Scanner) ResolveType

func (s *Scanner) ResolveType(ctx context.Context, fieldType *FieldType) (*TypeInfo, error)

ResolveType starts the type resolution process for a given field type.

func (*Scanner) ScanFiles

func (s *Scanner) ScanFiles(ctx context.Context, filePaths []string, pkgDirPath string) (*PackageInfo, error)

ScanFiles parses a specific list of .go files and returns PackageInfo.

func (*Scanner) ScanFilesWithKnownImportPath

func (s *Scanner) ScanFilesWithKnownImportPath(ctx context.Context, filePaths []string, pkgDirPath string, canonicalImportPath string) (*PackageInfo, error)

ScanFilesWithKnownImportPath parses files with a predefined import path.

func (*Scanner) ScanPackageByImport

func (s *Scanner) ScanPackageByImport(ctx context.Context, importPath string) (*PackageInfo, error)

ScanPackageByImport makes scanner.Scanner implement the PackageResolver interface.

func (*Scanner) ScanPackageImports

func (s *Scanner) ScanPackageImports(ctx context.Context, filePaths []string, pkgDirPath string, canonicalImportPath string) (*PackageImports, error)

ScanPackageImports parses only the import declarations from a set of Go files.

func (*Scanner) TypeInfoFromExpr added in v0.0.2

func (s *Scanner) TypeInfoFromExpr(ctx context.Context, expr ast.Expr, currentTypeParams []*TypeParamInfo, info *PackageInfo, importLookup map[string]string) *FieldType

TypeInfoFromExpr resolves an AST expression that represents a type into a FieldType. This is the core type-parsing logic, exposed for tools that need to resolve type information dynamically.

type StructInfo

type StructInfo struct {
	Fields []*FieldInfo
}

StructInfo represents a struct type.

type TypeInfo

type TypeInfo struct {
	Name       string           `json:"name"`
	PkgPath    string           `json:"pkgPath"`
	FilePath   string           `json:"filePath"`
	Doc        string           `json:"doc,omitempty"`
	Kind       Kind             `json:"kind"`
	TypeParams []*TypeParamInfo `json:"typeParams,omitempty"` // For generic types
	Node       ast.Node         `json:"-"`                    // Avoid cyclic JSON with Node itself.
	Struct     *StructInfo      `json:"struct,omitempty"`
	Func       *FunctionInfo    `json:"func,omitempty"` // For type alias to func type
	Interface  *InterfaceInfo   `json:"interface,omitempty"`
	Underlying *FieldType       `json:"underlying,omitempty"` // For alias types

	// --- Fields for Enum-like patterns ---
	IsEnum      bool            `json:"isEnum,omitempty"`      // True if this type is identified as an enum
	EnumMembers []*ConstantInfo `json:"enumMembers,omitempty"` // List of constants belonging to this enum type

	// --- Fields for inspect mode ---
	Inspect           bool            `json:"-"` // Flag to enable inspection logging
	Logger            *slog.Logger    `json:"-"` // Logger for inspection
	Fset              *token.FileSet  `json:"-"` // Fileset for position information
	ResolutionContext context.Context `json:"-"` // Context for resolving nested types
}

TypeInfo represents a single type declaration (`type T ...`).

func (*TypeInfo) Annotation

func (ti *TypeInfo) Annotation(name string) (value string, ok bool)

Annotation extracts the value of a specific annotation from the TypeInfo's Doc string. Annotations are expected to be in the format "@<name>[:<value>]" or "@<name> <value>". If inspect mode is enabled, it logs the checking process.

type TypeParamInfo

type TypeParamInfo struct {
	Name       string     `json:"name"`
	Constraint *FieldType `json:"constraint,omitempty"`
}

TypeParamInfo stores information about a single type parameter.

type VariableInfo

type VariableInfo struct {
	Name       string
	FilePath   string
	Doc        string
	Type       *FieldType
	IsExported bool
	Node       ast.Node
}

VariableInfo represents a single top-level variable declaration.

type Visitor

type Visitor interface {
	// Visit is called for each package discovered during the walk.
	// It can inspect the package's imports and return the list of
	// imports that the walker should follow next. Returning an empty
	// slice stops the traversal from that node.
	Visit(pkg *PackageImports) (importsToFollow []string, err error)
}

Visitor defines the interface for operations to be performed at each node during a dependency graph walk.

Jump to

Keyboard shortcuts

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