analysis

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package analysis provides code analysis utilities including memory allocation analysis.

Index

Constants

This section is empty.

Variables

View Source
var KnownIOFunctions = map[string]types.SideEffectCategory{}/* 172 elements not displayed */

KnownIOFunctions maps "language:package.function" to the type of I/O they perform

View Source
var KnownPureFunctions = map[string]bool{}/* 278 elements not displayed */

KnownPureFunctions maps "language:package.function" to true for functions that are known to be pure (no side effects, deterministic output for same input).

Criteria for inclusion: - No I/O operations - No mutation of parameters - No global state access - Deterministic (same input -> same output) - No panics on valid input

Functions

func CheckFunctionPurity

func CheckFunctionPurity(language, qualifiedName string) (isPure bool, confidence types.PurityConfidence)

CheckFunctionPurity returns purity status and confidence for a function

func GetKnownSideEffects

func GetKnownSideEffects(language, qualifiedName string) types.SideEffectCategory

GetKnownSideEffects returns the known side effects for a function, or SideEffectUncertain if unknown

func GetLanguageFromExt

func GetLanguageFromExt(ext string) string

GetLanguageFromExt returns the language name from file extension

func GetLanguageFromPath

func GetLanguageFromPath(path string) string

GetLanguageFromPath extracts language from file path

func GetMemoryAllocationLabelRule

func GetMemoryAllocationLabelRule() core.LabelPropagationRule

GetMemoryAllocationLabelRule returns a LabelPropagationRule for memory allocation tracking This can be added to GraphPropagator's config for integrated analysis

func IsKnownPure

func IsKnownPure(language, qualifiedName string) bool

IsKnownPure checks if a function is known to be pure

Types

type AllocationPattern

type AllocationPattern struct {
	Pattern     *regexp.Regexp
	Category    string  // "heap", "stack", "pool", "gc-managed"
	Weight      float64 // Relative allocation cost (1.0 = baseline)
	Description string
}

AllocationPattern defines a pattern that indicates memory allocation

type AnalysisConfig

type AnalysisConfig struct {
	// Language support
	EnabledLanguages []string `json:"enabled_languages"`

	// Relationship types to analyze
	AnalyzeExtends        bool `json:"analyze_extends"`
	AnalyzeImplements     bool `json:"analyze_implements"`
	AnalyzeContains       bool `json:"analyze_contains"`
	AnalyzeDependencies   bool `json:"analyze_dependencies"`
	AnalyzeCalls          bool `json:"analyze_calls"`
	AnalyzeReferences     bool `json:"analyze_references"`
	AnalyzeImports        bool `json:"analyze_imports"`
	AnalyzeFileCoLocation bool `json:"analyze_file_co_location"`
	AnalyzeCrossLanguage  bool `json:"analyze_cross_language"`

	// Analysis depth and limits
	MaxCallDepth    int `json:"max_call_depth"`
	MaxReferences   int `json:"max_references"`
	MaxDependencies int `json:"max_dependencies"`

	// Performance settings
	ConcurrentAnalysis bool `json:"concurrent_analysis"`
	MaxConcurrentFiles int  `json:"max_concurrent_files"`

	// Feature flags
	EnableIncrementalAnalysis bool `json:"enable_incremental_analysis"`
	EnableCrossFileAnalysis   bool `json:"enable_cross_file_analysis"`
}

AnalysisConfig configures the relationship analysis process

func DefaultAnalysisConfig

func DefaultAnalysisConfig() AnalysisConfig

DefaultAnalysisConfig returns default configuration

type AnalysisStats

type AnalysisStats struct {
	TotalSymbols      int            `json:"total_symbols"`
	SymbolsByLanguage map[string]int `json:"symbols_by_language"`
	SymbolsByKind     map[string]int `json:"symbols_by_kind"`
	RelationshipCount map[string]int `json:"relationship_count"`
	QueryCount        int64          `json:"query_count"`
	AvgQueryTime      time.Duration  `json:"avg_query_time"`
	LastUpdated       time.Time      `json:"last_updated"`
	MemoryUsage       int64          `json:"memory_usage"`
	EnabledAnalyzers  []string       `json:"enabled_analyzers"`
}

AnalysisStats represents statistics from relationship analysis

type ArchitectureMetrics

type ArchitectureMetrics struct {
	ModuleStability      float64 `json:"module_stability"`       // incoming/(incoming+outgoing)
	AbstractionLevel     float64 `json:"abstraction_level"`      // interfaces/total_types
	DistanceFromMainSeq  float64 `json:"distance_main_sequence"` // |A + I - 1|
	ComponentCohesion    float64 `json:"component_cohesion"`
	InterfaceSegregation float64 `json:"interface_segregation"`
	DependencyInversion  float64 `json:"dependency_inversion"`
}

ArchitectureMetrics represents higher-level architectural measurements

type AwaitInfo

type AwaitInfo struct {
	Line        int
	AssignedVar string   // Variable receiving the result (empty if not assigned)
	CallTarget  string   // Function/method being awaited
	UsedVars    []string // Variables referenced in the await arguments
}

AwaitInfo tracks information about an await expression

type BasicMetricsCalculator

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

BasicMetricsCalculator calculates simple code metrics for symbols (Phase 3A)

func NewBasicMetricsCalculator

func NewBasicMetricsCalculator(enableAdvanced bool) *BasicMetricsCalculator

NewBasicMetricsCalculator creates a new basic metrics calculator

func (*BasicMetricsCalculator) CalculateBasicSymbolMetrics

func (mc *BasicMetricsCalculator) CalculateBasicSymbolMetrics(symbol *types.EnhancedSymbol, astNode *tree_sitter.Node, content []byte) *BasicSymbolMetrics

CalculateBasicSymbolMetrics calculates metrics for a single symbol using its AST node

type BasicSymbolMetrics

type BasicSymbolMetrics struct {
	// Core metrics
	Complexity     float64  `json:"complexity"`
	LinesOfCode    int      `json:"lines_of_code"`
	ReferenceCount int      `json:"reference_count"`
	Dependencies   []string `json:"dependencies"`

	// Quality indicators
	Quality   map[string]float64 `json:"quality"`
	RiskScore float64            `json:"risk_score"`
	Tags      []string           `json:"tags"`
}

BasicSymbolMetrics represents simple metrics calculated for a symbol (Phase 3A)

func (*BasicSymbolMetrics) ConvertToMainMetrics

func (basic *BasicSymbolMetrics) ConvertToMainMetrics() *SymbolMetrics

ConvertToMainMetrics converts BasicSymbolMetrics to main branch SymbolMetrics format

type BlockKey

type BlockKey struct {
	FileID    types.FileID
	StartLine int
	EndLine   int
}

BlockKey is a zero-allocation key type for code block comparison Replaces fmt.Sprintf("%d:%d:%d") in duplicate detection (5-10MB savings per analysis)

type BlockSize

type BlockSize struct {
	Lines      int
	Tokens     int
	Characters int
	Complexity int // cyclomatic complexity
}

BlockSize contains size metrics for a code block

type BlockType

type BlockType string

BlockType categorizes the type of code block

const (
	BlockTypeFunction  BlockType = "function"
	BlockTypeMethod    BlockType = "method"
	BlockTypeClass     BlockType = "class"
	BlockTypeBlock     BlockType = "block"
	BlockTypeStatement BlockType = "statement"
)

type BranchAllocation

type BranchAllocation struct {
	BranchType     string // "if", "else", "switch_case", "loop_body", "try", "catch"
	StartLine      int
	EndLine        int
	Depth          int     // Nesting depth
	Created        int     // Objects created in this branch
	Dropped        int     // Objects that go out of scope
	Retained       int     // Objects that escape the branch
	Weight         float64 // Weighted allocation score based on patterns
	LoopMultiplier float64 // If in loop, estimated iteration count multiplier
}

