domain

package
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultType1CloneThreshold = 0.85
	DefaultType2CloneThreshold = 0.80
	DefaultType3CloneThreshold = 0.80
	DefaultType4CloneThreshold = 0.65
)

Clone type thresholds (similarity score 0.0-1.0).

Type-2 and Type-3 share one threshold on purpose. The detector reports pairs from the Type-3 threshold, so a lower Type-2 threshold would classify pairs that are then never reported. What separates the two types is the syntactic gate, not the similarity: a pair at or above 0.80 whose normalized trees also match is Type-2, otherwise Type-3. Pairs between 0.70 and 0.80 were mostly functions that share a shape rather than code, such as two output formatters' switch statements, which is why the floor moved up from 0.70. The JavaScript/TypeScript analyzer keeps its own thresholds in polyscan/internal/js/constants; they were tuned separately and Type-3 is off by default there.

View Source
const (
	DefaultDFAPairCountWeight   = 0.25
	DefaultDFAChainLengthWeight = 0.20
	DefaultDFACrossBlockWeight  = 0.20
	DefaultDFADefKindWeight     = 0.20
	DefaultDFAUseKindWeight     = 0.15
)

DFA feature weights for similarity comparison.

View Source
const (
	DefaultCFGFeatureWeight = 0.60
	DefaultDFAFeatureWeight = 0.40
)

CFG/DFA combined weights for semantic similarity.

View Source
const (
	DefaultComplexityLowThreshold    = 9
	DefaultComplexityMediumThreshold = 19
)

Complexity thresholds for risk assessment.

View Source
const (
	DefaultCBOLowThreshold    = 3
	DefaultCBOMediumThreshold = 7
)

CBO (Coupling Between Objects) thresholds.

View Source
const (
	DefaultLCOMLowThreshold    = 2
	DefaultLCOMMediumThreshold = 5
)

LCOM (Lack of Cohesion of Methods) thresholds.

View Source
const (
	DefaultCloneMinLines            = 10
	DefaultCloneMinNodes            = 20
	DefaultCloneMaxEditDistance     = 50.0
	DefaultCloneSimilarityThreshold = 0.65
	DefaultCloneGroupingThreshold   = 0.65
)

Clone detection parameters.

View Source
const (
	DefaultLSHAutoThreshold       = 500
	DefaultLSHSimilarityThreshold = 0.50
	DefaultLSHBands               = 32
	DefaultLSHRows                = 4
	DefaultLSHHashes              = 128
)

LSH (Locality-Sensitive Hashing) parameters.

View Source
const (
	DefaultMaxMemoryMB    = 100
	DefaultBatchSize      = 100
	DefaultMaxGoroutines  = 4
	DefaultTimeoutSeconds = 300
)

Performance parameters.

View Source
const (
	ErrCodeInvalidInput      = "INVALID_INPUT"
	ErrCodeFileNotFound      = "FILE_NOT_FOUND"
	ErrCodeParseError        = "PARSE_ERROR"
	ErrCodeAnalysisError     = "ANALYSIS_ERROR"
	ErrCodeConfigError       = "CONFIG_ERROR"
	ErrCodeOutputError       = "OUTPUT_ERROR"
	ErrCodeUnsupportedFormat = "UNSUPPORTED_FORMAT"
	ErrCodeValidation        = "VALIDATION_ERROR"
	ErrCodeTimeout           = "TIMEOUT"
	ErrCodeCancelled         = "CANCELLED"
	ErrCodeNotImplemented    = "NOT_IMPLEMENTED"
	ErrCodeInternal          = "INTERNAL_ERROR"
)

Error code constants for domain errors.

