analysis

package
v0.0.0-...-40e5a00 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ASTExprToString

func ASTExprToString(expr ast.Expr) string

ASTExprToString converts an AST type expression to its string representation.

func ComputeImportPath

func ComputeImportPath(ws *types.Workspace, fsPath string) string

ComputeImportPath computes the Go import path for a package given its filesystem path.

func FindFuncDeclByName

func FindFuncDeclByName(astFile *ast.File, name string) *ast.FuncDecl

FindFuncDeclByName finds a function or method declaration by name, supporting Type.Method syntax.

func MatchesReceiverType

func MatchesReceiverType(expr ast.Expr, typeName string) bool

MatchesReceiverType checks if a receiver type expression matches a given type name.

Types

type CacheSize

type CacheSize struct {
	ResolvedRefs   int
	MethodSets     int
	PackageSymbols int
}

CacheSize represents the current size of caches

type CacheStats

type CacheStats struct {
	ResolvedRefHits      int64
	ResolvedRefMisses    int64
	MethodSetHits        int64
	MethodSetMisses      int64
	PackageHits          int64
	PackageMisses        int64
	IdentifierTypeHits   int64 // NEW
	IdentifierTypeMisses int64 // NEW
	MethodTypeMapHits    int64 // NEW
	MethodTypeMapMisses  int64 // NEW
	LastReset            time.Time
}

CacheStats tracks cache performance metrics

type DependencyAnalyzer

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

DependencyAnalyzer analyzes package and symbol dependencies

func NewDependencyAnalyzer

func NewDependencyAnalyzer(ws *types.Workspace, logger *slog.Logger) *DependencyAnalyzer

func (*DependencyAnalyzer) AnalyzeImpact

func (da *DependencyAnalyzer) AnalyzeImpact(op types.Operation) (*types.ImpactAnalysis, error)

AnalyzeImpact analyzes impact of a potential change

func (*DependencyAnalyzer) BuildDependencyGraph

func (da *DependencyAnalyzer) BuildDependencyGraph() (*types.DependencyGraph, error)

BuildDependencyGraph builds complete dependency graph for workspace

func (*DependencyAnalyzer) DetectCycles

func (da *DependencyAnalyzer) DetectCycles() ([][]string, error)

DetectCycles detects import cycles in package graph

type DiagnosticEngine

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

DiagnosticEngine provides enhanced error reporting with suggestions

func NewDiagnosticEngine

func NewDiagnosticEngine(resolver *SymbolResolver) *DiagnosticEngine

func (*DiagnosticEngine) AnalyzeImportError

func (de *DiagnosticEngine) AnalyzeImportError(packagePath string, file *types.File) *ResolutionError

AnalyzeImportError provides analysis for import-related errors

func (*DiagnosticEngine) AnalyzeResolutionFailure

func (de *DiagnosticEngine) AnalyzeResolutionFailure(ident *ast.Ident, file *types.File, originalError error) *ResolutionError

AnalyzeResolutionFailure provides detailed analysis when symbol resolution fails

func (*DiagnosticEngine) AnalyzeTypeError

func (de *DiagnosticEngine) AnalyzeTypeError(symbol *types.Symbol, expectedKind types.SymbolKind) *ResolutionError

AnalyzeTypeError provides analysis for type-related errors

func (*DiagnosticEngine) AnalyzeVisibilityError

func (de *DiagnosticEngine) AnalyzeVisibilityError(symbol *types.Symbol, accessingPackage string) *ResolutionError

AnalyzeVisibilityError provides analysis for visibility-related errors

type FuncParam

type FuncParam struct {
	Name string
	Type string
}

FuncParam represents a function parameter with name and type.

func ExtractFuncParams

func ExtractFuncParams(ws *types.Workspace, sourceFile, functionName string) ([]FuncParam, error)

ExtractFuncParams finds a function declaration in the workspace and returns its current parameters.

type GoParser

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

Parser handles Go code parsing and AST management

func NewParser