BranchAllocation tracks allocations within a code branch

type CachedMetricsCalculator

type CachedMetricsCalculator struct {
	*MetricsCalculator // Embed the original calculator
	// contains filtered or unexported fields
}

CachedMetricsCalculator wraps MetricsCalculator with intelligent caching

func NewCachedMetricsCalculator

func NewCachedMetricsCalculator(config CachedMetricsConfig) *CachedMetricsCalculator

NewCachedMetricsCalculator creates a new cached metrics calculator

func (*CachedMetricsCalculator) CalculateCyclomaticComplexity added in v0.4.0

func (c *CachedMetricsCalculator) CalculateCyclomaticComplexity(node *tree_sitter.Node) int

CalculateCyclomaticComplexity calculates cyclomatic complexity for a node Exported for use by git change analyzer

func (*CachedMetricsCalculator) CalculateLinesOfCode added in v0.4.0

func (c *CachedMetricsCalculator) CalculateLinesOfCode(node *tree_sitter.Node) int

CalculateLinesOfCode calculates the lines of code for a node Exported for use by git change analyzer

func (*CachedMetricsCalculator) CalculateNestingDepth added in v0.4.0

func (c *CachedMetricsCalculator) CalculateNestingDepth(node *tree_sitter.Node, currentDepth int) int

CalculateNestingDepth calculates the maximum nesting depth for a node Exported for use by git change analyzer

func (*CachedMetricsCalculator) CalculateSymbolMetrics

func (c *CachedMetricsCalculator) CalculateSymbolMetrics(
	symbol *types.EnhancedSymbol,
	node *tree_sitter.Node,
	content []byte,
) (*SymbolMetrics, error)

CalculateSymbolMetrics calculates metrics for an enhanced symbol with intelligent caching

func (*CachedMetricsCalculator) ClearCache

func (c *CachedMetricsCalculator) ClearCache()

ClearCache clears all cached metrics

func (*CachedMetricsCalculator) GetCacheInfo

func (c *CachedMetricsCalculator) GetCacheInfo() cache.CacheInfo

GetCacheInfo returns detailed cache information

func (*CachedMetricsCalculator) GetCacheStats

func (c *CachedMetricsCalculator) GetCacheStats() cache.CacheStats

GetCacheStats returns caching performance statistics

func (*CachedMetricsCalculator) SetCacheMaxEntries

func (c *CachedMetricsCalculator) SetCacheMaxEntries(maxEntries int)

SetCacheMaxEntries updates the cache size limit

func (*CachedMetricsCalculator) UpdateCacheTTL

func (c *CachedMetricsCalculator) UpdateCacheTTL(ttl time.Duration)

UpdateCacheTTL updates the cache time-to-live

type CachedMetricsConfig

type CachedMetricsConfig struct {
	EnableCaching bool              `json:"enable_caching"`
	CacheConfig   cache.CacheConfig `json:"cache_config"`
	MetricsConfig MetricsConfig     `json:"metrics_config"`
}

CachedMetricsConfig provides configuration for cached metrics calculator

func DefaultCachedMetricsConfig

func DefaultCachedMetricsConfig() CachedMetricsConfig

DefaultCachedMetricsConfig returns a production-ready configuration

type CallGraphNode

type CallGraphNode struct {
	Symbol      *types.EnhancedSymbol `json:"symbol"`
	DirectCalls []*FunctionDependency `json:"direct_calls"`
	CalledBy    []*FunctionDependency `json:"called_by"`
	Depth       int                   `json:"depth"`
	IsRecursive bool                  `json:"is_recursive"`
	CyclePaths  [][]types.SymbolID    `json:"cycle_paths,omitempty"`
	IsCritical  bool                  `json:"is_critical"` // Many dependents
	IsLeaf      bool                  `json:"is_leaf"`     // No dependencies
	IsRoot      bool                  `json:"is_root"`     // No callers
}

CallGraphNode represents a node in the function call graph

type CallInfo

type CallInfo struct {
	Target    string // Function/method name
	Line      int
	InLoop    bool // Whether this call is inside a loop
	LoopDepth int  // Depth of containing loop (0 if not in loop)
	LoopLine  int  // Line of containing loop
}

CallInfo tracks information about a function call

type CallType

type CallType string

CallType represents different types of function calls

const (
	CallTypeDirect      CallType = "direct_call"
	CallTypeIndirect    CallType = "indirect_call"
	CallTypeCallback    CallType = "callback"
	CallTypeAsync       CallType = "async"
	CallTypeRecursive   CallType = "recursive"
	CallTypeConditional CallType = "conditional"
	CallTypePolymorphic CallType = "polymorphic"
	CallTypeExternal    CallType = "external"
)

type CodeBlock

type CodeBlock struct {
	FileID            types.FileID
	FilePath          string
	StartLine         int
	EndLine           int
	StartColumn       int
	EndColumn         int
	Content           string
	NormalizedContent string
	Tokens            []string
	ASTHash           string
	FunctionName      string
	BlockType         BlockType
	Size              BlockSize
}

CodeBlock represents a block of code that can be analyzed for duplication

type CodeQualityMetrics

type CodeQualityMetrics struct {
	CyclomaticComplexity int     `json:"cyclomatic_complexity"`
	CognitiveComplexity  int     `json:"cognitive_complexity"`
	NestingDepth         int     `json:"nesting_depth"`
	LinesOfCode          int     `json:"lines_of_code"`
	LinesOfComments      int     `json:"lines_of_comments"`
	HalsteadVolume       float64 `json:"halstead_volume"`
	HalsteadDifficulty   float64 `json:"halstead_difficulty"`
	MaintainabilityIndex float64 `json:"maintainability_index"`
}

CodeQualityMetrics represents various code quality measurements

type DependencyMetrics

type DependencyMetrics struct {
	IncomingDependencies   int     `json:"incoming_dependencies"`
	OutgoingDependencies   int     `json:"outgoing_dependencies"`
	TransitiveDependencies int     `json:"transitive_dependencies"`
	CouplingStrength       float64 `json:"coupling_strength"` // 0-1 scale
	CohesionStrength       float64 `json:"cohesion_strength"` // 0-1 scale
	DepthInCallTree        int     `json:"depth_in_call_tree"`
	HasCircularDeps        bool    `json:"has_circular_deps"`
	StabilityIndex         float64 `json:"stability_index"`   // incoming/(incoming+outgoing)
	InstabilityIndex       float64 `json:"instability_index"` // outgoing/(incoming+outgoing)
}

DependencyMetrics represents dependency-related measurements

type DependencyQuery

type DependencyQuery struct {
	SymbolID          types.SymbolID `json:"symbol_id,omitempty"`
	SymbolName        string         `json:"symbol_name,omitempty"`
	FileID            types.FileID   `json:"file_id,omitempty"`
	Direction         string         `json:"direction"` // "incoming", "outgoing", "both"
	IncludeTransitive bool           `json:"include_transitive"`
	MaxDepth          int            `json:"max_depth"`
	IncludeExternal   bool           `json:"include_external"`
	FilterByType      []CallType     `json:"filter_by_type,omitempty"`
	MinProbability    float64        `json:"min_probability,omitempty"`
	ExcludeFiles      []types.FileID `json:"exclude_files,omitempty"`
}

DependencyQuery represents a query for dependency analysis

type DependencySet