View Source
const (
	// Complexity thresholds and penalties
	ComplexityThresholdHigh   = 20
	ComplexityThresholdMedium = 10
	ComplexityThresholdLow    = 5
	ComplexityPenaltyHigh     = 20
	ComplexityPenaltyMedium   = 12
	ComplexityPenaltyLow      = 6

	// Code duplication thresholds and penalties
	// 0% = perfect, 60% = max penalty (using fragment ratio: clonedFragments/totalFragments).
	// The fragment ratio counts every function of ten or more lines that has any
	// partner at or above the Type-3 threshold, so it runs high on languages with
	// conventional function shapes: cobra, x/crypto and polyscan itself sit near
	// 20%, and testify and afero near 35%. Real duplication still saturates:
	// pyscn's app/ directory of near-identical use cases sits at 54% and six
	// renamed copies of one file at 100%.
	// DuplicationThresholdMedium and the three penalty constants are unused by
	// DuplicationPenalty, which is linear from Low to High; they are kept only
	// because pyscn aliases them.
	DuplicationThresholdHigh   = 60.0
	DuplicationThresholdMedium = 15.0
	DuplicationThresholdLow    = 0.0
	DuplicationPenaltyHigh     = 20
	DuplicationPenaltyMedium   = 12
	DuplicationPenaltyLow      = 6

	// CBO coupling scoring curve (used by CouplingPenalty)
	// Penalty grows linearly with the weighted ratio of problematic classes
	// and saturates (reaches the max penalty) at CouplingSaturationRatio.
	CouplingMediumWeight    = 0.3  // Medium-risk classes count 0.3 vs High = 1.0
	CouplingSaturationRatio = 0.40 // weighted ratio at which the penalty maxes out

	// Maximum penalties
	MaxDeadCodePenalty = 20
	MaxCriticalPenalty = 10
	MaxCyclesPenalty   = 10
	MaxDepthPenalty    = 3
	MaxArchPenalty     = 12
	MaxMSDPenalty      = 3

	// Score display scale - all categories normalized to this base
	MaxScoreBase = 20

	// Actual maximum penalty values for normalization
	MaxDependencyPenalty   = MaxCyclesPenalty + MaxDepthPenalty + MaxMSDPenalty // 16
	MaxArchitecturePenalty = MaxArchPenalty                                     // 12

	// Grade thresholds
	GradeAThreshold = 90
	GradeBThreshold = 75
	GradeCThreshold = 60
	GradeDThreshold = 45

	// Score quality thresholds (aligned with grade thresholds)
	ScoreThresholdExcellent = 90 // Excellent: 90-100
	ScoreThresholdGood      = 75 // Good: 75-89
	ScoreThresholdFair      = 60 // Fair: 60-74

	// Files that fail to parse are absent from every metric, so without a
	// penalty they score better than working code. The bounds are anchored to
	// the grade thresholds: a single unanalyzable file forfeits an A, and a
	// target where nothing parses cannot rank above F.
	MinParseErrorPenalty = 100 - GradeAThreshold + 1
	MaxParseErrorPenalty = 100 - GradeDThreshold + 1

	// Other constants
	MinimumScore                = 0 // Allow truly low scores for severely problematic code
	HealthyThreshold            = 70
	FallbackComplexityThreshold = 10
	FallbackPenalty             = 5
)

Health score calculation constants shared by all language analyzers. Grade computation must match across tools; language-specific penalty formulas (complexity, dead code) live in each analyzer and compose with the shared calculators below.

Variables

View Source
var CloneTypeDescriptions = map[CloneType]string{
	Type1Clone: "Identical code fragments except for whitespace and comments",
	Type2Clone: "Structurally identical with renamed identifiers or changed literals",
	Type3Clone: "Near-miss clones with added, removed, or modified statements",
	Type4Clone: "Semantically similar code with different syntactic structure",
}

CloneTypeDescriptions maps clone types to their descriptions.

View Source
var CloneTypeNames = map[CloneType]string{
	Type1Clone: "Exact",
	Type2Clone: "Renamed",
	Type3Clone: "Near-miss",
	Type4Clone: "Semantic",
}

CloneTypeNames maps clone types to their short names.

Functions

func ArchitecturePenalty

func ArchitecturePenalty(compliance float64) int

ArchitecturePenalty calculates the penalty for architecture compliance (max 12). Compliance is a 0..1 ratio. A NaN compliance is treated as missing data and yields no penalty.

func CouplingPenalty

func CouplingPenalty(highCouplingClasses, mediumCouplingClasses, totalClasses int) int

CouplingPenalty calculates the penalty for class coupling (max 20) from the weighted ratio of problematic classes (High = 1.0, Medium = CouplingMediumWeight), saturating at CouplingSaturationRatio.

func DependencyPenalty

func DependencyPenalty(totalModules, modulesInCycles, maxDepth int, mainSequenceDeviation float64) int

DependencyPenalty calculates the penalty for module dependencies (max 16: cycles=10, depth=3, main sequence deviation=3).

func DuplicationPenalty

func DuplicationPenalty(duplicationPercent float64) int

DuplicationPenalty calculates the penalty for code duplication (max 20). Linear: 0% duplication = 0 penalty, DuplicationThresholdHigh (60%) = max. A NaN percentage is treated as missing data and yields no penalty.

func GradeFromScore

func GradeFromScore(score int) string

GradeFromScore maps a health score to a letter grade. This mapping must stay identical across all language analyzers.

func HealthScoreFromPenalties

func HealthScoreFromPenalties(penalties ...int) int

HealthScoreFromPenalties returns 100 minus the sum of all penalties, floored at MinimumScore and capped at 100 (negative penalties cannot raise the score above a clean result).

func IsHealthyScore

func IsHealthyScore(score int) bool

IsHealthyScore reports whether a health score is considered healthy.

func LinearPenalty

func LinearPenalty(value, start, saturation float64) int