func NewParser(logger *slog.Logger) *GoParser

func (*GoParser) EnsureTypeChecked

func (p *GoParser) EnsureTypeChecked(ws *types.Workspace, pkg *types.Package)

EnsureTypeChecked runs type-checking on a package if it hasn't been done yet. This enables lazy/on-demand type-checking instead of eager upfront checking.

func (*GoParser) ParseFile

func (p *GoParser) ParseFile(filename string) (*types.File, error)

ParseFile parses a single Go file

func (*GoParser) ParsePackage

func (p *GoParser) ParsePackage(dir string) (*types.Package, error)

ParsePackage parses all Go files in a package directory

func (*GoParser) ParseWorkspace

func (p *GoParser) ParseWorkspace(rootPath string) (*types.Workspace, error)

ParseWorkspace parses an entire Go workspace/module. Package directories are discovered sequentially, then parsed in parallel using a bounded worker pool (runtime.NumCPU goroutines).

func (*GoParser) TypeCheckPackage

func (p *GoParser) TypeCheckPackage(ws *types.Workspace, pkg *types.Package)

TypeCheckPackage runs go/types type-checking on a package. Results are stored in pkg.TypesInfo and pkg.TypesPkg. Errors are silently ignored — packages that fail type-checking will have nil TypesInfo and fall back to AST-based inference.

func (*GoParser) UpdateFile

func (p *GoParser) UpdateFile(file *types.File) error

UpdateFile updates AST after file modifications

type ReferenceIndex

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

ReferenceIndex maps identifier names to all their occurrences across the workspace. The workspaceIndex provides O(1) lookups by types.Object pointer identity when type information is available, using varint-compressed cursor indexes for ~10x memory reduction vs the previous objectIndex.

func (*ReferenceIndex) NameEntries

func (idx *ReferenceIndex) NameEntries(name string) ([]indexEntry, bool)

NameEntries returns all name index entries for a given identifier name.

func (*ReferenceIndex) ObjectEntries

func (idx *ReferenceIndex) ObjectEntries(obj gotypes.Object) []objectEntry

ObjectEntries returns all entries for a given types.Object via the workspaceIndex. Returns nil if the workspace index is not populated or the object is not found.

type ResolutionContext

type ResolutionContext struct {
	ScopeKind        ScopeKind
	AvailableSymbols []string // Symbols available in current scope
	NearbySymbols    []string // Symbols in nearby scopes
	ImportedPackages []string // Available imported packages
	ParentFunction   string   // Name of containing function if applicable
	Line             int      // Line number where resolution failed
	Column           int      // Column number where resolution failed
}

ResolutionContext provides additional context about where resolution failed

type ResolutionError

type ResolutionError struct {
	*types.RefactorError
	Suggestions []string
	Context     *ResolutionContext
	Similar     []*types.Symbol // Similar symbols that might have been intended
}

ResolutionError represents an enhanced error with suggestions and context

func (*ResolutionError) Error

func (re *ResolutionError) Error() string

Error implements the error interface

func (*ResolutionError) FormatError

func (re *ResolutionError) FormatError() string

FormatError returns a nicely formatted error message with suggestions

type Scope

type Scope struct {
	Kind     ScopeKind
	Node     ast.Node                 // AST node that creates this scope
	Parent   *Scope                   // Parent scope
	Children []*Scope                 // Child scopes
	Symbols  map[string]*types.Symbol // Symbols defined in this scope
	Start    token.Pos                // Start position of scope
	End      token.Pos                // End position of scope
}

Scope represents a lexical scope in Go code

type ScopeAnalyzer

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

ScopeAnalyzer handles lexical scope analysis and symbol resolution within scopes

func NewScopeAnalyzer

func NewScopeAnalyzer(resolver *SymbolResolver) *ScopeAnalyzer

func (*ScopeAnalyzer) BuildScopeTree

func (sa *ScopeAnalyzer) BuildScopeTree(file *types.File) (*Scope, error)

BuildScopeTree builds the complete scope tree for a file