type DependencySet struct {
	SymbolID types.SymbolID `json:"symbol_id"`

	// Direct dependencies
	DirectDeps       []*FunctionDependency `json:"direct_deps"`
	DirectDependents []*FunctionDependency `json:"direct_dependents"`

	// Transitive dependencies
	TransitiveDeps       []*FunctionDependency `json:"transitive_deps"`
	TransitiveDependents []*FunctionDependency `json:"transitive_dependents"`

	// File-level dependencies
	FileDeps     []types.FileID        `json:"file_deps"`
	ExternalDeps []*ExternalDependency `json:"external_deps"`

	// Analysis results
	DepthLevels       [][]types.SymbolID `json:"depth_levels"`
	CyclicDeps        [][]types.SymbolID `json:"cyclic_deps"`
	CriticalPath      []types.SymbolID   `json:"critical_path"`
	BottleneckSymbols []types.SymbolID   `json:"bottleneck_symbols"`

	// Metrics
	MaxDepth          int `json:"max_depth"`
	TotalDependencies int `json:"total_dependencies"`
	UniqueFiles       int `json:"unique_files"`
	CircularCount     int `json:"circular_count"`
	FanOut            int `json:"fan_out"`
	FanIn             int `json:"fan_in"`

	// Cache management
	CalculatedAt int64 `json:"calculated_at"`
	IsStale      bool  `json:"is_stale"`
}

DependencySet represents all dependencies for a function

type DuplicateCluster

type DuplicateCluster struct {
	ID         string
	Type       DuplicateType
	Blocks     []CodeBlock
	Similarity float64
	Impact     DuplicateImpact
	Suggestion string
}

DuplicateCluster represents a group of similar code blocks

type DuplicateDetector

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

DuplicateDetector finds code duplicates using multiple analysis techniques

func NewDuplicateDetector

func NewDuplicateDetector() *DuplicateDetector

NewDuplicateDetector creates a new duplicate detection system

func (*DuplicateDetector) AnalyzeFile

func (dd *DuplicateDetector) AnalyzeFile(fileID types.FileID, filePath string, content []byte, tree *tree_sitter.Tree) error

AnalyzeFile analyzes a file for code blocks and adds them to duplicate detection

func (*DuplicateDetector) Clear

func (dd *DuplicateDetector) Clear()

Clear resets the duplicate detector state

func (*DuplicateDetector) GetDuplicates

func (dd *DuplicateDetector) GetDuplicates() []DuplicateCluster

GetDuplicates returns all detected duplicates organized by type

type DuplicateImpact

type DuplicateImpact struct {
	Severity        ImpactSeverity
	LinesCount      int
	FilesCount      int
	Maintainability float64 // 0.0 (hard) to 1.0 (easy)
	Refactorable    bool
}

DuplicateImpact assesses the impact of duplication

type DuplicateType

type DuplicateType string

DuplicateType categorizes the kind of duplication

const (
	DuplicateTypeExact      DuplicateType = "exact"      // Identical code
	DuplicateTypeStructural DuplicateType = "structural" // Same structure, different names
	DuplicateTypeSemantic   DuplicateType = "semantic"   // Similar functionality
)

type ExclusionChecker

type ExclusionChecker interface {
	IsExcludedFromAnalysis(fileID types.FileID, symbolID types.SymbolID, analysisType string) bool
}

ExclusionChecker interface for checking if symbols should be excluded from analysis This allows for dependency injection and testing

type ExpensiveCallConfig

type ExpensiveCallConfig struct {
	Pattern     *regexp.Regexp // Compiled regex for matching
	Category    string         // "regex", "io", "network", "parse", "reflection"
	Description string         // Human-readable description
	Severity    string         // "high", "medium", "low"
}

ExpensiveCallConfig defines a known expensive operation pattern

type ExternalDepType

type ExternalDepType string

ExternalDepType categorizes external dependencies

const (
	ExtDepLibrary   ExternalDepType = "library"
	ExtDepFramework ExternalDepType = "framework"
	ExtDepService   ExternalDepType = "service"
	ExtDepDatabase  ExternalDepType = "database"
	ExtDepAPI       ExternalDepType = "api"
	ExtDepUtility   ExternalDepType = "utility"
	ExtDepStdlib    ExternalDepType = "stdlib"
)

type ExternalDependency

type ExternalDependency struct {
	Name              string            `json:"name"`
	Type              ExternalDepType   `json:"type"`
	Version           string            `json:"version,omitempty"`
	Source            string            `json:"source"`      // package manager, URL, etc.
	IsStandard        bool              `json:"is_standard"` // stdlib vs third-party
	SecurityRisk      SecurityRisk      `json:"security_risk"`
	PerformanceImpact PerformanceImpact `json:"performance_impact"`
	Stability         float64           `json:"stability"` // 0-1 stability score
}

ExternalDependency represents a dependency on external libraries/services

type FileGraphNode

type FileGraphNode struct {
	FileID          types.FileID     `json:"file_id"`
	FilePath        string           `json:"file_path"`
	ImportedFiles   []types.FileID   `json:"imported_files"`
	ImportedBy      []types.FileID   `json:"imported_by"`
	InternalSymbols []types.SymbolID `json:"internal_symbols"`
	ExportedSymbols []types.SymbolID `json:"exported_symbols"`
	ModuleStability float64          `json:"module_stability"`
	CouplingFactor  float64          `json:"coupling_factor"`
}

FileGraphNode represents dependencies between files

type FileImportProvider

type FileImportProvider interface {
	GetFileImports(fileID types.FileID) []types.Import
	GetFileInfo(fileID types.FileID) *types.FileInfo
}

FileImportProvider provides access to file-level imports

type FileInfo

type FileInfo struct {
	Path         string    `json:"path"`
	Language     string    `json:"language"`
	Size         int64     `json:"size"`
	LastModified time.Time `json:"last_modified"`
	IsGenerated  bool      `json:"is_generated"`
}

FileInfo represents information about a file

type FileMetrics

type FileMetrics struct {
	FileID   types.FileID `json:"file_id"`
	FilePath string       `json:"file_path"`

	// Aggregated metrics
	TotalComplexity   int     `json:"total_complexity"`
	AverageComplexity float64 `json:"average_complexity"`
	MaxComplexity     int     `json:"max_complexity"`
	TotalLines        int     `json:"total_lines"`
	CodeLines         int     `json:"code_lines"`
	CommentLines      int     `json:"comment_lines"`

	// Dependency metrics
	InternalDependencies int `json:"internal_dependencies"`
	ExternalDependencies int `json:"external_dependencies"`
	Dependents           int `json:"dependents"`

	// Symbol breakdown
	Functions  int `json:"functions"`
	Classes    int `json:"classes"`
	Interfaces int `json:"interfaces"`
	Variables  int `json:"variables"`

	// Quality indicators
	OverallQualityScore float64 `json:"overall_quality_score"`
	TechnicalDebt       float64 `json:"technical_debt"`
	MaintainabilityRank string  `json:"maintainability_rank"` // A, B, C, D, F

	// Hot spots
	MostComplexSymbol *SymbolMetrics   `json:"most_complex_symbol,omitempty"`
	HighRiskSymbols   []*SymbolMetrics `json:"high_risk_symbols,omitempty"`
}

FileMetrics aggregates metrics for an entire file

type FileServiceInterface

type FileServiceInterface interface {
	// GetFileContent returns the content of a file
	GetFileContent(fileID types.FileID) (string, error)

	// GetFilePath returns the path of a file
	GetFilePath(fileID types.FileID) (string, error)

	// GetFileInfo returns information about a file
	GetFileInfo(fileID types.FileID) (FileInfo, error)
}

FileServiceInterface defines the interface for file service operations

type FunctionAnalysis

type FunctionAnalysis struct {
	Name      string
	SymbolID  types.SymbolID
	StartLine int
	EndLine   int
	IsAsync   bool
	Loops     []LoopInfo  // All loops in the function
	Awaits    []AwaitInfo // All await expressions
	Calls     []CallInfo  // All function calls
	Language  string
	FilePath  string
}