LinearPenalty maps a value onto a 0..MaxScoreBase penalty that starts at 0 when value <= start and grows linearly to the maximum at saturation. A NaN value is treated as missing data and yields no penalty.

func NormalizeToScoreBase

func NormalizeToScoreBase(penalty int, maxPenalty int) int

NormalizeToScoreBase normalizes a penalty value to the MaxScoreBase scale (0-20) so all category scores use a consistent display scale.

func ParseErrorPenalty added in v0.2.4

func ParseErrorPenalty(skippedFiles, totalFiles int) int

ParseErrorPenalty charges the health score for files that could not be analyzed at all. Such a file yields no functions, no dead code, no clones and no coupling, so without this term corrupting a file raises the score. The penalty grows with the unanalyzed fraction and never drops below MinParseErrorPenalty, so one broken file in a large tree still costs a grade.

func PenaltyToScore

func PenaltyToScore(penalty int, maxPenalty int) int

PenaltyToScore converts a penalty value to a 0-100 score.

Types

type CloneType

type CloneType int

CloneType represents the type of code clone (Type-1 through Type-4).

const (
	Type1Clone CloneType = 1 // Exact clones (identical except whitespace/comments)
	Type2Clone CloneType = 2 // Renamed/parameterized clones
	Type3Clone CloneType = 3 // Near-miss clones (statements added/removed)
	Type4Clone CloneType = 4 // Semantic clones (different syntax, same behavior)
)

func (CloneType) String

func (ct CloneType) String() string

String returns the string representation of a CloneType.

type DomainError

type DomainError struct {
	Code    string
	Message string
	Cause   error
}

DomainError represents a structured error with code, message, and optional cause.

func NewAnalysisError

func NewAnalysisError(message string, cause error) *DomainError

NewAnalysisError creates an error for analysis failures.

func NewCancelledError

func NewCancelledError(message string, cause error) *DomainError

NewCancelledError creates an error for cancelled operations.

func NewConfigError

func NewConfigError(message string, cause error) *DomainError

NewConfigError creates an error for configuration issues.

func NewDomainError

func NewDomainError(code, message string, cause error) *DomainError

NewDomainError creates a new DomainError with the given code, message, and optional cause.

func NewFileNotFoundError

func NewFileNotFoundError(message string, cause error) *DomainError

NewFileNotFoundError creates an error for missing files.

func NewInternalError

func NewInternalError(message string, cause error) *DomainError

NewInternalError creates an error for internal failures.

func NewInvalidInputError

func NewInvalidInputError(message string, cause error) *DomainError

NewInvalidInputError creates an error for invalid input.

func NewNotImplementedError

func NewNotImplementedError(message string, cause error) *DomainError

NewNotImplementedError creates an error for unimplemented features.

func NewOutputError

func NewOutputError(message string, cause error) *DomainError

NewOutputError creates an error for output failures.

func NewParseError

func NewParseError(message string, cause error) *DomainError

NewParseError creates an error for parse failures.

func NewTimeoutError

func NewTimeoutError(message string, cause error) *DomainError

NewTimeoutError creates an error for timeout conditions.

func NewUnsupportedFormatError

func NewUnsupportedFormatError(message string, cause error) *DomainError

NewUnsupportedFormatError creates an error for unsupported formats.

func NewValidationError

func NewValidationError(message string, cause error) *DomainError

NewValidationError creates an error for validation failures.

func (*DomainError) Error

func (e *DomainError) Error() string

Error implements the error interface.

func (*DomainError) Unwrap

func (e *DomainError) Unwrap() error

Unwrap returns the underlying cause for errors.Is/As support.

type OutputFormat

type OutputFormat string

OutputFormat represents an output format type.

const (
	OutputFormatText OutputFormat = "text"
	OutputFormatJSON OutputFormat = "json"
	OutputFormatYAML OutputFormat = "yaml"
	OutputFormatCSV  OutputFormat = "csv"
	OutputFormatHTML OutputFormat = "html"
	OutputFormatDOT  OutputFormat = "dot"
)

type RiskLevel

type RiskLevel string

RiskLevel represents the risk level of a metric.

const (
	RiskLevelLow    RiskLevel = "low"
	RiskLevelMedium RiskLevel = "medium"
	RiskLevelHigh   RiskLevel = "high"
)

type SortCriteria

type SortCriteria string

SortCriteria represents a sorting criterion for results.

const (
	SortByComplexity SortCriteria = "complexity"
	SortByName       SortCriteria = "name"
	SortByRisk       SortCriteria = "risk"
	SortBySimilarity SortCriteria = "similarity"
	SortBySize       SortCriteria = "size"
	SortByLocation   SortCriteria = "location"
	SortByCoupling   SortCriteria = "coupling"
	SortByCohesion   SortCriteria = "cohesion"
)

Jump to

Keyboard shortcuts

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