func (*ScopeAnalyzer) ClearCache

func (sa *ScopeAnalyzer) ClearCache()

ClearCache clears all cached scopes

func (*ScopeAnalyzer) FindInLocalScope

func (sa *ScopeAnalyzer) FindInLocalScope(name string, scope *Scope) (*types.Symbol, error)

FindInLocalScope searches for a symbol in the immediate local scope

func (*ScopeAnalyzer) GetIdentifierType

func (sa *ScopeAnalyzer) GetIdentifierType(identName string, file *types.File, pos token.Pos) *types.Symbol

GetIdentifierType resolves the type of an identifier at a given position in a file. This uses direct AST walking to avoid scope analysis position-matching issues.

func (*ScopeAnalyzer) GetScopeAt

func (sa *ScopeAnalyzer) GetScopeAt(file *types.File, pos token.Pos) (*Scope, error)

GetScopeAt returns the scope at a specific position

func (*ScopeAnalyzer) InvalidateCache

func (sa *ScopeAnalyzer) InvalidateCache(filePath string)

InvalidateCache clears the scope cache for a file

func (*ScopeAnalyzer) ResolveInScope

func (sa *ScopeAnalyzer) ResolveInScope(ident *ast.Ident, file *types.File, pos token.Pos) (*types.Symbol, error)

ResolveInScope resolves an identifier within its lexical scope

type ScopeKind

type ScopeKind int
const (
	UniverseScope ScopeKind = iota // Built-in identifiers
	PackageScope                   // Package-level declarations
	FileScope                      // File-level imports and declarations
	FunctionScope                  // Function parameters and body
	BlockScope                     // Block statements
	TypeScope                      // Type parameter scope (for generics)
)

func (ScopeKind) String

func (sk ScopeKind) String() string

String returns the string representation of a ScopeKind

type SymbolCache

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

SymbolCache provides efficient caching for symbol resolution operations

func NewSymbolCache

func NewSymbolCache() *SymbolCache

NewSymbolCache creates a new symbol cache

func (*SymbolCache) CleanupStaleEntries

func (c *SymbolCache) CleanupStaleEntries()

CleanupStaleEntries removes old cache entries (not implemented in this basic version) In a production system, this could remove entries based on last access time

func (*SymbolCache) Clear

func (c *SymbolCache) Clear()

Clear removes all cache entries

func (*SymbolCache) GetCacheSize

func (c *SymbolCache) GetCacheSize() CacheSize

GetCacheSize returns the current size of all caches

func (*SymbolCache) GetHitRate

func (c *SymbolCache) GetHitRate() float64

GetHitRate returns the overall cache hit rate as a percentage

func (*SymbolCache) GetIdentifierType

func (c *SymbolCache) GetIdentifierType(key string) *types.Symbol

GetIdentifierType retrieves a cached identifier type resolution

func (*SymbolCache) GetMemoryUsage

func (c *SymbolCache) GetMemoryUsage() int64

GetMemoryUsage estimates memory usage (basic implementation)

func (*SymbolCache) GetMethodSet

func (c *SymbolCache) GetMethodSet(key string) []*types.Symbol

GetMethodSet retrieves a cached method set

func (*SymbolCache) GetMethodSetHitRate

func (c *SymbolCache) GetMethodSetHitRate() float64

GetMethodSetHitRate returns the hit rate for method sets

func (*SymbolCache) GetMethodTypeMapping

func (c *SymbolCache) GetMethodTypeMapping(key string) (bool, bool)

GetMethodTypeMapping retrieves a cached method-to-type mapping

func (*SymbolCache) GetPackageHitRate

func (c *SymbolCache) GetPackageHitRate() float64

GetPackageHitRate returns the hit rate for package symbols

func (*SymbolCache) GetPackageSymbols

func (c *SymbolCache) GetPackageSymbols(packagePath string) *types.SymbolTable

GetPackageSymbols retrieves a cached package symbol table

func (*SymbolCache) GetResolvedRef