FunctionAnalysis holds analysis data for a single function

type FunctionAnalysisContext

type FunctionAnalysisContext struct {
	// Function identity
	Name      string
	File      string
	StartLine int
	EndLine   int

	// Parameters (names to track for parameter writes)
	Parameters   map[string]int // name -> parameter index
	ReceiverName string         // "this", "self", or Go receiver name
	ReceiverType string         // Type of receiver (for methods)

	// Scope tracking for closure detection
	LocalVariables map[string]int   // name -> declaration line
	ScopeDepth     int              // Current nesting depth
	OuterScopes    []map[string]int // Variables from enclosing scopes (closures)

	// Access tracking
	Accesses []types.FieldAccess
	SeqNum   int // Next sequence number

	// Detected effects
	SideEffects types.SideEffectCategory

	// External calls (truly external: I/O, network, etc.)
	ExternalCalls []types.ExternalCallInfo

	// Unresolved function calls (need Phase 2 resolution)
	UnresolvedCalls []types.UnresolvedCallInfo

	// Throw sites
	ThrowSites []types.ThrowSiteInfo

	// Error handling
	DeferCount      int
	TryFinallyCount int
	ReturnsError    bool

	// Impurity reasons (for debugging)
	ImpurityReasons []string
}

FunctionAnalysisContext tracks state while analyzing a single function

type FunctionDependency

type FunctionDependency struct {
	SourceSymbol      types.SymbolID    `json:"source_symbol"`
	TargetSymbol      types.SymbolID    `json:"target_symbol"`
	CallType          CallType          `json:"call_type"`
	CallStrength      types.RefStrength `json:"call_strength"`
	CallContext       []types.ScopeInfo `json:"call_context"`
	FileLocation      types.FileID      `json:"file_location"`
	LineNumber        int               `json:"line_number"`
	Distance          int               `json:"distance"`        // Degrees of separation
	ThroughSymbols    []types.SymbolID  `json:"through_symbols"` // For transitive deps
	Probability       float64           `json:"probability"`     // 0-1 likelihood of execution
	PerformanceImpact PerformanceImpact `json:"performance_impact"`
}

FunctionDependency represents a dependency relationship between functions

type FunctionDependencyTracker

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

FunctionDependencyTracker provides enhanced dependency analysis with transitive resolution

func NewFunctionDependencyTracker

func NewFunctionDependencyTracker(refTracker *core.ReferenceTracker) *FunctionDependencyTracker

NewFunctionDependencyTracker creates a new enhanced dependency tracker

func (*FunctionDependencyTracker) BuildCallGraph

func (fdt *FunctionDependencyTracker) BuildCallGraph() error

BuildCallGraph constructs the complete function call graph

func (*FunctionDependencyTracker) CompareGraphs

func (fdt *FunctionDependencyTracker) CompareGraphs(fileID types.FileID) *GraphComparison

CompareGraphs compares file-level vs symbol-level dependency patterns

func (*FunctionDependencyTracker) GetFileGraph

func (fdt *FunctionDependencyTracker) GetFileGraph() map[types.FileID]*FileGraphNode

GetFileGraph returns file-level dependency information

func (*FunctionDependencyTracker) GetFunctionDependencies

func (fdt *FunctionDependencyTracker) GetFunctionDependencies(query DependencyQuery) (*DependencySet, error)

GetFunctionDependencies returns comprehensive dependency information for a function

func (*FunctionDependencyTracker) GetStats

func (fdt *FunctionDependencyTracker) GetStats() map[string]interface{}

GetStats returns dependency tracking statistics

func (*FunctionDependencyTracker) InvalidateCache

func (fdt *FunctionDependencyTracker) InvalidateCache()

InvalidateCache marks all dependency caches as stale

func (*FunctionDependencyTracker) SetIndexer

func (fdt *FunctionDependencyTracker) SetIndexer(indexer FileImportProvider)

SetIndexer sets the file import provider for graph comparison

type FunctionMemoryProfile

type FunctionMemoryProfile struct {
	Name      string
	FilePath  string
	StartLine int
	EndLine   int
	Language  string
	FileID    types.FileID   // For annotation lookup
	SymbolID  types.SymbolID // For integration with GraphPropagator

	// Branch-level data
	Branches []BranchAllocation

	// Aggregated metrics
	TotalCreated   int
	TotalDropped   int
	TotalRetained  int     // Objects that escape function scope
	WeightedScore  float64 // Weighted allocation score
	LoopAllocScore float64 // Extra score for allocations in loops

	// Call relationships for propagation
	Callees []string // Functions this function calls
	Callers []string // Functions that call this function

	// Memory analysis hints from @lci annotations
	MemoryHints *core.MemoryAnalysisHints
}

FunctionMemoryProfile tracks memory characteristics of a function

type GoAnalyzer

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

GoAnalyzer implements language-specific analysis for Go code

func NewGoAnalyzer

func NewGoAnalyzer() *GoAnalyzer

NewGoAnalyzer creates a new Go analyzer

func (*GoAnalyzer) AnalyzeCalls

func (ga *GoAnalyzer) AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

AnalyzeCalls analyzes function call relationships

func (*GoAnalyzer) AnalyzeContains

func (ga *GoAnalyzer) AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeContains analyzes containment relationships (methods, fields, etc.)

func (*GoAnalyzer) AnalyzeDependencies

func (ga *GoAnalyzer) AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

AnalyzeDependencies analyzes dependency relationships

func (*GoAnalyzer) AnalyzeExtends

func (ga *GoAnalyzer) AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeExtends analyzes Go inheritance (embedding) relationships

func (*GoAnalyzer) AnalyzeImplements

func (ga *GoAnalyzer) AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeImplements analyzes Go interface implementation relationships

func (*GoAnalyzer) ExtractSymbols

func (ga *GoAnalyzer) ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

ExtractSymbols extracts all symbols from Go code

func (*GoAnalyzer) GetLanguageName

func (ga *GoAnalyzer) GetLanguageName() string

GetLanguageName returns the language name

type GraphComparison

type GraphComparison struct {
	FileID                  types.FileID `json:"file_id"`
	ImportVsUsageGap        float64      `json:"import_vs_usage_gap"`
	UnusedImports           []string     `json:"unused_imports"`
	MissingImports          []string     `json:"missing_imports"`
	ArchitecturalViolations []string     `json:"architectural_violations"`
	CouplingDiscrepancies   []string     `json:"coupling_discrepancies"`
}

GraphComparison represents the results of comparing file vs dependency graphs

type HalsteadMetrics

type HalsteadMetrics struct {
	Volume     float64
	Difficulty float64
	Effort     float64
	Time       float64
	Bugs       float64
}

Halstead metrics calculation

type ImpactSeverity

type ImpactSeverity string
const (
	ImpactLow      ImpactSeverity = "low"
	ImpactMedium   ImpactSeverity = "medium"
	ImpactHigh     ImpactSeverity = "high"
	ImpactCritical ImpactSeverity = "critical"
)

type ImportResolution

type ImportResolution struct {
	ImportPath   string                    `json:"import_path"`   // The import path
	ResolvedPath string                    `json:"resolved_path"` // Resolved file path
	Symbols      []types.CompositeSymbolID `json:"symbols"`       // Imported symbols
	ImportType   ImportType                `json:"import_type"`   // Type of import
	Location     types.SymbolLocation      `json:"location"`      // Location of import statement
}

ImportResolution represents a resolved import

type ImportType

type ImportType uint8

ImportType represents different types of imports

