Documentation
¶
Index ¶
- Constants
- Variables
- func CalculateCouplingMetrics(ctx context.Context, graph *DependencyGraph, topology *DependencyTopology, ...) error
- func CalculateDIAntipatterns(ast *parser.Node, filePath string) ([]domain.DIAntipatternFinding, error)
- func CalculateDIAntipatternsWithConfig(ast *parser.Node, filePath string, options *DIAntipatternOptions) ([]domain.DIAntipatternFinding, error)
- func CalculateFilesCBO(asts map[string]*parser.Node, options *CBOOptions) (map[string][]*CBOResult, error)
- func ExtractAttributeName(attrNode *parser.Node) string
- func FindClassMethods(classNode *parser.Node) []*parser.Node
- func FindInitMethod(classNode *parser.Node) *parser.Node
- func GenerateSummary(findings []domain.DIAntipatternFinding, filesAnalyzed int) domain.DIAntipatternSummary
- func GetCycleBreakingSuggestions(result *CircularDependencyResult) []string
- func GroupFindingsByReason(findings []*DeadCodeFinding) map[DeadCodeReason][]*DeadCodeFinding
- func HasCircularDependencies(graph *DependencyGraph) bool
- func IsBoilerplateLabel(label string) bool
- func PopulateLogicalLines(result *RawMetricsResult, ast *parser.Node)
- func SortFindings(findings []domain.DIAntipatternFinding, sortBy domain.SortCriteria) []domain.DIAntipatternFinding
- type AggregateComplexity
- type AggregateRawMetrics
- type BasicBlock
- type BridgeModuleMetrics
- type CBOAnalyzer
- type CBOOptions
- type CBOResult
- type CFG
- type CFGBuilder
- type CFGFeatures
- type CFGScope
- type CFGVisitor
- type CircularDependency
- type CircularDependencyDetector
- type CircularDependencyResult
- type ClassificationResult
- type CloneClassifier
- func (c *CloneClassifier) ClassifyClone(f1, f2 *CodeFragment) *ClassificationResult
- func (c *CloneClassifier) ClassifyCloneSimple(f1, f2 *CodeFragment) (CloneType, float64, float64)
- func (c *CloneClassifier) SetSemanticAnalyzer(analyzer SimilarityAnalyzer)
- func (c *CloneClassifier) SetStructuralAnalyzer(analyzer SimilarityAnalyzer)
- func (c *CloneClassifier) SetSyntacticAnalyzer(analyzer SimilarityAnalyzer)
- func (c *CloneClassifier) SetTextualAnalyzer(analyzer SimilarityAnalyzer)
- type CloneClassifierConfig
- type CloneDetectionResult
- type CloneDetectionStatistics
- type CloneDetector
- func (cd *CloneDetector) DetectClones(fragments []*CodeFragment) *CloneDetectionResult
- func (cd *CloneDetector) DetectClonesWithContext(ctx context.Context, fragments []*CodeFragment) *CloneDetectionResult
- func (cd *CloneDetector) DetectClonesWithLSH(ctx context.Context, fragments []*CodeFragment) *CloneDetectionResult
- func (cd *CloneDetector) ExtractFragments(astNodes []*parser.Node, filePath string) []*CodeFragment
- func (cd *CloneDetector) ExtractFragmentsWithSource(astNodes []*parser.Node, filePath string, sourceCode []byte) []*CodeFragment
- func (cd *CloneDetector) GetStatistics() map[string]interface{}
- func (cd *CloneDetector) SetBatchSizeLarge(size int)
- func (cd *CloneDetector) SetUseLSH(enabled bool)
- type CloneDetectorConfig
- type CloneGroup
- type ClonePair
- type CloneType
- type CodeFragment
- type CodeLocation
- type CognitiveComplexityResult
- type CommunityDirectedEdge
- type CommunityGraph
- type CommunityGraphBuildOptions
- type CommunityPartition
- type CommunityPartitionMetrics
- type ComplexityAnalyzer
- func (ca *ComplexityAnalyzer) AnalyzeAndReport(cfgs ControlFlowGraphs) error
- func (ca *ComplexityAnalyzer) AnalyzeFunction(cfg *CFG) *ComplexityResult
- func (ca *ComplexityAnalyzer) AnalyzeFunctions(cfgs []*CFG) []*ComplexityResult
- func (ca *ComplexityAnalyzer) CheckComplexityLimits(cfgs []*CFG) (bool, []*ComplexityResult)
- func (ca *ComplexityAnalyzer) GenerateReport(cfgs ControlFlowGraphs) *reporter.ComplexityReport
- func (ca *ComplexityAnalyzer) GetConfiguration() *config.Config
- func (ca *ComplexityAnalyzer) SetOutput(output io.Writer) error
- func (ca *ComplexityAnalyzer) UpdateConfiguration(cfg *config.Config) error
- type ComplexityResult
- func CalculateComplexity(cfg *CFG) *ComplexityResult
- func CalculateComplexityWithConfig(cfg *CFG, complexityConfig *config.ComplexityConfig) *ComplexityResult
- func CalculateFileComplexity(cfgs []*CFG) []*ComplexityResult
- func CalculateFileComplexityWithConfig(cfgs []*CFG, complexityConfig *config.ComplexityConfig) []*ComplexityResult
- type ConcreteDependencyDetector
- type ConstructorAnalyzer
- type ControlFlowGraphs
- type CouplingMetricsCalculator
- type CouplingMetricsOptions
- type CycleSeverity
- type DFABuilder
- type DFAFeatures
- type DFAInfo
- type DIAntipatternDetector
- type DIAntipatternOptions
- type DeadCodeDetector
- type DeadCodeFinding
- type DeadCodeReason
- type DeadCodeResult
- type DefUseChain
- type DefUseKind
- type DefUsePair
- type DependencyChain
- type DependencyEdge
- type DependencyEdgeType
- type DependencyGraph
- func (g *DependencyGraph) AddDependency(from, to string, edgeType DependencyEdgeType, importInfo *ImportInfo)
- func (g *DependencyGraph) AddModule(moduleName, filePath string) *ModuleNode
- func (g *DependencyGraph) Clone() *DependencyGraph
- func (g *DependencyGraph) GetDependencies(moduleName string) []string
- func (g *DependencyGraph) GetDependencyChain(from, to string) []string
- func (g *DependencyGraph) GetDependents(moduleName string) []string
- func (g *DependencyGraph) GetLeafModules() []string
- func (g *DependencyGraph) GetModule(moduleName string) *ModuleNode
- func (g *DependencyGraph) GetModuleNames() []string
- func (g *DependencyGraph) GetModulesInCycles() []string
- func (g *DependencyGraph) GetPackages() []string
- func (g *DependencyGraph) GetRootModules() []string
- func (g *DependencyGraph) HasCycle() bool
- func (g *DependencyGraph) HasNode(moduleName string) bool
- func (g *DependencyGraph) NodeCount() int
- func (g *DependencyGraph) NodeIDs() []string
- func (g *DependencyGraph) Predecessors(moduleName string) []string
- func (g *DependencyGraph) String() string
- func (g *DependencyGraph) Successors(moduleName string) []string
- func (g *DependencyGraph) Validate() error
- type DependencyTopology
- type Edge
- type EdgeType
- type FileComplexityAnalyzer
- type GroupingMode
- type HiddenDependencyDetector
- type ImportInfo
- type LCOMAnalyzer
- type LCOMOptions
- type LCOMResult
- type LayerMismatchMetrics
- type LeidenOptions
- type LeidenResult
- type ModuleAnalysisOptions
- type ModuleAnalyzer
- type ModuleMetrics
- type ModuleNode
- type NestingDepthResult
- type PackageMismatchMetrics
- type ParsedModule
- type PythonCostModel
- type RawMetricsResult
- type ReExportEntry
- type ReExportMap
- type ReExportResolver
- type ReachabilityAnalyzer
- type ReachabilityResult
- type ScopedCFG
- type SemanticSimilarityAnalyzer
- func (s *SemanticSimilarityAnalyzer) BuildCFG(node *parser.Node) (*CFG, error)
- func (s *SemanticSimilarityAnalyzer) BuildDFA(cfg *CFG) (*DFAInfo, error)
- func (s *SemanticSimilarityAnalyzer) ComputeSimilarity(f1, f2 *CodeFragment) float64
- func (s *SemanticSimilarityAnalyzer) ExtractDFAFeaturesFromInfo(info *DFAInfo) *DFAFeatures
- func (s *SemanticSimilarityAnalyzer) ExtractFeatures(cfg *CFG) *CFGFeatures
- func (s *SemanticSimilarityAnalyzer) GetName() string
- func (s *SemanticSimilarityAnalyzer) IsDFAEnabled() bool
- func (s *SemanticSimilarityAnalyzer) SetEnableDFA(enable bool)
- func (s *SemanticSimilarityAnalyzer) SetMinCyclomaticComplexity(n int)
- func (s *SemanticSimilarityAnalyzer) SetWeights(cfgWeight, dfaWeight float64)
- type ServiceLocatorDetector
- type SeverityLevel
- type SimilarityAnalyzer
- type StructuralSimilarityAnalyzer
- func (s *StructuralSimilarityAnalyzer) ComputeDistance(f1, f2 *CodeFragment) float64
- func (s *StructuralSimilarityAnalyzer) ComputeSimilarity(f1, f2 *CodeFragment) float64
- func (s *StructuralSimilarityAnalyzer) GetAnalyzer() *coreapted.APTEDAnalyzer
- func (s *StructuralSimilarityAnalyzer) GetName() string
- type SystemMetrics
- type TreeConverter
- type VarReference
- type WeightedNeighbor
Constants ¶
const ( EdgeNormal = corecfg.EdgeNormal EdgeCondTrue = corecfg.EdgeCondTrue EdgeCondFalse = corecfg.EdgeCondFalse EdgeException = corecfg.EdgeException EdgeLoop = corecfg.EdgeLoop EdgeBreak = corecfg.EdgeBreak EdgeContinue = corecfg.EdgeContinue EdgeReturn = corecfg.EdgeReturn )
const ( LabelFunctionBody = "func_body" LabelClassBody = "class_body" LabelUnreachable = "unreachable" LabelEntry = "ENTRY" LabelExit = "EXIT" // Conditional labels LabelIfThen = "if_then" LabelIfMerge = "if_merge" // Loop-related labels LabelLoopHeader = "loop_header" LabelLoopBody = "loop_body" LabelLoopExit = "loop_exit" LabelLoopElse = "loop_else" // Exception-related labels LabelTryBlock = "try_block" LabelExceptBlock = "except_block" LabelFinallyBlock = "finally_block" LabelTryElse = "try_else" // Advanced construct labels LabelWithSetup = "with_setup" LabelWithBody = "with_body" LabelWithTeardown = "with_teardown" LabelMatchEval = "match_eval" LabelMatchCase = "match_case" LabelMatchMerge = "match_merge" )
Block label constants to avoid magic strings
const ( DefKindAssign = coredfa.DefKindAssign DefKindAugAssign = coredfa.DefKindAugAssign DefKindParam = coredfa.DefKindParam DefKindImport = coredfa.DefKindImport DefKindFor = coredfa.DefKindFor DefKindWith = coredfa.DefKindWith DefKindExcept = coredfa.DefKindExcept DefKindPattern = coredfa.DefKindPattern UseKindLoad = coredfa.UseKindLoad UseKindCall = coredfa.UseKindCall UseKindAttribute = coredfa.UseKindAttribute UseKindSubscript = coredfa.UseKindSubscript )
Variables ¶
var ( NewBasicBlock = corecfg.NewBasicBlock NewCFG = corecfg.NewCFG )
var ( NewVarReference = coredfa.NewVarReference NewDefUsePair = coredfa.NewDefUsePair NewDefUseChain = coredfa.NewDefUseChain NewDFAInfo = coredfa.NewDFAInfo )
Functions ¶
func CalculateCouplingMetrics ¶
func CalculateCouplingMetrics( ctx context.Context, graph *DependencyGraph, topology *DependencyTopology, options *CouplingMetricsOptions, ) error
CalculateCouplingMetrics is a convenience function for calculating metrics.
func CalculateDIAntipatterns ¶ added in v1.16.0
func CalculateDIAntipatterns(ast *parser.Node, filePath string) ([]domain.DIAntipatternFinding, error)
CalculateDIAntipatterns is a convenience function for detecting DI anti-patterns with default options
func CalculateDIAntipatternsWithConfig ¶ added in v1.16.0
func CalculateDIAntipatternsWithConfig(ast *parser.Node, filePath string, options *DIAntipatternOptions) ([]domain.DIAntipatternFinding, error)
CalculateDIAntipatternsWithConfig detects DI anti-patterns with custom configuration
func CalculateFilesCBO ¶
func CalculateFilesCBO(asts map[string]*parser.Node, options *CBOOptions) (map[string][]*CBOResult, error)
CalculateFilesCBO calculates CBO for multiple files
func ExtractAttributeName ¶ added in v1.16.0
ExtractAttributeName extracts the attribute/method name from an Attribute node. This is a shared helper used by concrete dependency and service locator detectors.
func FindClassMethods ¶ added in v1.16.0
FindClassMethods finds all methods (functions) defined in a class body. This is a shared helper for DI anti-pattern detectors.
func FindInitMethod ¶ added in v1.16.0
FindInitMethod finds the __init__ method in a class body. Returns nil if no __init__ method is found. This is a shared helper for DI anti-pattern detectors.
func GenerateSummary ¶ added in v1.16.0
func GenerateSummary(findings []domain.DIAntipatternFinding, filesAnalyzed int) domain.DIAntipatternSummary
GenerateSummary generates summary statistics from findings
func GetCycleBreakingSuggestions ¶
func GetCycleBreakingSuggestions(result *CircularDependencyResult) []string
GetCycleBreakingSuggestions suggests module refactoring to break cycles
func GroupFindingsByReason ¶
func GroupFindingsByReason(findings []*DeadCodeFinding) map[DeadCodeReason][]*DeadCodeFinding
GroupFindingsByReason groups findings by their reason
func HasCircularDependencies ¶
func HasCircularDependencies(graph *DependencyGraph) bool
HasCircularDependencies quickly checks if a graph has any circular dependencies
func IsBoilerplateLabel ¶ added in v1.9.2
IsBoilerplateLabel checks if a tree node label represents boilerplate code. Boilerplate includes type annotations, decorators, and type hint related nodes. This is the single source of truth for boilerplate detection, used by both the cost model and any other components that need to identify boilerplate.
func PopulateLogicalLines ¶ added in v1.15.0
func PopulateLogicalLines(result *RawMetricsResult, ast *parser.Node)
PopulateLogicalLines updates raw metrics with LLOC derived from the parsed AST.
func SortFindings ¶ added in v1.16.0
func SortFindings(findings []domain.DIAntipatternFinding, sortBy domain.SortCriteria) []domain.DIAntipatternFinding
SortFindings sorts findings by the specified criteria
Types ¶
type AggregateComplexity ¶
type AggregateComplexity struct {
TotalFunctions int
AverageComplexity float64
MaxComplexity int
MinComplexity int
HighRiskCount int
MediumRiskCount int
LowRiskCount int
}
AggregateComplexity calculates aggregate metrics for multiple functions
func CalculateAggregateComplexity ¶
func CalculateAggregateComplexity(results []*ComplexityResult) *AggregateComplexity
CalculateAggregateComplexity computes aggregate complexity metrics
type AggregateRawMetrics ¶ added in v1.15.0
type AggregateRawMetrics struct {
FilesAnalyzed int
SLOC int
LLOC int
CommentLines int
DocstringLines int
BlankLines int
TotalLines int
CommentRatio float64
}
AggregateRawMetrics contains aggregated raw code metrics across files.
func CalculateAggregateRawMetrics ¶ added in v1.15.0
func CalculateAggregateRawMetrics(results []*RawMetricsResult) *AggregateRawMetrics
CalculateAggregateRawMetrics aggregates raw code metrics across files.
type BasicBlock ¶
type BasicBlock = corecfg.BasicBlock
CFG data structures and traversal are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific construction stays local.
type BridgeModuleMetrics ¶ added in v1.25.0
type BridgeModuleMetrics struct {
Module string
CommunityID string
CrossCommunityEdges int
TargetCommunities []string
}
BridgeModuleMetrics describes a module that couples multiple communities.
type CBOAnalyzer ¶
type CBOAnalyzer struct {
// contains filtered or unexported fields
}
CBOAnalyzer analyzes class coupling in Python code
func NewCBOAnalyzer ¶
func NewCBOAnalyzer(options *CBOOptions) *CBOAnalyzer
NewCBOAnalyzer creates a new CBO analyzer
func (*CBOAnalyzer) AnalyzeClasses ¶
AnalyzeClasses analyzes CBO for all classes in the given AST
type CBOOptions ¶
type CBOOptions struct {
IncludeBuiltins bool
IncludeImports bool
PublicClassesOnly bool
GroupNamespaceImports bool
ExcludePatterns []string
LowThreshold int // Default: 3 (industry standard)
MediumThreshold int // Default: 7 (industry standard)
}
CBOOptions configures CBO analysis behavior
func DefaultCBOOptions ¶
func DefaultCBOOptions() *CBOOptions
DefaultCBOOptions returns default CBO analysis options Threshold values are sourced from domain/defaults.go
type CBOResult ¶
type CBOResult struct {
// Core CBO metric
CouplingCount int
// Class information
ClassName string
FilePath string
StartLine int
EndLine int
// Dependency breakdown
InheritanceDependencies int
TypeHintDependencies int
InstantiationDependencies int
AttributeAccessDependencies int
ImportDependencies int
// Detailed dependency list
DependentClasses []string
// Risk assessment
RiskLevel string // "low", "medium", "high"
// Additional class metadata
IsAbstract bool
BaseClasses []string
Methods []string
Attributes []string
}
CBOResult holds CBO (Coupling Between Objects) metrics for a class
func CalculateCBO ¶
CalculateCBO is a convenience function for calculating CBO with default config
func CalculateCBOWithConfig ¶
func CalculateCBOWithConfig(ast *parser.Node, filePath string, options *CBOOptions) ([]*CBOResult, error)
CalculateCBOWithConfig calculates CBO with custom configuration
type CFG ¶
CFG data structures and traversal are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific construction stays local.
type CFGBuilder ¶
type CFGBuilder struct {
// contains filtered or unexported fields
}
CFGBuilder builds control flow graphs from AST nodes
func (*CFGBuilder) Build ¶
func (b *CFGBuilder) Build(node *parser.Node) (*CFG, error)
Build constructs a CFG from an AST node
func (*CFGBuilder) BuildAll ¶
func (b *CFGBuilder) BuildAll(node *parser.Node) (ControlFlowGraphs, error)
BuildAll builds CFGs for every supported execution scope in source order.
func (*CFGBuilder) BuildExecutionFragment ¶ added in v1.30.0
func (b *CFGBuilder) BuildExecutionFragment(node *parser.Node) (*CFG, error)
BuildExecutionFragment constructs the single graph used for semantic clone comparison. Class suites reached while executing the fragment are inlined, matching Python's class-definition execution; nested function bodies remain separate because defining a function does not execute its body.
func (*CFGBuilder) SetLogger ¶
func (b *CFGBuilder) SetLogger(logger *log.Logger)
SetLogger sets an optional logger for error reporting
type CFGFeatures ¶ added in v1.5.0
type CFGFeatures struct {
BlockCount int // Number of basic blocks
EdgeCount int // Number of edges
EdgeTypeCounts map[EdgeType]int // Distribution of edge types
CyclomaticNumber int // Cyclomatic complexity: V(G) = E - N + 2P
BranchingFactor float64 // Average number of successors per block
LoopEdgeCount int // Number of loop back-edges
ConditionalCount int // Number of conditional branches
}
CFGFeatures captures key structural properties of a control flow graph
type CFGScope ¶ added in v1.30.0
type CFGScope struct {
Kind domain.AnalysisScopeKind
Name string
StartLine int
StartColumn int
}
CFGScope is the canonical identity of one Python execution scope. Name is user-facing and may repeat; source location and kind keep identities distinct without leaking encoded map keys into reports.
type CFGVisitor ¶
CFG data structures and traversal are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific construction stays local.
type CircularDependency ¶
type CircularDependency struct {
Modules []string // Modules involved in the cycle
Dependencies []DependencyChain // The dependency chains that form the cycle
Severity CycleSeverity // Severity level of this cycle
Size int // Number of modules in the cycle
Description string // Human-readable description
}
CircularDependency represents a circular dependency relationship
func FindSimpleCycles ¶
func FindSimpleCycles(graph *DependencyGraph) []*CircularDependency
FindSimpleCycles finds all simple cycles (2-module cycles) in the graph
type CircularDependencyDetector ¶
type CircularDependencyDetector struct {
// contains filtered or unexported fields
}
CircularDependencyDetector enriches cycles detected by polyscan core.
func NewCircularDependencyDetector ¶
func NewCircularDependencyDetector(graph *DependencyGraph) *CircularDependencyDetector
NewCircularDependencyDetector creates a new circular dependency detector
func (*CircularDependencyDetector) DetectCircularDependencies ¶
func (cdd *CircularDependencyDetector) DetectCircularDependencies() *CircularDependencyResult
DetectCircularDependencies detects all circular dependencies in the graph
type CircularDependencyResult ¶
type CircularDependencyResult struct {
HasCircularDependencies bool // True if any cycles were found
TotalCycles int // Total number of cycles detected
TotalModulesInCycles int // Total number of modules involved in cycles
CircularDependencies []*CircularDependency // All detected circular dependencies
// Severity breakdown
LowSeverityCycles int // Number of low severity cycles
MediumSeverityCycles int // Number of medium severity cycles
HighSeverityCycles int // Number of high severity cycles
CriticalSeverityCycles int // Number of critical severity cycles
// Most problematic cycles
LargestCycle *CircularDependency // Cycle with most modules
MostComplexCycle *CircularDependency // Cycle with most dependency chains
CoreInfrastructure []string // Modules that appear in multiple cycles
}
CircularDependencyResult contains the results of circular dependency analysis
func DetectCircularDependencies ¶
func DetectCircularDependencies(graph *DependencyGraph) *CircularDependencyResult
DetectCircularDependencies is a convenience function for detecting cycles in a graph
type ClassificationResult ¶ added in v1.5.0
type ClassificationResult struct {
CloneType CloneType
Similarity float64
Confidence float64
Analyzer string
}
ClassificationResult holds the result of clone classification
type CloneClassifier ¶ added in v1.5.0
type CloneClassifier struct {
// contains filtered or unexported fields
}
CloneClassifier orchestrates multi-dimensional clone classification. It uses different analyzers for each clone type and applies a cascading classification approach from fastest (Type-1) to slowest (Type-4).
func NewCloneClassifier ¶ added in v1.5.0
func NewCloneClassifier(config *CloneClassifierConfig) *CloneClassifier
NewCloneClassifier creates a new multi-dimensional clone classifier
func (*CloneClassifier) ClassifyClone ¶ added in v1.5.0
func (c *CloneClassifier) ClassifyClone(f1, f2 *CodeFragment) *ClassificationResult
ClassifyClone determines the clone type using cascading analysis. It returns the clone type, similarity score, and confidence. Classification order: Type-1 (fastest) -> Type-2 -> Type-3 -> Type-4 (slowest)
func (*CloneClassifier) ClassifyCloneSimple ¶ added in v1.5.0
func (c *CloneClassifier) ClassifyCloneSimple(f1, f2 *CodeFragment) (CloneType, float64, float64)
ClassifyCloneSimple is a simplified version that returns just CloneType, similarity, and confidence. This is for backward compatibility with existing code.
func (*CloneClassifier) SetSemanticAnalyzer ¶ added in v1.5.0
func (c *CloneClassifier) SetSemanticAnalyzer(analyzer SimilarityAnalyzer)
SetSemanticAnalyzer sets the semantic similarity analyzer (for testing)
func (*CloneClassifier) SetStructuralAnalyzer ¶ added in v1.5.0
func (c *CloneClassifier) SetStructuralAnalyzer(analyzer SimilarityAnalyzer)
SetStructuralAnalyzer sets the structural similarity analyzer (for testing)
func (*CloneClassifier) SetSyntacticAnalyzer ¶ added in v1.5.0
func (c *CloneClassifier) SetSyntacticAnalyzer(analyzer SimilarityAnalyzer)
SetSyntacticAnalyzer sets the syntactic similarity analyzer (for testing)
func (*CloneClassifier) SetTextualAnalyzer ¶ added in v1.5.0
func (c *CloneClassifier) SetTextualAnalyzer(analyzer SimilarityAnalyzer)
SetTextualAnalyzer sets the textual similarity analyzer (for testing)
type CloneClassifierConfig ¶ added in v1.5.0
type CloneClassifierConfig struct {
Type1Threshold float64
Type2Threshold float64
Type3Threshold float64
Type4Threshold float64
EnableTextualAnalysis bool
EnableSemanticAnalysis bool
EnableDFAAnalysis bool // Enable Data Flow Analysis for enhanced Type-4 detection
}
CloneClassifierConfig holds configuration for the clone classifier
type CloneDetectionResult ¶ added in v1.24.3
type CloneDetectionResult struct {
Pairs []*ClonePair
Groups []*CloneGroup
Statistics *CloneDetectionStatistics
}
CloneDetectionResult bundles the detected clone pairs and groups with the statistics derived from them. Wrapping the output prevents accidental use of raw fragment counts where detected clone counts are required.
type CloneDetectionStatistics ¶ added in v1.24.3
type CloneDetectionStatistics struct {
TotalFragments int
TotalClones int
TotalClonePairs int
TotalCloneGroups int
ClonesByType map[string]int
AverageSimilarity float64
}
CloneDetectionStatistics provides statistics computed during clone detection. It tracks only the data the detector itself can derive from the fragment and pair/group collections. Callers (e.g. service/clone_service.go) augment it with file/line/node counts gathered while reading sources.
type CloneDetector ¶
type CloneDetector struct {
// contains filtered or unexported fields
}
CloneDetector detects code clones using APTED algorithm
func NewCloneDetector ¶
func NewCloneDetector(config *CloneDetectorConfig) *CloneDetector
NewCloneDetector creates a new clone detector with the given configuration
func (*CloneDetector) DetectClones ¶
func (cd *CloneDetector) DetectClones(fragments []*CodeFragment) *CloneDetectionResult
DetectClones detects clones in the given code fragments
func (*CloneDetector) DetectClonesWithContext ¶
func (cd *CloneDetector) DetectClonesWithContext(ctx context.Context, fragments []*CodeFragment) *CloneDetectionResult
DetectClonesWithContext detects clones with context support for cancellation
func (*CloneDetector) DetectClonesWithLSH ¶
func (cd *CloneDetector) DetectClonesWithLSH(ctx context.Context, fragments []*CodeFragment) *CloneDetectionResult
DetectClonesWithLSH runs a two-stage pipeline using LSH for candidate generation, followed by APTED verification on candidates only. Falls back to exhaustive if misconfigured.
func (*CloneDetector) ExtractFragments ¶
func (cd *CloneDetector) ExtractFragments(astNodes []*parser.Node, filePath string) []*CodeFragment
ExtractFragments extracts code fragments from AST nodes
func (*CloneDetector) ExtractFragmentsWithSource ¶ added in v1.5.0
func (cd *CloneDetector) ExtractFragmentsWithSource(astNodes []*parser.Node, filePath string, sourceCode []byte) []*CodeFragment
ExtractFragmentsWithSource extracts code fragments from AST nodes with source content. Source content is needed for Type-1 clone classification and optional report output.
func (*CloneDetector) GetStatistics ¶
func (cd *CloneDetector) GetStatistics() map[string]interface{}
GetStatistics returns clone detection statistics as a map for backward compatibility with existing callers and tests. New code should prefer the structured CloneDetectionResult returned by DetectClones* methods.
func (*CloneDetector) SetBatchSizeLarge ¶
func (cd *CloneDetector) SetBatchSizeLarge(size int)
SetBatchSizeLarge sets the batch size for normal projects (used in testing)
func (*CloneDetector) SetUseLSH ¶
func (cd *CloneDetector) SetUseLSH(enabled bool)
SetUseLSH enables or disables LSH acceleration for clone detection
type CloneDetectorConfig ¶
type CloneDetectorConfig struct {
// Minimum number of lines for a code fragment to be considered
MinLines int
// Minimum number of AST nodes for a code fragment
MinNodes int
// Similarity thresholds for different clone types
Type1Threshold float64 // Usually > domain.DefaultType1CloneThreshold
Type2Threshold float64 // Usually > domain.DefaultType2CloneThreshold
Type3Threshold float64 // Usually > domain.DefaultType3CloneThreshold
Type4Threshold float64 // Usually > domain.DefaultType4CloneThreshold
// Minimum similarity threshold for clone reporting (user-configurable via --clone-threshold)
SimilarityThreshold float64
// Maximum edit distance allowed
MaxEditDistance float64
// Whether to ignore differences in literals
IgnoreLiterals bool
// Whether to ignore differences in identifiers
IgnoreIdentifiers bool
// Whether to skip docstrings from AST comparison (default: true)
// Docstrings are the first Expr(Constant(str)) in function/class/module bodies
SkipDocstrings bool
// Cost model to use for APTED
CostModelType string // "default", "python", "weighted"
// Performance tuning parameters
MaxClonePairs int // Maximum pairs to keep in memory
BatchSizeThreshold int // Minimum fragments to trigger batching
BatchSizeLarge int // Batch size for normal projects
BatchSizeSmall int // Batch size for large projects
LargeProjectSize int // Fragment count threshold for large projects
MaxGoroutines int // Goroutines for parallel pair comparison (0 = all CPUs)
// Grouping configuration
GroupingMode GroupingMode // Default: GroupingModeConnected
GroupingThreshold float64 // Default: Type3Threshold
KCoreK int // Default: 2
// LSH Configuration (optional, opt-in)
UseLSH bool // Enable LSH acceleration
LSHSimilarityThreshold float64 // Candidate threshold using MinHash similarity
LSHBands int // Number of LSH bands (default: 32)
LSHRows int // Rows per band (default: 4)
LSHMinHashCount int // Number of MinHash functions (default: 128)
LSHMaxCandidates int // Maximum candidates returned per LSH query
// Multi-dimensional classification (optional, opt-in)
EnableMultiDimensionalAnalysis bool // Enable multi-dimensional clone type classification
EnableTextualAnalysis bool // Enable Type-1 textual analysis (increases memory usage)
EnableSemanticAnalysis bool // Enable Type-4 semantic/CFG analysis (increases CPU usage)
EnableDFAAnalysis bool // Enable Data Flow Analysis for enhanced Type-4 detection
// Framework pattern handling (reduces false positives for dataclass, Pydantic, etc.)
ReduceBoilerplateSimilarity bool // Apply lower weight to boilerplate nodes (default: true)
BoilerplateMultiplier float64 // Cost multiplier for boilerplate nodes (default: 0.1)
}
CloneDetectorConfig holds configuration for clone detection
func DefaultCloneDetectorConfig ¶
func DefaultCloneDetectorConfig() *CloneDetectorConfig
DefaultCloneDetectorConfig returns default configuration
type CloneGroup ¶
type CloneGroup struct {
ID int // Unique identifier for this group
Fragments []*CodeFragment // All fragments in this group
CloneType CloneType // Primary type of clones in this group
Similarity float64 // Average similarity within the group
Size int // Number of fragments
}
CloneGroup represents a group of similar code fragments
func (*CloneGroup) AddFragment ¶
func (cg *CloneGroup) AddFragment(fragment *CodeFragment)
AddFragment adds a fragment to the clone group
type ClonePair ¶
type ClonePair struct {
Fragment1 *CodeFragment
Fragment2 *CodeFragment
Similarity float64 // Similarity score (0.0 to 1.0)
Distance float64 // Edit distance
CloneType CloneType // Type of clone detected
Confidence float64 // Confidence in the detection (0.0 to 1.0)
}
ClonePair represents a pair of similar code fragments
type CloneType ¶
type CloneType int
CloneType represents different types of code clones
const ( // Type1Clone - Identical code fragments (except whitespace and comments) Type1Clone CloneType = iota + 1 // Type2Clone - Syntactically identical but with different identifiers/literals Type2Clone // Type3Clone - Syntactically similar with small modifications Type3Clone // Type4Clone - Functionally similar but syntactically different Type4Clone )
type CodeFragment ¶
type CodeFragment struct {
Location *CodeLocation
ASTNode *parser.Node
TreeNode *coreapted.TreeNode
Content string // Original source code content
Hash string // FNV-64a hex hash of Type-1 normalized content; "" when no source content
Size int // Number of AST nodes
LineCount int // Number of source lines
Complexity int // Cyclomatic complexity (if applicable)
Features []string // Detector-populated clone feature cache for this fragment's tree
// contains filtered or unexported fields
}
CodeFragment represents a fragment of code
func NewCodeFragment ¶
func NewCodeFragment(location *CodeLocation, astNode *parser.Node, content string) *CodeFragment
NewCodeFragment creates a new code fragment
func (*CodeFragment) ItemID ¶ added in v1.27.0
func (f *CodeFragment) ItemID() int
ItemID returns the fragment's unique ID for core/clone grouping.
func (*CodeFragment) ItemLocation ¶ added in v1.27.0
func (f *CodeFragment) ItemLocation() coreclone.ItemLocation
ItemLocation returns the fragment's source location for core/clone grouping.
type CodeLocation ¶
CodeLocation represents a location in source code
func (*CodeLocation) String ¶
func (cl *CodeLocation) String() string
String returns string representation of CodeLocation
type CognitiveComplexityResult ¶ added in v1.14.0
type CognitiveComplexityResult struct {
// Total cognitive complexity score
Total int
// Function/method information
FunctionName string
StartLine int
EndLine int
}
CognitiveComplexityResult holds the cognitive complexity score for an execution scope.
func CalculateCognitiveComplexity ¶ added in v1.14.0
func CalculateCognitiveComplexity(scopeNode *parser.Node) *CognitiveComplexityResult
CalculateCognitiveComplexity computes cognitive complexity for an execution scope following the SonarSource specification, with one deliberate deviation for nested scopes (see below).
Rules:
- +1 (base increment) for: if, elif, else, for, while, except, break, continue, goto, ternary (IfExp), and each boolean operator sequence change
- +nesting level (nesting increment) for: if, ternary (IfExp), for, while, except, match/case, and lambdas (structures that increase nesting)
- Nesting level increases inside: if, elif, else, for, while, except, with, match/case, and lambda
Deviation from the SonarSource specification: nested function and class definitions are scope boundaries, so their control flow is NOT aggregated into the enclosing scope's score. The specification folds a nested function's complexity into its parent, but pyscn builds a separate CFG per nested function or class (see CFGBuilder.buildNestedScope) and reports it as its own scope, so aggregating here would double-count it and inflate parents that contain no control flow of their own. Lambdas have no separate scope, so they still contribute to the enclosing scope.
type CommunityDirectedEdge ¶ added in v1.25.0
CommunityDirectedEdge is a directed dependency edge between indexed nodes.
type CommunityGraph ¶ added in v1.25.0
type CommunityGraph struct {
NodeCount int
NodeNames []string
NameToIndex map[string]int
// UndirectedAdj holds weighted undirected adjacency lists for clustering.
// Each neighbor list is sorted by index for deterministic iteration.
UndirectedAdj [][]WeightedNeighbor
// DirectedEdges preserves directed import edges for cross-community
// in/out counts. Not collapsed into undirected form.
DirectedEdges []CommunityDirectedEdge
// TotalUndirectedWeight is the sum of undirected edge weights (each
// undirected pair counted once). Used as a modularity denominator hook.
TotalUndirectedWeight float64
}
CommunityGraph is a compact, integer-indexed graph derived from a DependencyGraph for community detection (e.g. Leiden) and cross-community metrics.
func BuildCommunityGraph ¶ added in v1.25.0
func BuildCommunityGraph(graph *DependencyGraph, opts *CommunityGraphBuildOptions) *CommunityGraph
BuildCommunityGraph constructs a CommunityGraph from a DependencyGraph. Returns an empty graph when graph is nil or has no modules.
type CommunityGraphBuildOptions ¶ added in v1.25.0
type CommunityGraphBuildOptions struct {
// ExcludeLazyEdges omits lazy (function-body) import edges when true.
// Default false (lazy edges included). Exclusion uses the same criterion
// as circular dependency detection (issue #460).
ExcludeLazyEdges bool
// EdgeWeightFunc assigns a weight to each dependency edge. When nil, every
// edge has weight 1.0. Reserved for future weighting by import type,
// frequency, or laziness.
EdgeWeightFunc func(edge *DependencyEdge) float64
}
CommunityGraphBuildOptions configures construction of a CommunityGraph.
func DefaultCommunityGraphBuildOptions ¶ added in v1.25.0
func DefaultCommunityGraphBuildOptions() *CommunityGraphBuildOptions
DefaultCommunityGraphBuildOptions returns the default build options.
type CommunityPartition ¶ added in v1.25.0
type CommunityPartition struct {
ID string
Modules []string
Packages []string
InternalEdges int
ExternalEdges int
ExternalDependencyRatio float64
IncomingCrossCommunityEdges int
OutgoingCrossCommunityEdges int
Size int
DominantPackage string
PackageCount int
PackageAlignment float64
DominantLayer string
LayerCount int
Layers []string
LayerAlignment float64
}
CommunityPartition describes one detected community.
type CommunityPartitionMetrics ¶ added in v1.25.0
type CommunityPartitionMetrics struct {
Communities []CommunityPartition
BridgeModules []BridgeModuleMetrics
TotalCommunities int
Modularity float64
}
CommunityPartitionMetrics holds community-level metrics derived from a Leiden partition over a module dependency graph.
func ComputeCommunityMetrics ¶ added in v1.25.0
func ComputeCommunityMetrics(graph *DependencyGraph, cg *CommunityGraph, leiden *LeidenResult, moduleToLayer map[string]string) *CommunityPartitionMetrics
ComputeCommunityMetrics derives per-community and bridge-module metrics from a Leiden partition. graph supplies package metadata; cg supplies directed edges. moduleToLayer maps modules to configured layers; pass nil to skip layer mismatch.
type ComplexityAnalyzer ¶
type ComplexityAnalyzer struct {
// contains filtered or unexported fields
}
ComplexityAnalyzer provides high-level complexity analysis functionality
func NewComplexityAnalyzer ¶
NewComplexityAnalyzer creates a new complexity analyzer with configuration
func NewComplexityAnalyzerWithDefaults ¶
func NewComplexityAnalyzerWithDefaults(output io.Writer) (*ComplexityAnalyzer, error)
NewComplexityAnalyzerWithDefaults creates a new analyzer with default configuration
func (*ComplexityAnalyzer) AnalyzeAndReport ¶
func (ca *ComplexityAnalyzer) AnalyzeAndReport(cfgs ControlFlowGraphs) error
AnalyzeAndReport performs complexity analysis and generates a formatted report.
func (*ComplexityAnalyzer) AnalyzeFunction ¶
func (ca *ComplexityAnalyzer) AnalyzeFunction(cfg *CFG) *ComplexityResult
AnalyzeFunction analyzes a single function and returns the result
func (*ComplexityAnalyzer) AnalyzeFunctions ¶
func (ca *ComplexityAnalyzer) AnalyzeFunctions(cfgs []*CFG) []*ComplexityResult
AnalyzeFunctions analyzes multiple functions and returns filtered results
func (*ComplexityAnalyzer) CheckComplexityLimits ¶
func (ca *ComplexityAnalyzer) CheckComplexityLimits(cfgs []*CFG) (bool, []*ComplexityResult)
CheckComplexityLimits checks if any functions exceed the configured maximum complexity Returns true if all functions are within limits, false otherwise
func (*ComplexityAnalyzer) GenerateReport ¶
func (ca *ComplexityAnalyzer) GenerateReport(cfgs ControlFlowGraphs) *reporter.ComplexityReport
GenerateReport creates a comprehensive report without outputting it.
func (*ComplexityAnalyzer) GetConfiguration ¶
func (ca *ComplexityAnalyzer) GetConfiguration() *config.Config
GetConfiguration returns the current configuration
func (*ComplexityAnalyzer) SetOutput ¶
func (ca *ComplexityAnalyzer) SetOutput(output io.Writer) error
SetOutput changes the output destination for reports
func (*ComplexityAnalyzer) UpdateConfiguration ¶
func (ca *ComplexityAnalyzer) UpdateConfiguration(cfg *config.Config) error
UpdateConfiguration updates the analyzer configuration
type ComplexityResult ¶
type ComplexityResult struct {
// McCabe cyclomatic complexity
Complexity int
// Raw CFG metrics
Edges int
Nodes int
ConnectedComponents int
// Function/method information
FunctionName string
StartLine int
StartCol int
EndLine int
// Nesting depth
NestingDepth int
CognitiveComplexity int
// Decision points breakdown
IfStatements int
LoopStatements int
ExceptionHandlers int
SwitchCases int
// SLOC is the source lines of code for this function.
SLOC int
// Risk assessment based on complexity thresholds
RiskLevel string // "low", "medium", "high"
}
ComplexityResult holds cyclomatic complexity metrics for a function or method
func CalculateComplexity ¶
func CalculateComplexity(cfg *CFG) *ComplexityResult
CalculateComplexity computes McCabe cyclomatic complexity for a CFG using default thresholds
func CalculateComplexityWithConfig ¶
func CalculateComplexityWithConfig(cfg *CFG, complexityConfig *config.ComplexityConfig) *ComplexityResult
CalculateComplexityWithConfig computes McCabe cyclomatic complexity using provided configuration
func CalculateFileComplexity ¶
func CalculateFileComplexity(cfgs []*CFG) []*ComplexityResult
CalculateFileComplexity calculates complexity for all execution scopes in a collection of CFGs.
func CalculateFileComplexityWithConfig ¶
func CalculateFileComplexityWithConfig(cfgs []*CFG, complexityConfig *config.ComplexityConfig) []*ComplexityResult
CalculateFileComplexityWithConfig calculates execution-scope complexity using the provided configuration.
func (*ComplexityResult) GetComplexity ¶
func (cr *ComplexityResult) GetComplexity() int
func (*ComplexityResult) GetDetailedMetrics ¶
func (cr *ComplexityResult) GetDetailedMetrics() map[string]int
func (*ComplexityResult) GetFunctionName ¶
func (cr *ComplexityResult) GetFunctionName() string
func (*ComplexityResult) GetRiskLevel ¶
func (cr *ComplexityResult) GetRiskLevel() string
func (*ComplexityResult) String ¶
func (cr *ComplexityResult) String() string
String returns a human-readable representation of the complexity result
type ConcreteDependencyDetector ¶ added in v1.16.0
type ConcreteDependencyDetector struct {
// contains filtered or unexported fields
}
ConcreteDependencyDetector detects concrete dependency anti-patterns
func NewConcreteDependencyDetector ¶ added in v1.16.0
func NewConcreteDependencyDetector() *ConcreteDependencyDetector
NewConcreteDependencyDetector creates a new concrete dependency detector
func (*ConcreteDependencyDetector) Analyze ¶ added in v1.16.0
func (d *ConcreteDependencyDetector) Analyze(ast *parser.Node, filePath string) []domain.DIAntipatternFinding
Analyze detects concrete dependencies in the given AST
type ConstructorAnalyzer ¶ added in v1.16.0
type ConstructorAnalyzer struct {
// contains filtered or unexported fields
}
ConstructorAnalyzer detects constructor over-injection anti-pattern
func NewConstructorAnalyzer ¶ added in v1.16.0
func NewConstructorAnalyzer(threshold int) *ConstructorAnalyzer
NewConstructorAnalyzer creates a new constructor analyzer
func (*ConstructorAnalyzer) Analyze ¶ added in v1.16.0
func (a *ConstructorAnalyzer) Analyze(ast *parser.Node, filePath string) []domain.DIAntipatternFinding
Analyze detects constructor over-injection in the given AST
type ControlFlowGraphs ¶ added in v1.30.0
type ControlFlowGraphs []ScopedCFG
ControlFlowGraphs preserves source traversal order and permits same-named scopes. A string-keyed map cannot represent those contracts without making an internal disambiguation key part of the public function name.
type CouplingMetricsCalculator ¶
type CouplingMetricsCalculator struct {
// contains filtered or unexported fields
}
CouplingMetricsCalculator calculates various coupling and quality metrics for modules
func NewCouplingMetricsCalculator ¶
func NewCouplingMetricsCalculator(graph *DependencyGraph, options *CouplingMetricsOptions) *CouplingMetricsCalculator
NewCouplingMetricsCalculator creates a new coupling metrics calculator
func (*CouplingMetricsCalculator) CalculateMetrics ¶
func (calc *CouplingMetricsCalculator) CalculateMetrics( ctx context.Context, topology *DependencyTopology, ) error
CalculateMetrics calculates all metrics using topology from the same graph.
type CouplingMetricsOptions ¶
type CouplingMetricsOptions struct {
IncludeAbstractness bool // Calculate abstractness metrics
ComplexityData map[string]int // Complexity data from complexity analysis
ClonesData map[string]float64 // Clone data from clone analysis
DeadCodeData map[string]int // Dead code data from dead code analysis
}
CouplingMetricsOptions configures metrics calculation
func DefaultCouplingMetricsOptions ¶
func DefaultCouplingMetricsOptions() *CouplingMetricsOptions
DefaultCouplingMetricsOptions returns default options
type CycleSeverity ¶
type CycleSeverity string
CycleSeverity represents the severity level of a circular dependency
const ( CycleSeverityLow CycleSeverity = "low" // Simple 2-module cycles CycleSeverityMedium CycleSeverity = "medium" // 3-5 module cycles CycleSeverityHigh CycleSeverity = "high" // 6-10 module cycles CycleSeverityCritical CycleSeverity = "critical" // 10+ module cycles or core infrastructure )
type DFABuilder ¶ added in v1.5.0
type DFABuilder = coredfa.DFABuilder
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
func NewDFABuilder ¶ added in v1.5.0
func NewDFABuilder() *DFABuilder
NewDFABuilder creates a DFA builder wired to Python reference extraction
type DFAFeatures ¶ added in v1.5.0
type DFAFeatures struct {
TotalDefs int // Total number of definitions
TotalUses int // Total number of uses
TotalPairs int // Total number of def-use pairs
UniqueVariables int // Number of unique variables
AvgChainLength float64 // Average uses per definition
MaxChainLength int // Maximum def-use chain length
CrossBlockPairs int // Def-use pairs spanning blocks
IntraBlockPairs int // Def-use pairs within same block
DefKindCounts map[DefUseKind]int // Distribution of definition kinds
UseKindCounts map[DefUseKind]int // Distribution of use kinds
}
DFAFeatures captures data flow characteristics for clone comparison. pyscn keeps its own feature shape: AvgChainLength is pairs per definition, which differs from core's per-chain average, and Type-4 similarity scores depend on it.
func ExtractDFAFeatures ¶ added in v1.5.0
func ExtractDFAFeatures(info *DFAInfo) *DFAFeatures
ExtractDFAFeatures extracts DFA features from DFAInfo
func NewDFAFeatures ¶ added in v1.5.0
func NewDFAFeatures() *DFAFeatures
NewDFAFeatures creates a new DFA features instance
type DFAInfo ¶ added in v1.5.0
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
type DIAntipatternDetector ¶ added in v1.16.0
type DIAntipatternDetector struct {
// contains filtered or unexported fields
}
DIAntipatternDetector coordinates all DI anti-pattern detectors
func NewDIAntipatternDetector ¶ added in v1.16.0
func NewDIAntipatternDetector(options *DIAntipatternOptions) *DIAntipatternDetector
NewDIAntipatternDetector creates a new DI anti-pattern detector
func (*DIAntipatternDetector) Analyze ¶ added in v1.16.0
func (d *DIAntipatternDetector) Analyze(ast *parser.Node, filePath string) ([]domain.DIAntipatternFinding, error)
Analyze runs all DI anti-pattern detectors on the given AST
type DIAntipatternOptions ¶ added in v1.16.0
type DIAntipatternOptions struct {
ConstructorParamThreshold int
MinSeverity domain.DIAntipatternSeverity
}
DIAntipatternOptions configures DI anti-pattern detection
func DefaultDIAntipatternOptions ¶ added in v1.16.0
func DefaultDIAntipatternOptions() *DIAntipatternOptions
DefaultDIAntipatternOptions returns default options
type DeadCodeDetector ¶
type DeadCodeDetector struct {
// contains filtered or unexported fields
}
DeadCodeDetector provides high-level dead code detection functionality
func NewDeadCodeDetector ¶
func NewDeadCodeDetector(cfg *CFG) *DeadCodeDetector
NewDeadCodeDetector creates a detector for a function CFG.
func NewDeadCodeDetectorWithFilePath ¶
func NewDeadCodeDetectorWithFilePath(cfg *CFG, filePath string) *DeadCodeDetector
NewDeadCodeDetectorWithFilePath creates a detector for a function CFG with file path context.
func (*DeadCodeDetector) Detect ¶
func (dcd *DeadCodeDetector) Detect() *DeadCodeResult
Detect performs dead code detection and returns structured findings
func (*DeadCodeDetector) GetDeadCodeRatio ¶
func (dcd *DeadCodeDetector) GetDeadCodeRatio() float64
GetDeadCodeRatio returns the ratio of dead blocks to total blocks
func (*DeadCodeDetector) HasDeadCode ¶
func (dcd *DeadCodeDetector) HasDeadCode() bool
HasDeadCode checks if the CFG contains any dead code
type DeadCodeFinding ¶
type DeadCodeFinding struct {
// Execution-scope information
FunctionName string `json:"function_name"`
ScopeKind domain.AnalysisScopeKind `json:"scope_kind"`
FilePath string `json:"file_path"`
// Location information
StartLine int `json:"start_line"`
EndLine int `json:"end_line"`
// Dead code details
BlockID string `json:"block_id"`
Code string `json:"code"`
Reason DeadCodeReason `json:"reason"`
Severity SeverityLevel `json:"severity"`
Description string `json:"description"`
// Context information
Context []string `json:"context,omitempty"`
}
DeadCodeFinding represents a single dead code detection result
func FilterFindingsBySeverity ¶
func FilterFindingsBySeverity(findings []*DeadCodeFinding, minSeverity SeverityLevel) []*DeadCodeFinding
FilterFindingsBySeverity filters findings by minimum severity level
type DeadCodeReason ¶
type DeadCodeReason string
DeadCodeReason represents the reason why code is considered dead
const ( // ReasonUnreachableAfterReturn indicates code after a return statement ReasonUnreachableAfterReturn DeadCodeReason = "unreachable_after_return" // ReasonUnreachableAfterBreak indicates code after a break statement ReasonUnreachableAfterBreak DeadCodeReason = "unreachable_after_break" // ReasonUnreachableAfterContinue indicates code after a continue statement ReasonUnreachableAfterContinue DeadCodeReason = "unreachable_after_continue" // ReasonUnreachableAfterRaise indicates code after a raise statement ReasonUnreachableAfterRaise DeadCodeReason = "unreachable_after_raise" // ReasonUnreachableBranch indicates an unreachable branch condition ReasonUnreachableBranch DeadCodeReason = "unreachable_branch" // ReasonUnreachableAfterInfiniteLoop indicates code after an infinite loop ReasonUnreachableAfterInfiniteLoop DeadCodeReason = "unreachable_after_infinite_loop" )
type DeadCodeResult ¶
type DeadCodeResult struct {
// Execution-scope information
FunctionName string `json:"function_name"`
ScopeKind domain.AnalysisScopeKind `json:"scope_kind"`
FilePath string `json:"file_path"`
// Analysis results
Findings []*DeadCodeFinding `json:"findings"`
TotalBlocks int `json:"total_blocks"`
DeadBlocks int `json:"dead_blocks"`
ReachableRatio float64 `json:"reachable_ratio"`
// Performance metrics
AnalysisTime time.Duration `json:"analysis_time"`
}
DeadCodeResult contains the results of dead code analysis for a single CFG
func DetectInFile ¶
func DetectInFile(cfgs ControlFlowGraphs, filePath string) []*DeadCodeResult
DetectInFile analyzes multiple CFGs from a file and returns combined findings
func DetectInFunction ¶
func DetectInFunction(cfg *CFG) *DeadCodeResult
DetectInFunction analyzes a single CFG and returns findings
func DetectInFunctionWithFilePath ¶
func DetectInFunctionWithFilePath(cfg *CFG, filePath string) *DeadCodeResult
DetectInFunctionWithFilePath analyzes a single CFG with file path context
func DetectInScopeWithFilePath ¶ added in v1.30.0
func DetectInScopeWithFilePath(scopedCFG ScopedCFG, filePath string) *DeadCodeResult
DetectInScopeWithFilePath analyzes one explicitly owned execution scope.
type DefUseChain ¶ added in v1.5.0
type DefUseChain = coredfa.DefUseChain
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
type DefUseKind ¶ added in v1.5.0
type DefUseKind = coredfa.DefUseKind
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
type DefUsePair ¶ added in v1.5.0
type DefUsePair = coredfa.DefUsePair
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
type DependencyChain ¶
type DependencyChain struct {
From string // Starting module
To string // Ending module
Path []string // Complete dependency path
Length int // Length of the chain
}
DependencyChain represents a chain of dependencies
type DependencyEdge ¶
type DependencyEdge struct {
From string // Source module name
To string // Target module name
EdgeType DependencyEdgeType // Type of dependency
ImportInfo *ImportInfo // Details about the import
IsLazy bool // True if every import forming this edge is lazy (function/method-body)
}
DependencyEdge represents a dependency relationship between modules
type DependencyEdgeType ¶
type DependencyEdgeType string
DependencyEdgeType represents the type of dependency relationship
const ( DependencyEdgeImport DependencyEdgeType = "import" // Direct import (import module) DependencyEdgeFromImport DependencyEdgeType = "from_import" // From import (from module import name) DependencyEdgeRelative DependencyEdgeType = "relative" // Relative import DependencyEdgeImplicit DependencyEdgeType = "implicit" // Implicit dependency )
type DependencyGraph ¶
type DependencyGraph struct {
// Graph structure
Nodes map[string]*ModuleNode // Module name -> ModuleNode
Edges []*DependencyEdge // All dependency relationships
// Graph metadata
TotalModules int // Total number of modules
TotalEdges int // Total number of dependencies
// ResolvedImports and UnresolvedImports count internal import statements,
// excluding standard-library and third-party imports that are not part of
// the analyzed graph.
ResolvedImports int
UnresolvedImports int
RootModules []string // Modules with no dependencies
LeafModules []string // Modules with no dependents
ProjectRoot string // Project root directory
// Analysis results
CyclicGroups [][]string // Strongly connected components (cycles)
ModuleMetrics map[string]*ModuleMetrics // Module-level metrics
SystemMetrics *SystemMetrics // System-wide metrics
// contains filtered or unexported fields
}
DependencyGraph represents the complete module dependency graph
func NewDependencyGraph ¶
func NewDependencyGraph(projectRoot string) *DependencyGraph
NewDependencyGraph creates a new dependency graph
func (*DependencyGraph) AddDependency ¶
func (g *DependencyGraph) AddDependency(from, to string, edgeType DependencyEdgeType, importInfo *ImportInfo)
AddDependency adds a dependency edge between two modules
func (*DependencyGraph) AddModule ¶
func (g *DependencyGraph) AddModule(moduleName, filePath string) *ModuleNode
AddModule adds a module to the graph
func (*DependencyGraph) Clone ¶
func (g *DependencyGraph) Clone() *DependencyGraph
Clone creates a deep copy of the dependency graph
func (*DependencyGraph) GetDependencies ¶
func (g *DependencyGraph) GetDependencies(moduleName string) []string
GetDependencies returns all modules that the given module depends on
func (*DependencyGraph) GetDependencyChain ¶
func (g *DependencyGraph) GetDependencyChain(from, to string) []string
GetDependencyChain finds the dependency path between two modules
func (*DependencyGraph) GetDependents ¶
func (g *DependencyGraph) GetDependents(moduleName string) []string
GetDependents returns all modules that depend on the given module
func (*DependencyGraph) GetLeafModules ¶
func (g *DependencyGraph) GetLeafModules() []string
GetLeafModules returns modules with no dependents (utilities)
func (*DependencyGraph) GetModule ¶
func (g *DependencyGraph) GetModule(moduleName string) *ModuleNode
GetModule retrieves a module node by name
func (*DependencyGraph) GetModuleNames ¶
func (g *DependencyGraph) GetModuleNames() []string
GetModuleNames returns all module names in the graph
func (*DependencyGraph) GetModulesInCycles ¶
func (g *DependencyGraph) GetModulesInCycles() []string
GetModulesInCycles returns all modules that are part of dependency cycles
func (*DependencyGraph) GetPackages ¶
func (g *DependencyGraph) GetPackages() []string
GetPackages returns all unique package names
func (*DependencyGraph) GetRootModules ¶
func (g *DependencyGraph) GetRootModules() []string
GetRootModules returns modules with no dependencies (entry points)
func (*DependencyGraph) HasCycle ¶
func (g *DependencyGraph) HasCycle() bool
HasCycle checks if the graph contains any cycles
func (*DependencyGraph) HasNode ¶ added in v1.27.0
func (g *DependencyGraph) HasNode(moduleName string) bool
HasNode reports whether moduleName exists in the graph.
func (*DependencyGraph) NodeCount ¶ added in v1.27.0
func (g *DependencyGraph) NodeCount() int
NodeCount returns the number of modules in the graph.
func (*DependencyGraph) NodeIDs ¶ added in v1.27.0
func (g *DependencyGraph) NodeIDs() []string
NodeIDs returns all module names in deterministic order for core graph analyses.
func (*DependencyGraph) Predecessors ¶ added in v1.27.0
func (g *DependencyGraph) Predecessors(moduleName string) []string
Predecessors returns the modules that directly import moduleName.
func (*DependencyGraph) String ¶
func (g *DependencyGraph) String() string
String returns a string representation of the graph
func (*DependencyGraph) Successors ¶ added in v1.27.0
func (g *DependencyGraph) Successors(moduleName string) []string
Successors returns the modules directly imported by moduleName.
func (*DependencyGraph) Validate ¶
func (g *DependencyGraph) Validate() error
Validate checks the graph for consistency
type DependencyTopology ¶ added in v1.29.1
type DependencyTopology struct {
// contains filtered or unexported fields
}
DependencyTopology is the canonical load-time structural analysis of one dependency graph. MaxDepth and LongestChains share the same SCC condensation. A result belongs to the exact graph instance passed to AnalyzeDependencyTopology. Structural mutations through AddModule or AddDependency invalidate it; directly mutating DependencyGraph storage is unsupported.
func AnalyzeDependencyTopology ¶ added in v1.29.1
func AnalyzeDependencyTopology( ctx context.Context, graph *DependencyGraph, chainLimit int, ) (*DependencyTopology, error)
AnalyzeDependencyTopology condenses the graph's load-time dependencies with core/graph's chain finder and reads maximum depth and the chainLimit globally ranked chains off that one condensation. Lazy-only imports remain available to other graph analyses. Cancelling ctx aborts the search.
func (*DependencyTopology) LongestChains ¶ added in v1.29.1
func (topology *DependencyTopology) LongestChains() []DependencyChain
LongestChains returns a defensive copy of the ranked dependency chains.
func (*DependencyTopology) MaxDepth ¶ added in v1.29.1
func (topology *DependencyTopology) MaxDepth() int
MaxDepth returns the number of edges along the longest dependency chain, which is the same chain LongestChains ranks first.
type Edge ¶
CFG data structures and traversal are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific construction stays local.
type EdgeType ¶
CFG data structures and traversal are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific construction stays local.
type FileComplexityAnalyzer ¶
type FileComplexityAnalyzer struct {
// contains filtered or unexported fields
}
FileComplexityAnalyzer provides high-level file analysis capabilities
func NewFileComplexityAnalyzer ¶
func NewFileComplexityAnalyzer(cfg *config.Config, output io.Writer) (*FileComplexityAnalyzer, error)
NewFileComplexityAnalyzer creates a new file analyzer with configuration
func (*FileComplexityAnalyzer) AnalyzeFile ¶
func (fca *FileComplexityAnalyzer) AnalyzeFile(filename string) error
AnalyzeFile analyzes a single Python file and outputs complexity results
func (*FileComplexityAnalyzer) AnalyzeFiles ¶
func (fca *FileComplexityAnalyzer) AnalyzeFiles(filenames []string) error
AnalyzeFiles analyzes multiple Python files and outputs combined complexity results
type GroupingMode ¶
type GroupingMode string
GroupingMode represents the strategy for grouping clones. The grouping algorithms themselves live in core/clone; this type preserves pyscn's user-facing mode names (notably "star" for core's "star_medoid").
const ( GroupingModeConnected GroupingMode = "connected" // Current default (high recall) GroupingModeStar GroupingMode = "star" // Star/medoid (balanced) GroupingModeCompleteLinkage GroupingMode = "complete_linkage" // Complete linkage (high precision) GroupingModeKCore GroupingMode = "k_core" // k-core constrained (scalable) GroupingModeCentroid GroupingMode = "centroid" // Centroid based (avoids transitivity issues) )
type HiddenDependencyDetector ¶ added in v1.16.0
type HiddenDependencyDetector struct {
// contains filtered or unexported fields
}
HiddenDependencyDetector detects hidden dependency anti-patterns
func NewHiddenDependencyDetector ¶ added in v1.16.0
func NewHiddenDependencyDetector() *HiddenDependencyDetector
NewHiddenDependencyDetector creates a new hidden dependency detector
func (*HiddenDependencyDetector) Analyze ¶ added in v1.16.0
func (d *HiddenDependencyDetector) Analyze(ast *parser.Node, filePath string) []domain.DIAntipatternFinding
Analyze detects hidden dependencies in the given AST
type ImportInfo ¶
type ImportInfo struct {
Statement string // Original import statement
ImportedNames []string // Names imported (for from imports)
Alias string // Alias used (if any)
IsRelative bool // True for relative imports
Level int // Level for relative imports (number of dots)
Line int // Line number where import occurs
IsTypeChecking bool // True if import is inside a TYPE_CHECKING block
IsLazy bool // True if import is inside a function/method body (not executed at module load)
}
ImportInfo contains details about an import statement
type LCOMAnalyzer ¶ added in v1.11.0
type LCOMAnalyzer struct {
// contains filtered or unexported fields
}
LCOMAnalyzer analyzes class cohesion in Python code
func NewLCOMAnalyzer ¶ added in v1.11.0
func NewLCOMAnalyzer(options *LCOMOptions) *LCOMAnalyzer
NewLCOMAnalyzer creates a new LCOM analyzer
func (*LCOMAnalyzer) AnalyzeClasses ¶ added in v1.11.0
func (a *LCOMAnalyzer) AnalyzeClasses(ast *parser.Node, filePath string) ([]*LCOMResult, error)
AnalyzeClasses analyzes LCOM4 for all classes in the given AST
type LCOMOptions ¶ added in v1.11.0
type LCOMOptions struct {
LowThreshold int // Default: 2 (LCOM4 <= 2 is low risk)
MediumThreshold int // Default: 5 (LCOM4 3-5 is medium risk)
}
LCOMOptions configures LCOM analysis behavior
func DefaultLCOMOptions ¶ added in v1.11.0
func DefaultLCOMOptions() *LCOMOptions
DefaultLCOMOptions returns default LCOM analysis options
type LCOMResult ¶ added in v1.11.0
type LCOMResult struct {
// Core LCOM4 metric - number of connected components
LCOM4 int
// Class information
ClassName string
FilePath string
StartLine int
EndLine int
// Method statistics
TotalMethods int // All methods found in class
ExcludedMethods int // @staticmethod/@classmethod/@abstractmethod and constructors excluded
// Instance variable count
InstanceVariables int // Distinct self.xxx variables
// Connected component details
MethodGroups [][]string // Method names grouped by connected component
// Risk assessment
RiskLevel string // "low", "medium", "high"
}
LCOMResult holds LCOM4 (Lack of Cohesion of Methods) metrics for a class
func CalculateLCOM ¶ added in v1.11.0
func CalculateLCOM(ast *parser.Node, filePath string) ([]*LCOMResult, error)
CalculateLCOM is a convenience function that creates an analyzer with defaults and runs it
func CalculateLCOMWithConfig ¶ added in v1.11.0
func CalculateLCOMWithConfig(ast *parser.Node, filePath string, options *LCOMOptions) ([]*LCOMResult, error)
CalculateLCOMWithConfig creates an analyzer with custom options and runs it
type LayerMismatchMetrics ¶ added in v1.25.0
type LayerMismatchMetrics struct {
LayerAlignmentScore float64
CrossLayerCommunities []string
LayerBridgeModules []string
}
LayerMismatchMetrics summarizes how well detected communities align with configured architecture layers.
func ComputeLayerMismatchMetrics ¶ added in v1.25.0
func ComputeLayerMismatchMetrics(partitions []CommunityPartition, bridges []BridgeModuleMetrics) *LayerMismatchMetrics
ComputeLayerMismatchMetrics derives system-level layer alignment metrics from per-community partitions that already include layer mismatch fields.
type LeidenOptions ¶ added in v1.25.0
type LeidenOptions struct {
// Resolution scales the null-model term in the modularity quality
// function (default 1.0). Higher values favour smaller communities.
Resolution float64
// MinCommunitySize merges communities smaller than this threshold into
// a neighbouring community after detection (default 1, no merging).
MinCommunitySize int
// MaxIterations bounds local-moving sweeps per phase (default 64).
MaxIterations int
// MaxPasses bounds Leiden passes before stopping (default 16).
MaxPasses int
}
LeidenOptions configures the Leiden community detection algorithm.
func DefaultLeidenOptions ¶ added in v1.25.0
func DefaultLeidenOptions() *LeidenOptions
DefaultLeidenOptions returns the default Leiden parameters.
type LeidenResult ¶ added in v1.25.0
type LeidenResult struct {
// Membership maps node index to community id in [0, NumCommunities).
Membership []int
// Modularity is the final modularity Q of the partition.
Modularity float64
// NumCommunities is the number of distinct communities.
NumCommunities int
}
LeidenResult holds the output of Leiden community detection.
func DetectCommunitiesLeiden ¶ added in v1.25.0
func DetectCommunitiesLeiden(cg *CommunityGraph, opts *LeidenOptions) *LeidenResult
DetectCommunitiesLeiden runs the Traag-Waltman-van Eck Leiden algorithm on a CommunityGraph. The implementation is pure Leiden (singleton start, no Louvain-style warm-up pass) with deterministic node iteration in sorted index order and lowest-community-id tie-breaking on equal modularity gain.
type ModuleAnalysisOptions ¶
type ModuleAnalysisOptions struct {
ProjectRoot string // Project root directory
PythonPath []string // Additional Python path entries
ModuleRoots []string // Explicit captured module roots; nil discovers from disk
ExcludePatterns []string // Module patterns to exclude; nil uses defaults, empty disables excludes
IncludePatterns []string // Module patterns to include; nil uses defaults, empty includes all files
IncludeStdLib *bool // Include standard library dependencies
IncludeThirdParty *bool // Include third-party dependencies
FollowRelative *bool // Follow relative imports
}
ModuleAnalysisOptions configures module analysis behavior
func DefaultModuleAnalysisOptions ¶
func DefaultModuleAnalysisOptions() *ModuleAnalysisOptions
DefaultModuleAnalysisOptions returns default analysis options
type ModuleAnalyzer ¶
type ModuleAnalyzer struct {
// contains filtered or unexported fields
}
ModuleAnalyzer analyzes module-level dependencies and builds dependency graphs
func NewModuleAnalyzer ¶
func NewModuleAnalyzer(options *ModuleAnalysisOptions) (*ModuleAnalyzer, error)
NewModuleAnalyzer creates a new module analyzer
func (*ModuleAnalyzer) AnalyzeFiles ¶
func (ma *ModuleAnalyzer) AnalyzeFiles(filePaths []string) (*DependencyGraph, error)
AnalyzeFiles analyzes specific Python files and builds a dependency graph
func (*ModuleAnalyzer) AnalyzeParsedModules ¶ added in v1.30.0
func (ma *ModuleAnalyzer) AnalyzeParsedModules(ctx context.Context, parsedModules []ParsedModule) (*DependencyGraph, error)
AnalyzeParsedModules builds a dependency graph from previously parsed source.
func (*ModuleAnalyzer) AnalyzeProject ¶
func (ma *ModuleAnalyzer) AnalyzeProject() (*DependencyGraph, error)
AnalyzeProject analyzes all Python modules in the project and builds a dependency graph
type ModuleMetrics ¶
type ModuleMetrics struct {
// Coupling metrics
AfferentCoupling int // Ca - Number of modules that depend on this module
EfferentCoupling int // Ce - Number of modules this module depends on
Instability float64 // I = Ce / (Ca + Ce) - Measure of instability
Abstractness float64 // A - Measure of abstractness (0-1)
Distance float64 // D - Distance from main sequence
// Size metrics
LinesOfCode int // Total lines of code
ClassCount int // Number of classes
AbstractClassCount int // Number of abstract classes
PublicInterface int // Number of public functions/classes
// Quality metrics
CyclomaticComplexity int // Average complexity of functions
}
ModuleMetrics contains metrics for a single module
type ModuleNode ¶
type ModuleNode struct {
// Module identification
Name string // Module name (e.g., "mypackage.submodule")
FilePath string // Absolute path to the Python file
RelativePath string // Relative path from project root
Package string // Package name (e.g., "mypackage")
IsPackage bool // True if this represents a package (__init__.py)
// Dependencies
Imports []string // Direct imports from this module
ImportedBy []string // Modules that import this module
Dependencies map[string]bool // Set of modules this module depends on
Dependents map[string]bool // Set of modules that depend on this module
// LazyDependencies is the subset of Dependencies that is reachable ONLY via
// lazy (function/method-body) imports — i.e. no module-load-time import to
// the target exists. These edges are real runtime dependencies but cannot
// form a load-time circular import, so circular-dependency detection skips
// them. As soon as a module-level import to the same target is seen, the
// entry is removed. See issue #460.
LazyDependencies map[string]bool
// Metrics
InDegree int // Number of incoming dependencies
OutDegree int // Number of outgoing dependencies
// Module information
LineCount int // Total lines in the module
FunctionCount int // Number of functions defined
ClassCount int // Number of classes defined
AbstractClassCount int // Number of abstract classes defined
PublicNames []string // Public names exported by this module
}
ModuleNode represents a module in the dependency graph
type NestingDepthResult ¶ added in v1.0.2
type NestingDepthResult struct {
// Maximum nesting depth found in the function
MaxDepth int
// Historical function/method metadata fields.
FunctionName string
StartLine int
EndLine int
// Location of deepest nesting (line number)
DeepestNestingLine int
}
NestingDepthResult holds maximum nesting depth and metadata for an execution scope.
func CalculateMaxNestingDepth ¶ added in v1.0.2
func CalculateMaxNestingDepth(scopeNode *parser.Node) *NestingDepthResult
CalculateMaxNestingDepth traverses one owned execution scope and tracks depth through its nested control structures.
type PackageMismatchMetrics ¶ added in v1.25.0
type PackageMismatchMetrics struct {
PackageAlignmentScore float64
SplitPackages []string
MixedCommunities []string
}
PackageMismatchMetrics summarizes how well detected communities align with declared package boundaries.
func ComputePackageMismatchMetrics ¶ added in v1.25.0
func ComputePackageMismatchMetrics(partitions []CommunityPartition) *PackageMismatchMetrics
ComputePackageMismatchMetrics derives system-level package alignment metrics from per-community partitions that already include package mismatch fields.
type ParsedModule ¶ added in v1.30.0
type ParsedModule struct {
// contains filtered or unexported fields
}
ParsedModule is a read-only view of source and syntax captured for module analysis. It borrows the source and AST for the duration of analysis; callers retain ownership and must not mutate either after construction.
func NewParsedModule ¶ added in v1.30.0
NewParsedModule creates a validated module-analysis input.
type PythonCostModel ¶
type PythonCostModel struct {
// Base costs for different operations
BaseInsertCost float64
BaseDeleteCost float64
BaseRenameCost float64
// Whether to ignore differences in literal values
IgnoreLiterals bool
// Whether to ignore differences in identifier names
IgnoreIdentifiers bool
// Whether to reduce weight for boilerplate nodes (type annotations, decorators, Field() calls)
ReduceBoilerplateWeight bool
// Multiplier for boilerplate nodes (default: 0.1)
BoilerplateMultiplier float64
}
PythonCostModel implements a Python-aware cost model with different costs for different node types
func NewPythonCostModel ¶
func NewPythonCostModel() *PythonCostModel
NewPythonCostModel creates a new Python-aware cost model with default settings
func NewPythonCostModelWithBoilerplateConfig ¶ added in v1.9.2
func NewPythonCostModelWithBoilerplateConfig(ignoreLiterals, ignoreIdentifiers, reduceBoilerplate bool, boilerplateMultiplier float64) *PythonCostModel
NewPythonCostModelWithBoilerplateConfig creates a Python cost model with full configuration
func NewPythonCostModelWithConfig ¶
func NewPythonCostModelWithConfig(ignoreLiterals, ignoreIdentifiers bool) *PythonCostModel
NewPythonCostModelWithConfig creates a Python cost model with custom configuration
func (*PythonCostModel) Delete ¶
func (c *PythonCostModel) Delete(node *coreapted.TreeNode) float64
Delete returns the cost of deleting a node
type RawMetricsResult ¶ added in v1.15.0
type RawMetricsResult struct {
FilePath string
SLOC int
LLOC int
CommentLines int
DocstringLines int
BlankLines int
TotalLines int
CommentRatio float64
// contains filtered or unexported fields
}
RawMetricsResult contains file-level raw code metrics.
func CalculateRawMetrics ¶ added in v1.15.0
func CalculateRawMetrics(content []byte, filePath string) *RawMetricsResult
CalculateRawMetrics calculates raw code metrics without requiring AST parsing.
func (*RawMetricsResult) Clone ¶ added in v1.30.0
func (r *RawMetricsResult) Clone() *RawMetricsResult
Clone returns an independent raw-metrics result.
func (*RawMetricsResult) FunctionSLOC ¶ added in v1.29.1
func (r *RawMetricsResult) FunctionSLOC(startLine, endLine int) int
FunctionSLOC returns the source lines of code within the 1-indexed, inclusive line range [startLine, endLine], using the classification computed for the whole file. Comments, blank lines and docstrings are excluded, exactly as in the file-level SLOC metric.
The range is measured verbatim, so lines belonging to definitions nested inside it (inner functions, classes) count toward the enclosing range as well: the value reflects the physical length of the definition.
type ReExportEntry ¶ added in v1.9.3
type ReExportEntry struct {
Name string // The exported name (e.g., "SomeClass")
SourceModule string // The actual source module (e.g., "pkg_a.module_x")
SourceName string // The name in the source module (may differ if aliased)
}
ReExportEntry represents a single re-exported name from an __init__.py
type ReExportMap ¶ added in v1.9.3
type ReExportMap struct {
PackageName string // The package name (e.g., "pkg_a")
Exports map[string]*ReExportEntry // name -> source info
AllDeclared []string // Names in __all__ if declared
HasAllDecl bool // True if __all__ is explicitly declared
}
ReExportMap holds all exports from a package's __init__.py
type ReExportResolver ¶ added in v1.9.3
type ReExportResolver struct {
// contains filtered or unexported fields
}
ReExportResolver resolves re-exports in __init__.py files
func NewReExportResolver ¶ added in v1.9.3
func NewReExportResolver(projectRoot string) *ReExportResolver
NewReExportResolver creates a new resolver
func NewReExportResolverWithRoots ¶ added in v1.25.0
func NewReExportResolverWithRoots(projectRoot string, roots []string) *ReExportResolver
NewReExportResolverWithRoots creates a resolver using one or more import roots.
func (*ReExportResolver) GetReExportMap ¶ added in v1.9.3
func (r *ReExportResolver) GetReExportMap(packageName string) (*ReExportMap, error)
GetReExportMap returns the re-export map for a package (cached)
func (*ReExportResolver) ResolveReExport ¶ added in v1.9.3
func (r *ReExportResolver) ResolveReExport(packageName, importedName string) (string, bool)
ResolveReExport resolves an imported name to its actual source module. Returns (sourceModule, found).
Parse errors are treated as "no re-exports found" - if the __init__.py cannot be parsed, we fall back to using the package as the dependency target. This is intentional: syntax errors in __init__.py shouldn't break dependency analysis, and the error is cached to avoid repeated parse attempts.
func (*ReExportResolver) UseParsedPackages ¶ added in v1.30.0
func (r *ReExportResolver) UseParsedPackages(packages map[string]*parser.Node)
UseParsedPackages replaces filesystem discovery with re-export maps derived from syntax owned by a project snapshot.
type ReachabilityAnalyzer ¶
type ReachabilityAnalyzer struct {
// contains filtered or unexported fields
}
ReachabilityAnalyzer performs reachability analysis on CFGs.
func NewReachabilityAnalyzer ¶
func NewReachabilityAnalyzer(cfg *CFG) *ReachabilityAnalyzer
NewReachabilityAnalyzer creates a new reachability analyzer for the given CFG.
func (*ReachabilityAnalyzer) AnalyzeReachability ¶
func (ra *ReachabilityAnalyzer) AnalyzeReachability() *ReachabilityResult
AnalyzeReachability performs reachability analysis starting from the entry block.
func (*ReachabilityAnalyzer) AnalyzeReachabilityFrom ¶
func (ra *ReachabilityAnalyzer) AnalyzeReachabilityFrom(startBlock *BasicBlock) *ReachabilityResult
AnalyzeReachabilityFrom retains pyscn's explicit-start structural traversal.
type ReachabilityResult ¶
type ReachabilityResult struct {
// ReachableBlocks contains blocks reachable from the CFG entry.
ReachableBlocks map[string]*BasicBlock
// UnreachableBlocks contains registered blocks not reachable from the CFG entry.
UnreachableBlocks map[string]*BasicBlock
// TotalBlocks is the total number of registered CFG blocks.
TotalBlocks int
// ReachableCount is the number of reachable registered blocks.
ReachableCount int
// UnreachableCount is the number of unreachable registered blocks.
UnreachableCount int
// AnalysisTime is the duration of the reachability analysis.
AnalysisTime time.Duration
}
ReachabilityResult preserves pyscn's enriched projection of core reachability.
func (*ReachabilityResult) GetReachabilityRatio ¶
func (result *ReachabilityResult) GetReachabilityRatio() float64
GetReachabilityRatio returns the ratio of reachable blocks to total blocks.
func (*ReachabilityResult) GetUnreachableBlocksWithStatements ¶
func (result *ReachabilityResult) GetUnreachableBlocksWithStatements() map[string]*BasicBlock
GetUnreachableBlocksWithStatements returns unreachable non-empty blocks.
func (*ReachabilityResult) HasUnreachableCode ¶
func (result *ReachabilityResult) HasUnreachableCode() bool
HasUnreachableCode reports whether an unreachable block contains statements.
type ScopedCFG ¶ added in v1.30.0
ScopedCFG binds a control-flow graph to the execution scope that owns it.
type SemanticSimilarityAnalyzer ¶ added in v1.5.0
type SemanticSimilarityAnalyzer struct {
// contains filtered or unexported fields
}
SemanticSimilarityAnalyzer computes semantic similarity using CFG (Control Flow Graph) and optionally DFA (Data Flow Analysis) feature comparison. This is used for Type-4 clone detection (functionally similar code with different syntax).
func NewSemanticSimilarityAnalyzer ¶ added in v1.5.0
func NewSemanticSimilarityAnalyzer() *SemanticSimilarityAnalyzer
NewSemanticSimilarityAnalyzer creates a new semantic similarity analyzer
func NewSemanticSimilarityAnalyzerWithDFA ¶ added in v1.5.0
func NewSemanticSimilarityAnalyzerWithDFA() *SemanticSimilarityAnalyzer
NewSemanticSimilarityAnalyzerWithDFA creates a new analyzer with DFA enabled
func (*SemanticSimilarityAnalyzer) BuildCFG ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) BuildCFG(node *parser.Node) (*CFG, error)
BuildCFG builds a CFG from a parser.Node (exposed for testing)
func (*SemanticSimilarityAnalyzer) BuildDFA ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) BuildDFA(cfg *CFG) (*DFAInfo, error)
BuildDFA builds DFA info from a CFG (exposed for testing)
func (*SemanticSimilarityAnalyzer) ComputeSimilarity ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) ComputeSimilarity(f1, f2 *CodeFragment) float64
ComputeSimilarity computes the semantic similarity between two code fragments by comparing their CFG structures and optionally DFA features.
func (*SemanticSimilarityAnalyzer) ExtractDFAFeaturesFromInfo ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) ExtractDFAFeaturesFromInfo(info *DFAInfo) *DFAFeatures
ExtractDFAFeatures extracts DFA features from DFA info (exposed for testing)
func (*SemanticSimilarityAnalyzer) ExtractFeatures ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) ExtractFeatures(cfg *CFG) *CFGFeatures
ExtractFeatures extracts CFG features (exposed for testing)
func (*SemanticSimilarityAnalyzer) GetName ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) GetName() string
GetName returns the name of this analyzer
func (*SemanticSimilarityAnalyzer) IsDFAEnabled ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) IsDFAEnabled() bool
IsDFAEnabled returns whether DFA analysis is enabled
func (*SemanticSimilarityAnalyzer) SetEnableDFA ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) SetEnableDFA(enable bool)
SetEnableDFA enables or disables DFA analysis
func (*SemanticSimilarityAnalyzer) SetMinCyclomaticComplexity ¶ added in v1.21.1
func (s *SemanticSimilarityAnalyzer) SetMinCyclomaticComplexity(n int)
SetMinCyclomaticComplexity sets the minimum CFG cyclomatic complexity V(G) required for Type-4 classification. A value <= 0 disables the gate.
func (*SemanticSimilarityAnalyzer) SetWeights ¶ added in v1.5.0
func (s *SemanticSimilarityAnalyzer) SetWeights(cfgWeight, dfaWeight float64)
SetWeights sets the CFG and DFA feature weights
type ServiceLocatorDetector ¶ added in v1.16.0
type ServiceLocatorDetector struct {
// contains filtered or unexported fields
}
ServiceLocatorDetector detects service locator anti-pattern
func NewServiceLocatorDetector ¶ added in v1.16.0
func NewServiceLocatorDetector() *ServiceLocatorDetector
NewServiceLocatorDetector creates a new service locator detector
func (*ServiceLocatorDetector) Analyze ¶ added in v1.16.0
func (d *ServiceLocatorDetector) Analyze(ast *parser.Node, filePath string) []domain.DIAntipatternFinding
Analyze detects service locator pattern in the given AST
type SeverityLevel ¶
type SeverityLevel string
SeverityLevel represents the severity of a dead code finding
const ( // SeverityLevelCritical indicates code that is definitely unreachable SeverityLevelCritical SeverityLevel = "critical" // SeverityLevelWarning indicates code that is likely unreachable SeverityLevelWarning SeverityLevel = "warning" // SeverityLevelInfo indicates potential optimization opportunities SeverityLevelInfo SeverityLevel = "info" )
type SimilarityAnalyzer ¶ added in v1.5.0
type SimilarityAnalyzer interface {
// ComputeSimilarity returns a similarity score between 0.0 and 1.0
ComputeSimilarity(fragment1, fragment2 *CodeFragment) float64
// GetName returns the name of this analyzer
GetName() string
}
SimilarityAnalyzer defines the interface for computing similarity between code fragments. Each clone type should have its own analyzer implementation.
func NewSyntacticSimilarityAnalyzer ¶ added in v1.5.0
func NewSyntacticSimilarityAnalyzer() SimilarityAnalyzer
NewSyntacticSimilarityAnalyzer returns the Type-2 syntactic similarity analyzer backed by core/clone (normalized AST hash comparison) with Python pattern and literal-like label configuration.
func NewTextualSimilarityAnalyzer ¶ added in v1.5.0
func NewTextualSimilarityAnalyzer() SimilarityAnalyzer
NewTextualSimilarityAnalyzer returns the Type-1 textual similarity analyzer backed by core/clone with Python comment stripping.
type StructuralSimilarityAnalyzer ¶ added in v1.5.0
type StructuralSimilarityAnalyzer struct {
// contains filtered or unexported fields
}
StructuralSimilarityAnalyzer computes structural similarity using APTED tree edit distance. This is used for Type-3 clone detection (near-miss clones with modifications).
func NewStructuralSimilarityAnalyzer ¶ added in v1.5.0
func NewStructuralSimilarityAnalyzer() *StructuralSimilarityAnalyzer
NewStructuralSimilarityAnalyzer creates a new structural similarity analyzer using the standard Python cost model (no normalization).
func NewStructuralSimilarityAnalyzerWithCostModel ¶ added in v1.5.0
func NewStructuralSimilarityAnalyzerWithCostModel(costModel coreapted.CostModel) *StructuralSimilarityAnalyzer
NewStructuralSimilarityAnalyzerWithCostModel creates a structural similarity analyzer with a custom cost model.
func (*StructuralSimilarityAnalyzer) ComputeDistance ¶ added in v1.5.0
func (s *StructuralSimilarityAnalyzer) ComputeDistance(f1, f2 *CodeFragment) float64
ComputeDistance computes the edit distance between two code fragments. This is useful for additional metrics beyond similarity.
func (*StructuralSimilarityAnalyzer) ComputeSimilarity ¶ added in v1.5.0
func (s *StructuralSimilarityAnalyzer) ComputeSimilarity(f1, f2 *CodeFragment) float64
ComputeSimilarity computes the structural similarity between two code fragments using APTED tree edit distance.
func (*StructuralSimilarityAnalyzer) GetAnalyzer ¶ added in v1.5.0
func (s *StructuralSimilarityAnalyzer) GetAnalyzer() *coreapted.APTEDAnalyzer
GetAnalyzer returns the underlying APTED analyzer (for advanced usage)
func (*StructuralSimilarityAnalyzer) GetName ¶ added in v1.5.0
func (s *StructuralSimilarityAnalyzer) GetName() string
GetName returns the name of this analyzer
type SystemMetrics ¶
type SystemMetrics struct {
// Overall structure
TotalModules int // Total number of modules
TotalDependencies int // Total number of dependencies
PackageCount int // Number of packages
// Dependency metrics
AverageFanIn float64 // Average number of incoming dependencies
AverageFanOut float64 // Average number of outgoing dependencies
DependencyRatio float64 // Total dependencies / Total modules
// Coupling and cohesion
AverageInstability float64 // System average instability
AverageAbstractness float64 // System average abstractness
MainSequenceDeviation float64 // Average distance from main sequence
// Modularity
ModularityIndex float64 // Measure of system decomposition quality
ComponentRatio float64 // Ratio of strongly connected components
// Quality indicators
CyclicDependencies int // Number of modules in cycles
MaxDependencyDepth int // Maximum dependency chain length
SystemComplexity float64 // Overall system complexity score
// Refactoring
RefactoringPriority []string // Modules needing refactoring (highest priority first)
StableModules []string // Low instability modules
InstableModules []string // High instability modules
ZoneOfPain []string // Stable concrete modules far from the main sequence
ZoneOfUselessness []string // Unstable abstract modules far from the main sequence
MainSequence []string // Modules close to A + I = 1
}
SystemMetrics contains system-wide quality metrics
type TreeConverter ¶
type TreeConverter struct {
// contains filtered or unexported fields
}
TreeConverter converts parser AST nodes to APTED tree nodes
func NewTreeConverter ¶
func NewTreeConverter() *TreeConverter
NewTreeConverter creates a new tree converter with default settings (no docstring skipping)
func NewTreeConverterWithConfig ¶ added in v1.5.2
func NewTreeConverterWithConfig(skipDocstrings bool) *TreeConverter
NewTreeConverterWithConfig creates a tree converter with configuration
func (*TreeConverter) ConvertAST ¶
func (tc *TreeConverter) ConvertAST(astNode *parser.Node) *coreapted.TreeNode
ConvertAST converts a parser AST node to an APTED tree
type VarReference ¶ added in v1.5.0
type VarReference = coredfa.VarReference
Def-use chain data structures and the DFA builder are owned by polyscan core. Aliases keep pyscn's internal API stable while Python-specific reference extraction stays local (see dfa_builder.go).
type WeightedNeighbor ¶ added in v1.25.0
WeightedNeighbor is a neighbor in the undirected adjacency list.
Source Files
¶
- apted_cost.go
- apted_tree.go
- cbo.go
- cfg.go
- cfg_builder.go
- circular_detector.go
- clone_detector.go
- cognitive_complexity.go
- community_graph.go
- community_metrics.go
- complexity.go
- complexity_analyzer.go
- concrete_dependency_detector.go
- constructor_analyzer.go
- coupling_metrics.go
- dead_code.go
- dependency_graph.go
- dependency_topology.go
- dfa.go
- dfa_builder.go
- di_antipattern_detector.go
- di_helpers.go
- file_analyzer.go
- framework_patterns.go
- grouping_compat.go
- grouping_mode.go
- hidden_dependency_detector.go
- lcom.go
- leiden.go
- lsh_index.go
- module_analyzer.go
- nesting_depth.go
- parsed_module.go
- python_cfg.go
- python_comments.go
- raw_metrics.go
- reachability.go
- reexport_resolver.go
- semantic_similarity.go
- service_locator_detector.go
- similarity_analyzer.go
- structural_similarity.go