func (c *SymbolCache) GetResolvedRef(key string) *types.Symbol

GetResolvedRef retrieves a cached resolved symbol reference

func (*SymbolCache) GetResolvedRefHitRate

func (c *SymbolCache) GetResolvedRefHitRate() float64

GetResolvedRefHitRate returns the hit rate for resolved references

func (*SymbolCache) GetStats

func (c *SymbolCache) GetStats() CacheStats

GetStats returns current cache statistics

func (*SymbolCache) InvalidateFile

func (c *SymbolCache) InvalidateFile(filePath string)

InvalidateFile removes cache entries related to a specific file

func (*SymbolCache) InvalidatePackage

func (c *SymbolCache) InvalidatePackage(packagePath string)

InvalidatePackage removes all cache entries related to a package

func (*SymbolCache) ResetStats

func (c *SymbolCache) ResetStats()

ResetStats resets cache statistics

func (*SymbolCache) SetIdentifierType

func (c *SymbolCache) SetIdentifierType(key string, symbol *types.Symbol)

SetIdentifierType caches an identifier type resolution

func (*SymbolCache) SetMethodSet

func (c *SymbolCache) SetMethodSet(key string, methods []*types.Symbol)

SetMethodSet caches a method set

func (*SymbolCache) SetMethodTypeMapping

func (c *SymbolCache) SetMethodTypeMapping(key string, matches bool)

SetMethodTypeMapping caches a method-to-type mapping

func (*SymbolCache) SetPackageSymbols

func (c *SymbolCache) SetPackageSymbols(packagePath string, symbolTable *types.SymbolTable)

SetPackageSymbols caches a package symbol table

func (*SymbolCache) SetResolvedRef

func (c *SymbolCache) SetResolvedRef(key string, symbol *types.Symbol)

SetResolvedRef caches a resolved symbol reference

func (*SymbolCache) WarmCache

func (c *SymbolCache) WarmCache(workspace *types.Workspace)

WarmCache pre-populates the cache with commonly accessed symbols

type SymbolResolver

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

SymbolResolver handles symbol resolution and reference finding

func NewSymbolResolver

func NewSymbolResolver(ws *types.Workspace, logger *slog.Logger) *SymbolResolver

func (*SymbolResolver) BuildReferenceIndex

func (sr *SymbolResolver) BuildReferenceIndex() *ReferenceIndex

BuildReferenceIndex builds a reverse index mapping identifier names to their occurrences across all files in the workspace. This performs one AST walk per file and pre-computes declaration and selector information, eliminating the need for repeated nested AST walks in identifierRefersToSymbol/getQualifyingPackage/isDeclarationContext.

func (*SymbolResolver) BuildSymbolTable

func (sr *SymbolResolver) BuildSymbolTable(pkg *types.Package) (*types.SymbolTable, error)

BuildSymbolTable builds complete symbol table for a package

func (*SymbolResolver) CheckInterfaceCompliance

func (sr *SymbolResolver) CheckInterfaceCompliance(typ, iface *types.Symbol) (bool, []string)

CheckInterfaceCompliance checks if a type implements an interface

func (*SymbolResolver) FindDefinition

func (sr *SymbolResolver) FindDefinition(file string, pos token.Pos) (*types.Symbol, error)

FindDefinition finds the definition of symbol at given position

func (*SymbolResolver) FindInterfaceImplementations

func (sr *SymbolResolver) FindInterfaceImplementations(iface *types.Symbol) ([]*types.Symbol, error)

FindInterfaceImplementations finds all types that implement an interface

func (*SymbolResolver) FindPromotedMethods

func (sr *SymbolResolver) FindPromotedMethods(symbol *types.Symbol) ([]*types.Symbol, error)

FindPromotedMethods finds methods promoted from embedded fields

func (*SymbolResolver) FindReferences

func (sr *SymbolResolver) FindReferences(symbol *types.Symbol) ([]*types.Reference, error)

FindReferences finds all references to a symbol in workspace