const (
	ImportTypeUnknown   ImportType = iota
	ImportTypeNamed                // import { foo } from 'bar'
	ImportTypeDefault              // import foo from 'bar'
	ImportTypeNamespace            // import * as foo from 'bar'
	ImportTypeModule               // import 'bar'
	ImportTypeRequire              // const foo = require('bar')
	ImportTypePackage              // import "package" (Go)
	ImportTypeDynamic              // import('bar') or require.resolve('bar')
)

func (ImportType) String

func (it ImportType) String() string

String returns string representation of import type

type JavaScriptAnalyzer

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

JavaScriptAnalyzer implements language-specific analysis for JavaScript/TypeScript code This is a simplified implementation using regex patterns - a production version would use a proper AST parser

func NewJavaScriptAnalyzer

func NewJavaScriptAnalyzer() *JavaScriptAnalyzer

NewJavaScriptAnalyzer creates a new JavaScript analyzer

func (*JavaScriptAnalyzer) AnalyzeCalls

func (jsa *JavaScriptAnalyzer) AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

AnalyzeCalls analyzes function call relationships

func (*JavaScriptAnalyzer) AnalyzeContains

func (jsa *JavaScriptAnalyzer) AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeContains analyzes containment relationships (methods in classes, etc.)

func (*JavaScriptAnalyzer) AnalyzeDependencies

func (jsa *JavaScriptAnalyzer) AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

AnalyzeDependencies analyzes dependency relationships

func (*JavaScriptAnalyzer) AnalyzeExtends

func (jsa *JavaScriptAnalyzer) AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeExtends analyzes inheritance relationships in JavaScript/TypeScript

func (*JavaScriptAnalyzer) AnalyzeImplements

func (jsa *JavaScriptAnalyzer) AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeImplements analyzes interface implementation relationships

func (*JavaScriptAnalyzer) ExtractSymbols

func (jsa *JavaScriptAnalyzer) ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

ExtractSymbols extracts all symbols from JavaScript/TypeScript code

func (*JavaScriptAnalyzer) GetLanguageName

func (jsa *JavaScriptAnalyzer) GetLanguageName() string

GetLanguageName returns the language name

type JavaScriptGoFastAnalyzer added in v0.4.0

type JavaScriptGoFastAnalyzer struct{}

JavaScriptGoFastAnalyzer implements language-specific analysis for JavaScript code Uses go-fAST for accurate AST-based parsing instead of regex patterns

func NewJavaScriptGoFastAnalyzer added in v0.4.0

func NewJavaScriptGoFastAnalyzer() *JavaScriptGoFastAnalyzer

NewJavaScriptGoFastAnalyzer creates a new JavaScript analyzer using go-fAST

func (*JavaScriptGoFastAnalyzer) AnalyzeCalls added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

AnalyzeCalls analyzes function calls

func (*JavaScriptGoFastAnalyzer) AnalyzeContains added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeContains returns containment relationships

func (*JavaScriptGoFastAnalyzer) AnalyzeDependencies added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

AnalyzeDependencies analyzes import dependencies Note: go-fast may not support ES6 imports, so this returns empty for now

func (*JavaScriptGoFastAnalyzer) AnalyzeExtends added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeExtends analyzes class inheritance