func (*SymbolResolver) FindReferencesIndexed

func (sr *SymbolResolver) FindReferencesIndexed(symbol *types.Symbol, idx *ReferenceIndex) ([]*types.Reference, error)

FindReferencesIndexed finds references to a symbol using the pre-built index. This is O(1) lookup + O(R) filtering where R is the number of occurrences of the name, compared to the O(P×F×A) of FindReferences.

func (*SymbolResolver) FindReferencesIndexedFiltered

func (sr *SymbolResolver) FindReferencesIndexedFiltered(symbol *types.Symbol, idx *ReferenceIndex, allowedPackages map[string]*types.Package) ([]*types.Reference, error)

FindReferencesIndexedFiltered finds all references to a symbol using the index, optionally filtering to only specific packages for performance.

func (*SymbolResolver) HasNonDeclarationReference

func (sr *SymbolResolver) HasNonDeclarationReference(symbol *types.Symbol, idx *ReferenceIndex) bool

HasNonDeclarationReference checks if a symbol has at least one non-declaration reference in the index. Returns true as soon as one is found (early exit for unused detection).

func (*SymbolResolver) InvalidateCacheForFile

func (sr *SymbolResolver) InvalidateCacheForFile(filePath string)

InvalidateCacheForFile clears cache entries for a file

func (*SymbolResolver) InvalidateCacheForPackage

func (sr *SymbolResolver) InvalidateCacheForPackage(pkgPath string)

InvalidateCacheForPackage clears cache entries for a package

func (*SymbolResolver) ResolveEmbeddedFields

func (sr *SymbolResolver) ResolveEmbeddedFields(symbol *types.Symbol) ([]*types.Symbol, error)

ResolveEmbeddedFields finds all embedded fields in a struct type

func (*SymbolResolver) ResolveMethodSet

func (sr *SymbolResolver) ResolveMethodSet(symbol *types.Symbol) ([]*types.Symbol, error)

ResolveMethodSet returns all methods available on a type (including promoted methods)

func (*SymbolResolver) ResolveSymbol

func (sr *SymbolResolver) ResolveSymbol(pkg *types.Package, name string) (*types.Symbol, error)

ResolveSymbol resolves a symbol name within a package context

func (*SymbolResolver) UpdateSymbolTable

func (sr *SymbolResolver) UpdateSymbolTable(pkg *types.Package, changedFiles []string) error

UpdateSymbolTable incrementally updates a package's symbol table

type UnusedAnalyzer

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

UnusedAnalyzer finds unused symbols in the workspace

func NewUnusedAnalyzer

func NewUnusedAnalyzer(ws *types.Workspace, logger *slog.Logger) *UnusedAnalyzer

NewUnusedAnalyzer creates a new unused symbol analyzer

func (*UnusedAnalyzer) FindUnusedSymbols

func (ua *UnusedAnalyzer) FindUnusedSymbols() ([]*UnusedSymbol, error)

FindUnusedSymbols finds all unused symbols in the workspace

func (*UnusedAnalyzer) FormatUnusedSymbol

func (ua *UnusedAnalyzer) FormatUnusedSymbol(unused *UnusedSymbol) string

FormatUnusedSymbol formats an unused symbol for display

func (*UnusedAnalyzer) GetUnusedUnexportedSymbols

func (ua *UnusedAnalyzer) GetUnusedUnexportedSymbols() ([]*UnusedSymbol, error)

GetUnusedUnexportedSymbols returns only unexported unused symbols that are safe to delete

func (*UnusedAnalyzer) SetIncludeExported

func (ua *UnusedAnalyzer) SetIncludeExported(include bool)

SetIncludeExported controls whether exported symbols are included in the analysis

type UnusedSymbol

type UnusedSymbol struct {
	Symbol       *types.Symbol
	SafeToDelete bool   // True if unexported and safe to remove
	Reason       string // Why it's considered unused
}

UnusedSymbol represents an unused symbol in the codebase

Jump to

Keyboard shortcuts

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