func (*JavaScriptGoFastAnalyzer) AnalyzeImplements added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeImplements analyzes interface implementation (JS doesn't have interfaces)

func (*JavaScriptGoFastAnalyzer) ExtractSymbols added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

ExtractSymbols extracts all symbols from JavaScript code using go-fAST

func (*JavaScriptGoFastAnalyzer) GetLanguageName added in v0.4.0

func (jga *JavaScriptGoFastAnalyzer) GetLanguageName() string

GetLanguageName returns the language name

type JavaScriptHybridAnalyzer added in v0.4.0

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

JavaScriptHybridAnalyzer combines go-fAST (for ES5/CommonJS) with regex fallback (for ES6 modules) This provides accurate AST-based parsing for compatible code while maintaining compatibility with ES6 module syntax that go-fAST doesn't support

func NewJavaScriptHybridAnalyzer added in v0.4.0

func NewJavaScriptHybridAnalyzer() *JavaScriptHybridAnalyzer

NewJavaScriptHybridAnalyzer creates a new hybrid JavaScript analyzer

func (*JavaScriptHybridAnalyzer) AnalyzeCalls added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

AnalyzeCalls tries go-fAST first, falls back to regex

func (*JavaScriptHybridAnalyzer) AnalyzeContains added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeContains delegates to the appropriate analyzer

func (*JavaScriptHybridAnalyzer) AnalyzeDependencies added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

AnalyzeDependencies delegates to the appropriate analyzer

func (*JavaScriptHybridAnalyzer) AnalyzeExtends added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeExtends delegates to the appropriate analyzer

func (*JavaScriptHybridAnalyzer) AnalyzeImplements added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeImplements delegates to the appropriate analyzer

func (*JavaScriptHybridAnalyzer) ExtractSymbols added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

ExtractSymbols tries go-fAST first, falls back to regex on parse failure

func (*JavaScriptHybridAnalyzer) GetLanguageName added in v0.4.0

func (jha *JavaScriptHybridAnalyzer) GetLanguageName() string

GetLanguageName returns the language name

type LanguageAnalyzer

type LanguageAnalyzer interface {
	// ExtractSymbols extracts all symbols from file content
	ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

	// AnalyzeExtends analyzes inheritance/extension relationships
	AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

	// AnalyzeImplements analyzes interface implementation relationships
	AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

	// AnalyzeContains analyzes containment relationships (methods in classes, etc.)
	AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

	// AnalyzeDependencies analyzes dependency relationships
	AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

	// AnalyzeCalls analyzes function call relationships
	AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

	// GetLanguageName returns the name of the language this analyzer handles
	GetLanguageName() string
}

LanguageAnalyzer defines the interface for language-specific analysis

type LoopInfo

type LoopInfo struct {
	NodeType  string // "for_statement", "while_statement", etc.
	StartLine int
	EndLine   int
	Depth     int // Nesting depth (1 = top-level loop)
}

LoopInfo tracks information about a loop during analysis

type MemoryAnalysisResult

type MemoryAnalysisResult struct {
	Functions []FunctionMemoryProfile
	Scores    []MemoryPressureScore
	Summary   MemorySummary
	Hotspots  []MemoryHotspot
}

MemoryAnalysisResult contains the full analysis results

type MemoryAnalyzer

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

MemoryAnalyzer performs memory allocation analysis using the core GraphPropagator for PageRank-style score propagation through the call graph. It tracks allocations per branch/function and propagates "memory pressure" scores to identify hotspots.

func NewMemoryAnalyzer

func NewMemoryAnalyzer() *MemoryAnalyzer

NewMemoryAnalyzer creates a new memory analyzer with default settings

func NewMemoryAnalyzerFull

func NewMemoryAnalyzerFull(propagator *core.GraphPropagator, refTracker *core.ReferenceTracker, symbolIndex *core.SymbolIndex, semanticAnnotator *core.SemanticAnnotator, options MemoryAnalyzerOptions) *MemoryAnalyzer

NewMemoryAnalyzerFull creates a memory analyzer with all dependencies including semantic annotator for @lci:exclude annotation support

func NewMemoryAnalyzerWithOptions

func NewMemoryAnalyzerWithOptions(options MemoryAnalyzerOptions) *MemoryAnalyzer

NewMemoryAnalyzerWithOptions creates a new memory analyzer with custom options

func NewMemoryAnalyzerWithPropagator

func NewMemoryAnalyzerWithPropagator(propagator *core.GraphPropagator, refTracker *core.ReferenceTracker, symbolIndex *core.SymbolIndex) *MemoryAnalyzer

NewMemoryAnalyzerWithPropagator creates a memory analyzer that uses the core GraphPropagator for accurate call graph based score propagation

func NewMemoryAnalyzerWithPropagatorAndOptions

func NewMemoryAnalyzerWithPropagatorAndOptions(propagator *core.GraphPropagator, refTracker *core.ReferenceTracker, symbolIndex *core.SymbolIndex, options MemoryAnalyzerOptions) *MemoryAnalyzer

NewMemoryAnalyzerWithPropagatorAndOptions creates a memory analyzer with propagator and custom options

func (*MemoryAnalyzer) AnalyzeFromPerfData

func (ma *MemoryAnalyzer) AnalyzeFromPerfData(files []*types.FileInfo) *MemoryAnalysisResult

AnalyzeFromPerfData creates FunctionAnalysis objects from PerfData and analyzes them

func (*MemoryAnalyzer) AnalyzeFromPerfDataWithSymbols

func (ma *MemoryAnalyzer) AnalyzeFromPerfDataWithSymbols(files []*types.FileInfo, refTracker *core.ReferenceTracker) *MemoryAnalysisResult

AnalyzeFromPerfDataWithSymbols creates FunctionAnalysis with resolved SymbolIDs This enables accurate call graph propagation via ReferenceTracker

func (*MemoryAnalyzer) AnalyzeFunctions

func (ma *MemoryAnalyzer) AnalyzeFunctions(functions []*FunctionAnalysis) *MemoryAnalysisResult

AnalyzeFunctions analyzes a set of functions for memory allocation patterns

func (*MemoryAnalyzer) GetOptions

func (ma *MemoryAnalyzer) GetOptions() MemoryAnalyzerOptions

GetOptions returns the current analyzer options

func (*MemoryAnalyzer) SetExclusionChecker

func (ma *MemoryAnalyzer) SetExclusionChecker(checker ExclusionChecker)

SetExclusionChecker sets a custom exclusion checker (primarily for testing)

func (*MemoryAnalyzer) SetOptions

func (ma *MemoryAnalyzer) SetOptions(options MemoryAnalyzerOptions)

SetOptions updates the analyzer options

func (*MemoryAnalyzer) SetSemanticAnnotator

func (ma *MemoryAnalyzer) SetSemanticAnnotator(annotator *core.SemanticAnnotator)

SetSemanticAnnotator sets the semantic annotator for @lci:exclude support

type MemoryAnalyzerOptions

type MemoryAnalyzerOptions struct {
	// IncludeTestFiles controls whether test files are included in the analysis.
	// When false (default), test files receive a 0.1x score penalty, effectively
	// filtering them from top hotspots while still tracking them.
	// When true, test files are scored normally (useful for analyzing test performance).
	IncludeTestFiles bool

	// TestFilePenalty is the multiplier applied to test file scores when
	// IncludeTestFiles is false. Default is 0.1 (10% of normal score).
	TestFilePenalty float64

	// TestFilePatterns configures how test files are detected.
	// If nil, uses DefaultTestFilePatterns().
	TestFilePatterns *TestFilePatterns
}

MemoryAnalyzerOptions configures memory analysis behavior

func DefaultMemoryAnalyzerOptions

func DefaultMemoryAnalyzerOptions() MemoryAnalyzerOptions

DefaultMemoryAnalyzerOptions returns the default options for memory analysis

type MemoryHotspot

type MemoryHotspot struct {
	FunctionName string
	FilePath     string
	Line         int
	Score        float64
	Reason       string
	Suggestion   string
}

MemoryHotspot identifies a specific location with high memory pressure

type MemoryPressureScore

type MemoryPressureScore struct {
	FunctionName     string
	FilePath         string
	Line             int
	SymbolID         types.SymbolID
	DirectScore      float64 // Score from direct allocations
	PropagatedScore  float64 // Score propagated from callees via GraphPropagator
	TotalScore       float64 // Combined score
	HeapPressure     float64 // Estimated heap allocation pressure
	LoopPressure     float64 // Pressure from loop allocations
	BranchComplexity float64 // Memory complexity from branching
	RetentionRisk    float64 // Risk of memory retention/leaks
	Percentile       float64 // Where this function ranks (0-100)
	Severity         string  // "critical", "high", "medium", "low"
	IsTestFile       bool    // Whether this function is in a test file
	IsExcluded       bool    // Whether this function is excluded via @lci:exclude[memory]

	// Call frequency context from @lci:call-frequency annotation
	// Values: "hot-path", "once-per-file", "once-per-request", "once-per-session",
	//         "startup-only", "cli-output", "test-only", "rare", or "" (unknown)
	CallFrequency string

	// Whether this function has bounded loops (reduces false positives for retry loops)
	HasBoundedLoops bool
}

MemoryPressureScore represents the final propagated score for a function

type MemorySummary

type MemorySummary struct {
	TotalFunctions   int
	TotalAllocations int
	AvgAllocPerFunc  float64
	MaxAllocInFunc   int
	LoopAllocCount   int // Allocations inside loops
	BranchAllocCount int // Allocations in conditional branches
	CriticalCount    int
	HighCount        int
	MediumCount      int
	LowCount         int
	ExcludedCount    int // Functions excluded via @lci:exclude[memory]
}

MemorySummary provides aggregate statistics

type MetricsCalculator

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

MetricsCalculator provides comprehensive code quality and dependency metrics

func NewMetricsCalculator

func NewMetricsCalculator(duplicateDetector *DuplicateDetector) *MetricsCalculator

NewMetricsCalculator creates a new metrics calculator

func (*MetricsCalculator) CalculateSymbolMetrics

func (mc *MetricsCalculator) CalculateSymbolMetrics(symbol *types.EnhancedSymbol, node *tree_sitter.Node, content []byte) *SymbolMetrics

CalculateSymbolMetrics computes comprehensive metrics for a symbol

func (*MetricsCalculator) FilterSymbolsByMetrics

func (mc *MetricsCalculator) FilterSymbolsByMetrics(symbols []*types.EnhancedSymbol, filter MetricsFilter) []*SymbolMetrics

FilterSymbolsByMetrics filters symbols based on metrics criteria

func (*MetricsCalculator) GetCacheStats

func (mc *MetricsCalculator) GetCacheStats() map[string]interface{}

GetCacheStats returns cache statistics

func (*MetricsCalculator) InvalidateCache

func (mc *MetricsCalculator) InvalidateCache()

InvalidateCache marks all cached metrics as stale

func (*MetricsCalculator) SetRefTracker

func (mc *MetricsCalculator) SetRefTracker(refTracker ReferenceProvider)

SetRefTracker sets the reference provider for advanced dependency analysis

type MetricsConfig

type MetricsConfig struct {
	EnableHalstead          bool `json:"enable_halstead"`
	EnableMaintainability   bool `json:"enable_maintainability"`
	EnableDependencyMetrics bool `json:"enable_dependency_metrics"`
}

MetricsConfig provides configuration for the underlying metrics calculator

type MetricsFilter

type MetricsFilter struct {
	MinComplexity    int      `json:"min_complexity,omitempty"`
	MaxComplexity    int      `json:"max_complexity,omitempty"`
	MinDependencies  int      `json:"min_dependencies,omitempty"`
	MaxDependencies  int      `json:"max_dependencies,omitempty"`
	SymbolTypes      []string `json:"symbol_types,omitempty"`
	CouplingStrength string   `json:"coupling_strength,omitempty"` // tight, loose, any
	HasCircularDeps  *bool    `json:"has_circular_deps,omitempty"`
	MinRiskScore     int      `json:"min_risk_score,omitempty"`
	MaxRiskScore     int      `json:"max_risk_score,omitempty"`
	Tags             []string `json:"tags,omitempty"`
	FilePaths        []string `json:"file_paths,omitempty"`
}

MetricsFilter provides filtering options for metrics queries

type PatternDetails

type PatternDetails struct {
	// For sequential-awaits pattern
	TotalAwaits         int      // Total await count in function
	ParallelizableCount int      // How many could be concurrent
	AwaitLines          []int    // Lines of parallelizable awaits
	AwaitTargets        []string // Function names being awaited

	// For nested-loops pattern
	NestingDepth  int // Depth of loop nesting
	OuterLoopLine int // Line of outermost loop
	InnerLoopLine int // Line of innermost loop

	// For expensive-call-in-loop pattern
	ExpensiveCall   string // The expensive function name
	LoopLine        int    // Line of containing loop
	CallLine        int    // Line of the expensive call
	ExpenseCategory string // "regex", "io", "network", "parse"
}

PatternDetails provides additional context for specific patterns

type PerformanceAnalyzer

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

PerformanceAnalyzer detects performance anti-patterns in code via AST analysis. Phase 1 focuses on cross-language patterns detectable without type inference: - Sequential awaits that could be parallelized - Await expressions inside loops - Expensive function calls inside loops - Nested loops (O(n²) complexity risk)

func NewPerformanceAnalyzer

func NewPerformanceAnalyzer() *PerformanceAnalyzer

NewPerformanceAnalyzer creates a new performance analyzer with default configurations

func (*PerformanceAnalyzer) AnalyzeFile

func (pa *PerformanceAnalyzer) AnalyzeFile(fileInfo *types.FileInfo, functions []*FunctionAnalysis) []PerformancePattern

AnalyzeFile analyzes all functions in a file for performance anti-patterns

func (*PerformanceAnalyzer) AnalyzeFunction

func (pa *PerformanceAnalyzer) AnalyzeFunction(analysis *FunctionAnalysis) []PerformancePattern

AnalyzeFunction analyzes a single function for performance anti-patterns

func (*PerformanceAnalyzer) IsAwaitNode

func (pa *PerformanceAnalyzer) IsAwaitNode(nodeType string) bool

IsAwaitNode checks if a node type represents an await expression

func (*PerformanceAnalyzer) IsLoopNode

func (pa *PerformanceAnalyzer) IsLoopNode(nodeType string) bool

IsLoopNode checks if a node type represents a loop construct

type PerformanceImpact

type PerformanceImpact string

PerformanceImpact represents the potential performance cost of a dependency

const (
	PerfImpactLow      PerformanceImpact = "low"
	PerfImpactMedium   PerformanceImpact = "medium"
	PerfImpactHigh     PerformanceImpact = "high"
	PerfImpactCritical PerformanceImpact = "critical"
	PerfImpactUnknown  PerformanceImpact = "unknown"
)

type PerformancePattern

type PerformancePattern struct {
	Type        string          // Pattern type
	Symbol      string          // Containing function name
	SymbolID    types.SymbolID  // Symbol ID for drill-down
	FilePath    string          // File path
	Line        int             // Line number
	Severity    string          // "high", "medium", "low"
	Description string          // Human-readable description
	Language    string          // Language where detected
	Suggestion  string          // Recommended fix
	Details     *PatternDetails // Additional details
}

PerformancePattern represents a detected performance anti-pattern

type PythonAnalyzer added in v0.4.0

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

PythonAnalyzer implements language-specific analysis for Python code Uses Tree-Sitter for parsing with enhanced semantic analysis

func NewPythonAnalyzer added in v0.4.0

func NewPythonAnalyzer() *PythonAnalyzer

NewPythonAnalyzer creates a new Python analyzer

func (*PythonAnalyzer) AnalyzeCalls added in v0.4.0

func (pa *PythonAnalyzer) AnalyzeCalls(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.FunctionCall, error)

AnalyzeCalls analyzes function call relationships

func (*PythonAnalyzer) AnalyzeContains added in v0.4.0

func (pa *PythonAnalyzer) AnalyzeContains(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeContains analyzes containment relationships

func (*PythonAnalyzer) AnalyzeDependencies added in v0.4.0

func (pa *PythonAnalyzer) AnalyzeDependencies(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.SymbolDependency, error)

AnalyzeDependencies analyzes import dependencies

func (*PythonAnalyzer) AnalyzeExtends added in v0.4.0

func (pa *PythonAnalyzer) AnalyzeExtends(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeExtends analyzes Python inheritance relationships

func (*PythonAnalyzer) AnalyzeImplements added in v0.4.0

func (pa *PythonAnalyzer) AnalyzeImplements(symbol *types.UniversalSymbolNode, content, filePath string) ([]types.CompositeSymbolID, error)

AnalyzeImplements analyzes interface implementation (Python uses duck typing)

func (*PythonAnalyzer) ExtractSymbols added in v0.4.0

func (pa *PythonAnalyzer) ExtractSymbols(fileID types.FileID, content, filePath string) ([]*types.UniversalSymbolNode, error)

ExtractSymbols extracts all symbols from Python code

func (*PythonAnalyzer) GetLanguageName added in v0.4.0

func (pa *PythonAnalyzer) GetLanguageName() string

GetLanguageName returns the language name

type ReferenceProvider

type ReferenceProvider interface {
	GetEnhancedSymbol(symbolID types.SymbolID) *types.EnhancedSymbol
}

ReferenceProvider provides access to symbol reference data

type ReferenceType

type ReferenceType uint8

ReferenceType represents different types of symbol references

const (
	RefTypeUnknown        ReferenceType = iota
	RefTypeCall                         // Function call
	RefTypeAccess                       // Variable/field access
	RefTypeType                         // Type reference
	RefTypeInheritance                  // Inheritance reference
	RefTypeImplementation               // Interface implementation
	RefTypeImport                       // Import reference
	RefTypeAnnotation                   // Annotation reference
)

func (ReferenceType) String

func (rt ReferenceType) String() string

String returns string representation of reference type

type RelationshipAnalyzer

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

RelationshipAnalyzer analyzes code to extract symbol relationships for the Universal Symbol Graph

func NewRelationshipAnalyzer

func NewRelationshipAnalyzer(
	universalGraph *core.UniversalSymbolGraph,
	symbolLinker SymbolLinkerInterface,
	fileService FileServiceInterface,
	config AnalysisConfig,
) *RelationshipAnalyzer

NewRelationshipAnalyzer creates a new relationship analyzer

func (*RelationshipAnalyzer) AnalyzeFile

func (ra *RelationshipAnalyzer) AnalyzeFile(fileID types.FileID) error

AnalyzeFile analyzes a single file and extracts all relationships

func (*RelationshipAnalyzer) AnalyzeProject

func (ra *RelationshipAnalyzer) AnalyzeProject(fileIDs []types.FileID) error

AnalyzeProject analyzes all files in a project

func (*RelationshipAnalyzer) Clear

func (ra *RelationshipAnalyzer) Clear()

Clear clears all analysis data

func (*RelationshipAnalyzer) GetAnalysisStats

func (ra *RelationshipAnalyzer) GetAnalysisStats() AnalysisStats

GetAnalysisStats returns statistics about the relationship analysis

func (*RelationshipAnalyzer) UpdateConfig

func (ra *RelationshipAnalyzer) UpdateConfig(config AnalysisConfig) error

UpdateConfig updates the analysis configuration

type ResolvedReference

type ResolvedReference struct {
	Target         types.CompositeSymbolID `json:"target"`          // Target symbol ID
	SourceLocation types.SymbolLocation    `json:"source_location"` // Where the reference occurs
	ImportPath     string                  `json:"import_path"`     // Import path if applicable
	Confidence     float64                 `json:"confidence"`      // Confidence in resolution (0-1)
	RefType        ReferenceType           `json:"ref_type"`        // Type of reference
}

ResolvedReference represents a resolved symbol reference

type SecurityRisk

type SecurityRisk string

SecurityRisk represents security implications of external dependencies

const (
	SecurityLow      SecurityRisk = "low"
	SecurityMedium   SecurityRisk = "medium"
	SecurityHigh     SecurityRisk = "high"
	SecurityCritical SecurityRisk = "critical"
	SecurityUnknown  SecurityRisk = "unknown"
)

type SideEffectAnalyzer

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

SideEffectAnalyzer performs conservative side-effect analysis on functions.

Design principle: If we say it's pure, it IS pure. - Unknown functions are marked with SideEffectExternalCall - Any uncertainty marks the function as potentially impure - Only well-analyzed local code can be marked pure

func NewSideEffectAnalyzer

func NewSideEffectAnalyzer(language string, config *SideEffectAnalyzerConfig) *SideEffectAnalyzer

NewSideEffectAnalyzer creates a new analyzer for the given language

func (*SideEffectAnalyzer) AddLocalVariable

func (sa *SideEffectAnalyzer) AddLocalVariable(name string, line int)

AddLocalVariable registers a local variable declaration

func (*SideEffectAnalyzer) AddParameter

func (sa *SideEffectAnalyzer) AddParameter(name string, index int)

AddParameter registers a function parameter for tracking

func (*SideEffectAnalyzer) BeginFunction

func (sa *SideEffectAnalyzer) BeginFunction(name, file string, startLine, endLine int)

BeginFunction starts analysis of a new function

func (*SideEffectAnalyzer) EndFunction

func (sa *SideEffectAnalyzer) EndFunction() *types.SideEffectInfo

EndFunction completes analysis of current function and returns results

func (*SideEffectAnalyzer) EnterScope

func (sa *SideEffectAnalyzer) EnterScope()

EnterScope pushes current locals to outer scope (for closure tracking)

func (*SideEffectAnalyzer) ExitScope

func (sa *SideEffectAnalyzer) ExitScope()

ExitScope pops scope

func (*SideEffectAnalyzer) GetResult

func (sa *SideEffectAnalyzer) GetResult(file string, line int) *types.SideEffectInfo

GetResult returns analysis for a specific function

func (*SideEffectAnalyzer) GetResults

func (sa *SideEffectAnalyzer) GetResults() map[string]*types.SideEffectInfo

GetResults returns all analysis results

func (*SideEffectAnalyzer) RecordAccess

func (sa *SideEffectAnalyzer) RecordAccess(
	identifier string,
	fieldPath []string,
	accessType types.AccessType,
	line, column int,
)

RecordAccess records a read or write access

func (*SideEffectAnalyzer) RecordChannelOp

func (sa *SideEffectAnalyzer) RecordChannelOp(line int)

RecordChannelOp records a channel send or receive (Go)

func (*SideEffectAnalyzer) RecordDefer

func (sa *SideEffectAnalyzer) RecordDefer()

RecordDefer records a defer statement (Go)

func (*SideEffectAnalyzer) RecordDynamicCall

func (sa *SideEffectAnalyzer) RecordDynamicCall(description string, line, column int)

RecordDynamicCall records a call through interface/function pointer

func (*SideEffectAnalyzer) RecordErrorReturn

func (sa *SideEffectAnalyzer) RecordErrorReturn()

RecordErrorReturn records that function returns an error

func (*SideEffectAnalyzer) RecordFunctionCall

func (sa *SideEffectAnalyzer) RecordFunctionCall(
	funcName string,
	qualifier string,
	isMethod bool,
	line, column int,
)

RecordFunctionCall records a function call and checks if it's known pure/impure Phase 1: Record all calls, classify as known pure/impure or unresolved Phase 2 will resolve unresolved calls using complete symbol table

func (*SideEffectAnalyzer) RecordThrow

func (sa *SideEffectAnalyzer) RecordThrow(throwType string, line, column int)

RecordThrow records a throw/panic/raise statement

func (*SideEffectAnalyzer) RecordTryFinally

func (sa *SideEffectAnalyzer) RecordTryFinally()

RecordTryFinally records a try-finally block

func (*SideEffectAnalyzer) SetReceiver

func (sa *SideEffectAnalyzer) SetReceiver(name, receiverType string)

SetReceiver sets the receiver name and type for method analysis

type SideEffectAnalyzerConfig

type SideEffectAnalyzerConfig struct {
	// TrustAnnotations: if true, @pure/@side-effect annotations override analysis
	TrustAnnotations bool

	// StrictMode: if true, any uncertainty marks function as impure
	// (recommended for high-signal analysis)
	StrictMode bool

	// TrackFieldAccess: if true, track field-level access patterns
	TrackFieldAccess bool

	// MaxAccessesPerFunction: limit to prevent memory issues on huge functions
	MaxAccessesPerFunction int
}

SideEffectAnalyzerConfig controls analyzer behavior

func DefaultSideEffectAnalyzerConfig

func DefaultSideEffectAnalyzerConfig() *SideEffectAnalyzerConfig

DefaultSideEffectAnalyzerConfig returns conservative default settings

type SymbolLinkerInterface

type SymbolLinkerInterface interface {
	// ResolveReferences resolves symbol references for a given symbol
	ResolveReferences(symbolID types.CompositeSymbolID) ([]ResolvedReference, error)

	// ResolveDependencies resolves dependencies for a symbol
	ResolveDependencies(symbolID types.CompositeSymbolID) ([]types.SymbolDependency, error)

	// ResolveImports resolves import statements for a file
	ResolveImports(fileID types.FileID) ([]ImportResolution, error)
}

SymbolLinkerInterface defines the interface for symbol linking functionality

type SymbolMetrics

type SymbolMetrics struct {
	SymbolID types.SymbolID   `json:"symbol_id"`
	Name     string           `json:"name"`
	Type     types.SymbolType `json:"type"`
	FileID   types.FileID     `json:"file_id"`
	FilePath string           `json:"file_path"`

	// Core metrics
	Quality      CodeQualityMetrics  `json:"quality"`
	Dependencies DependencyMetrics   `json:"dependencies"`
	Architecture ArchitectureMetrics `json:"architecture"`

	// Additional context
	ScopeChain []types.ScopeInfo `json:"scope_chain"`
	Tags       []string          `json:"tags"`       // HIGH_COMPLEXITY, PUBLIC_API, etc.
	RiskScore  int               `json:"risk_score"` // 0-10 risk assessment

	// Timestamps for caching
	CalculatedAt int64 `json:"calculated_at"`
	IsStale      bool  `json:"is_stale"`
}

SymbolMetrics combines all metrics for a symbol

type TestFilePatterns

type TestFilePatterns struct {
	// SuffixPatterns maps file extensions to suffix patterns (without extension)
	// e.g., ".go" -> ["_test"] matches "*_test.go"
	SuffixPatterns map[string][]string

	// PrefixPatterns maps file extensions to prefix patterns
	// e.g., ".py" -> ["test_"] matches "test_*.py"
	PrefixPatterns map[string][]string

	// DirectoryPatterns are directory path patterns that indicate test files
	// e.g., "/tests/", "/__tests__/"
	DirectoryPatterns []string

	// CustomMatcher is an optional function for custom test file detection
	// If provided, it's called after built-in patterns; returns true if file is a test
	CustomMatcher func(filePath string) bool
}

TestFilePatterns defines patterns for detecting test files by language

func DefaultTestFilePatterns

func DefaultTestFilePatterns() *TestFilePatterns

DefaultTestFilePatterns returns the default test file detection patterns

type TransitiveDependencyResolver

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

TransitiveDependencyResolver handles complex dependency resolution

Jump to

Keyboard shortcuts

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