From c969134b0592881991128607bb08ea6931f38bed Mon Sep 17 00:00:00 2001 From: Ivan Date: Wed, 11 Nov 2026 21:50:24 +0400 Subject: [PATCH] feat(parser): language-aware cohesion for JavaScript and TypeScript Cohesion was measured only by shared types in function signatures. JS and TS have no signature types, so every function was counted isolated and any module with five or more functions lost the full cohesion penalty: a hard ceiling of 85 regardless of design. Add AnalyzeCohesionLang and use shared module symbols for JS/TS: top-level declarations a function references, its own name, and the this.* fields its methods use. Unrelated helpers still score low; a class or a module built on its own helpers scores high. Typed languages keep the existing type signal. Tests cover cohesive classes, method call chains, shared helpers, unrelated helpers, TypeScript, unknown-language fallback, and a Go regression. Fixtures are embedded from each package's testdata so the test files stay self-scan clean. --- internal/analyzer/analyzer.go | 2 +- internal/analyzer/cohesion_lang_test.go | 92 +++++ .../testdata/cohesion/go_shared_types.txt | 13 + .../testdata/cohesion/js_cohesive_class.txt | 31 ++ .../cohesion/js_unrelated_functions.txt | 23 ++ internal/parser/cohesion.go | 334 +++++++++++++----- internal/parser/cohesion_lang_test.go | 77 ++++ .../testdata/cohesion/go_shared_types.txt | 13 + .../testdata/cohesion/js_cohesive_class.txt | 31 ++ .../testdata/cohesion/js_method_chain.txt | 21 ++ .../testdata/cohesion/js_shared_helpers.txt | 21 ++ .../cohesion/js_unrelated_functions.txt | 23 ++ 12 files changed, 597 insertions(+), 84 deletions(-) create mode 100644 internal/analyzer/cohesion_lang_test.go create mode 100644 internal/analyzer/testdata/cohesion/go_shared_types.txt create mode 100644 internal/analyzer/testdata/cohesion/js_cohesive_class.txt create mode 100644 internal/analyzer/testdata/cohesion/js_unrelated_functions.txt create mode 100644 internal/parser/cohesion_lang_test.go create mode 100644 internal/parser/testdata/cohesion/go_shared_types.txt create mode 100644 internal/parser/testdata/cohesion/js_cohesive_class.txt create mode 100644 internal/parser/testdata/cohesion/js_method_chain.txt create mode 100644 internal/parser/testdata/cohesion/js_shared_helpers.txt create mode 100644 internal/parser/testdata/cohesion/js_unrelated_functions.txt diff --git a/internal/analyzer/analyzer.go b/internal/analyzer/analyzer.go index 4e8a31c..a39f9db 100644 --- a/internal/analyzer/analyzer.go +++ b/internal/analyzer/analyzer.go @@ -103,7 +103,7 @@ func Analyze(src SourceInput, t Thresholds) QualityResult { dupPairs := parser.DetectDuplications(bloats, lines, t.DupMinLines, t.DupMinSimilarity) smells = append(smells, parser.DetectDuplicationSmells(dupPairs)...) - cohesion := parser.AnalyzeCohesion(bloats, lines) + cohesion := parser.AnalyzeCohesionLang(src.Lang, bloats, lines) addSmell(&smells, parser.DetectLowCohesionSmell(cohesion, 50, 75)) raw := computeScore(scoreParams{smells: smells, loc: loc, fnCount: countReal(bloats), coh: cohesion, dups: dupPairs, t: t}) diff --git a/internal/analyzer/cohesion_lang_test.go b/internal/analyzer/cohesion_lang_test.go new file mode 100644 index 0000000..0ec6508 --- /dev/null +++ b/internal/analyzer/cohesion_lang_test.go @@ -0,0 +1,92 @@ +package analyzer_test + +import ( + "embed" + "testing" + + "github.com/ailinter/ailinter/internal/analyzer" +) + +//go:embed testdata/cohesion/*.txt +var cohesionFixtures embed.FS + +func readCohesionFixture(t *testing.T, name string) string { + t.Helper() + data, err := cohesionFixtures.ReadFile("testdata/cohesion/" + name) + if err != nil { + t.Fatalf("read fixture %s: %v", name, err) + } + return string(data) +} + +func hasSmell(result analyzer.QualityResult, name string) bool { + for _, smell := range result.Smells { + if smell.Name == name { + return true + } + } + return false +} + +func TestAnalyze_JavascriptClassDoesNotGetLowCohesion(t *testing.T) { + result := analyzer.Analyze( + analyzer.SourceInput{ + FilePath: "counter.js", + Source: readCohesionFixture(t, "js_cohesive_class.txt"), + Lang: "javascript", + }, + analyzer.DefaultThresholds("javascript"), + ) + + if hasSmell(result, "low_cohesion") { + t.Fatalf("a class sharing this.value must not be low cohesion: %+v", result.Smells) + } + if result.Score < 95 { + t.Errorf("cohesive JavaScript should score at least 95, got %d", result.Score) + } +} + +func TestAnalyze_JavascriptUnrelatedFunctionsStillGetLowCohesion(t *testing.T) { + result := analyzer.Analyze( + analyzer.SourceInput{ + FilePath: "helpers.js", + Source: readCohesionFixture(t, "js_unrelated_functions.txt"), + Lang: "javascript", + }, + analyzer.DefaultThresholds("javascript"), + ) + + if !hasSmell(result, "low_cohesion") { + t.Fatalf("unrelated helpers should still be flagged: %+v", result.Smells) + } +} + +func TestAnalyze_TypeScriptClassDoesNotGetLowCohesion(t *testing.T) { + result := analyzer.Analyze( + analyzer.SourceInput{ + FilePath: "counter.ts", + Source: readCohesionFixture(t, "js_cohesive_class.txt"), + Lang: "typescript", + }, + analyzer.DefaultThresholds("typescript"), + ) + + if hasSmell(result, "low_cohesion") { + t.Fatalf("TypeScript uses the same symbol signal: %+v", result.Smells) + } +} + +func TestAnalyze_GoCohesionUnchanged(t *testing.T) { + result := analyzer.Analyze( + analyzer.SourceInput{ + FilePath: "data.go", + Source: readCohesionFixture(t, "go_shared_types.txt"), + Lang: "go", + }, + analyzer.DefaultThresholds("go"), + ) + + if hasSmell(result, "low_cohesion") { + t.Fatalf("shared *Data should keep Go cohesion high: %+v", result.Smells) + } +} diff --git a/internal/analyzer/testdata/cohesion/go_shared_types.txt b/internal/analyzer/testdata/cohesion/go_shared_types.txt new file mode 100644 index 0000000..5af85f1 --- /dev/null +++ b/internal/analyzer/testdata/cohesion/go_shared_types.txt @@ -0,0 +1,13 @@ +package main + +type Data struct{ N int } + +func ReadData(d *Data) int { return d.N } + +func WriteData(d *Data, n int) { d.N = n } + +func CopyData(d *Data) *Data { return &Data{N: d.N} } + +func ClearData(d *Data) { d.N = 0 } + +func SizeData(d *Data) int { return d.N } diff --git a/internal/analyzer/testdata/cohesion/js_cohesive_class.txt b/internal/analyzer/testdata/cohesion/js_cohesive_class.txt new file mode 100644 index 0000000..46eb4af --- /dev/null +++ b/internal/analyzer/testdata/cohesion/js_cohesive_class.txt @@ -0,0 +1,31 @@ +const LIMIT = 4; + +class Counter { + constructor() { + this.value = 0; + } + + inc() { + this.value = this.clamp(this.value + 1); + } + + dec() { + this.value = this.clamp(this.value - 1); + } + + clamp(value) { + return Math.min(LIMIT, value); + } + + reset() { + this.value = 0; + } + + read() { + return this.value; + } + + isZero() { + return this.value === 0; + } +} diff --git a/internal/analyzer/testdata/cohesion/js_unrelated_functions.txt b/internal/analyzer/testdata/cohesion/js_unrelated_functions.txt new file mode 100644 index 0000000..01ba12e --- /dev/null +++ b/internal/analyzer/testdata/cohesion/js_unrelated_functions.txt @@ -0,0 +1,23 @@ +function parseName(text) { + return text.trim(); +} + +function formatDate(date) { + return date.toISOString(); +} + +function readEnv(key) { + return key.length; +} + +function hashBytes(bytes) { + return bytes.length; +} + +function sortIds(ids) { + return ids.sort(); +} + +function logError(error) { + return String(error); +} diff --git a/internal/parser/cohesion.go b/internal/parser/cohesion.go index a0f2d1c..b12db83 100644 --- a/internal/parser/cohesion.go +++ b/internal/parser/cohesion.go @@ -2,6 +2,7 @@ package parser import ( "fmt" + "regexp" "strings" ) @@ -14,67 +15,260 @@ type CohesionResult struct { IsLowCohesion bool } -// AnalyzeCohesion estimates module cohesion by checking how many functions -// share common types in their signatures (parameters, returns). -// Low cohesion: many isolated functions that don't share types with others. +var jsPatterns = struct { + functionDecl *regexp.Regexp + classDecl *regexp.Regexp + varDecl *regexp.Regexp + thisProp *regexp.Regexp + identifier *regexp.Regexp +}{ + functionDecl: regexp.MustCompile(`^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)`), + classDecl: regexp.MustCompile(`^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)`), + varDecl: regexp.MustCompile(`^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)`), + thisProp: regexp.MustCompile(`\bthis\.([A-Za-z_$][\w$]*)`), + identifier: regexp.MustCompile(`[A-Za-z_$][\w$]*`), +} + +var typeKeywords = map[string]bool{ + "func": true, "function": true, "def": true, "var": true, "const": true, + "return": true, "if": true, "for": true, "while": true, "switch": true, + "case": true, "break": true, "continue": true, "else": true, "nil": true, + "null": true, "true": true, "false": true, "error": true, "err": true, + "int": true, "string": true, "float64": true, "float32": true, "bool": true, + "byte": true, "void": true, "auto": true, "self": true, "this": true, + "new": true, "make": true, "len": true, "append": true, "range": true, + "defer": true, "go": true, +} + +// cohesionSets holds one symbol set per function. A function is isolated when its set does not +// intersect any other set. +type cohesionSets []map[string]bool + +// AnalyzeCohesion estimates cohesion from shared type names in function signatures. +// It is the right signal for typed languages; use AnalyzeCohesionLang for untyped ones. func AnalyzeCohesion(bloats []FunctionBloat, lines []string) CohesionResult { - validFuncs := make([]FunctionBloat, 0) - for _, b := range bloats { - if b.Name != "unknown" && b.Name != "anonymous" && b.LineCount >= 2 { - validFuncs = append(validFuncs, b) - } + validFuncs := validFunctions(bloats) + if len(validFuncs) <= 3 { + return CohesionResult{TotalFuncs: len(validFuncs), CohesionScore: 1.0} } + sets := make(cohesionSets, len(validFuncs)) + for i, fn := range validFuncs { + sets[i] = extractTypeReferences(functionBody(fn, lines, 10)) + } + + isolated, total := countIsolated(sets) + return cohesionFromCounts(len(validFuncs), isolated, total) +} + +// AnalyzeCohesionLang picks the cohesion signal that fits the language. +// +// Typed languages are measured by shared types in signatures. JavaScript and TypeScript have no +// reliable signature types, so that metric marks every function isolated and caps the score at 85 +// for any module with five or more functions. For them, cohesion is measured by shared module +// symbols instead: top-level declarations a function references, plus the `this.*` fields its +// methods share. A module of unrelated helpers still scores low; a class or a module built on its +// own helpers scores high. +func AnalyzeCohesionLang(lang string, bloats []FunctionBloat, lines []string) CohesionResult { + switch lang { + case "javascript", "typescript": + return analyzeSymbolCohesion(bloats, lines) + default: + return AnalyzeCohesion(bloats, lines) + } +} + +// analyzeSymbolCohesion measures how many functions share a symbol with another function. +func analyzeSymbolCohesion(bloats []FunctionBloat, lines []string) CohesionResult { + validFuncs := validFunctions(bloats) if len(validFuncs) <= 3 { return CohesionResult{TotalFuncs: len(validFuncs), CohesionScore: 1.0} } - // Extract types referenced in each function's first few lines (signature+body start) - funcTypes := make(map[string]map[string]bool) // funcName -> set of types - for _, fn := range validFuncs { - end := fn.LineStart + fn.LineCount - 1 - if end > len(lines) { - end = len(lines) + moduleNames := moduleLevelNames(validFuncs, lines) + sets := make(cohesionSets, len(validFuncs)) + for i, fn := range validFuncs { + sets[i] = functionSymbols(fn, lines, moduleNames) + } + + return cohesionFromCounts(len(validFuncs), countIsolatedSets(sets), 0) +} + +func countIsolated(sets cohesionSets) (int, int) { + isolated, total := 0, 0 + for i, types := range sets { + if len(types) == 0 || !sets.shares(types, i) { + isolated++ + } + total += len(types) + } + return isolated, total +} + +func countIsolatedSets(sets cohesionSets) int { + isolated := 0 + for i := range sets { + if !sets.shares(sets[i], i) { + isolated++ } - start := fn.LineStart - 1 - if start < 0 { - start = 0 + } + return isolated +} + +func (sets cohesionSets) shares(set map[string]bool, at int) bool { + for other, otherSet := range sets { + if other == at { + continue } - // Only look at first ~10 lines of function for type references - scopeEnd := start + 10 - if scopeEnd > end { - scopeEnd = end + if intersects(set, otherSet) { + return true } - body := strings.Join(lines[start:scopeEnd], " ") - types := extractTypeReferences(body) - funcTypes[fn.Name] = types } + return false +} + +// cohesionFromCounts is the single place that turns counted functions into a result. +func cohesionFromCounts(functions, isolated, sharedTypes int) CohesionResult { + score := 1.0 + if functions > 0 { + score = float64(functions-isolated) / float64(functions) + } + return CohesionResult{ + TotalFuncs: functions, + SharedTypeCount: sharedTypes, + IsolatedFuncs: isolated, + CohesionScore: score, + IsLowCohesion: lowCohesion(score, functions), + } +} - // Count shared types across functions - totalTypeCount := 0 - isolatedCount := 0 - for fnName, types := range funcTypes { - if len(types) == 0 || !hasSharedType(fnName, types, funcTypes) { - isolatedCount++ +func lowCohesion(score float64, functions int) bool { + if functions < 5 { + return false + } + return score < 0.5 +} + +// validFunctions keeps the functions that carry enough signal to judge. +func validFunctions(bloats []FunctionBloat) []FunctionBloat { + valid := make([]FunctionBloat, 0, len(bloats)) + for _, b := range bloats { + if isValidFunction(b) { + valid = append(valid, b) } - totalTypeCount += len(types) } + return valid +} - // Cohesion score: ratio of functions with shared types - n := len(validFuncs) - sharedCount := n - isolatedCount - score := float64(sharedCount) / float64(n) +func isValidFunction(b FunctionBloat) bool { + if b.LineCount < 2 { + return false + } + if b.Name == "unknown" { + return false + } + return b.Name != "anonymous" +} - isLow := score < 0.5 && n >= 5 +// functionBody returns the first maxLines of a function, joined for scanning. +func functionBody(fn FunctionBloat, lines []string, maxLines int) string { + start := max(0, fn.LineStart-1) + end := min(len(lines), start+fn.LineCount) + if maxLines > 0 && end > start+maxLines { + end = start + maxLines + } + return strings.Join(lines[start:end], " ") +} - return CohesionResult{ - TotalFuncs: n, - IsolatedFuncs: isolatedCount, - CohesionScore: score, - IsLowCohesion: isLow, +// moduleLevelNames finds declarations outside every function: top-level functions, classes and +// constants. These are the symbols a function can share with a sibling. +func moduleLevelNames(bloats []FunctionBloat, lines []string) map[string]bool { + inside := insideFunctionLines(bloats, len(lines)) + names := make(map[string]bool) + addFunctionNames(names, bloats) + for i, line := range lines { + if inside[i] { + continue + } + addDeclaredName(names, line) + } + return names +} + +func addFunctionNames(names map[string]bool, bloats []FunctionBloat) { + for _, fn := range bloats { + if isNamedFunction(fn.Name) { + names[fn.Name] = true + } + } +} + +func insideFunctionLines(bloats []FunctionBloat, total int) []bool { + inside := make([]bool, total) + for _, fn := range bloats { + markFunctionRange(inside, fn) + } + return inside +} + +func markFunctionRange(inside []bool, fn FunctionBloat) { + start := max(0, fn.LineStart-1) + end := min(len(inside), start+fn.LineCount) + for i := start; i < end; i++ { + inside[i] = true } } +func addDeclaredName(names map[string]bool, line string) { + patterns := []*regexp.Regexp{jsPatterns.functionDecl, jsPatterns.classDecl, jsPatterns.varDecl} + for _, pattern := range patterns { + if match := pattern.FindStringSubmatch(line); match != nil { + names[match[1]] = true + } + } +} + +func isNamedFunction(name string) bool { + return name != "" && name != "unknown" && name != "anonymous" && name != "arrow" +} + +// functionSymbols collects the module declarations a function references and the fields it reads +// or writes through `this`. +func functionSymbols(fn FunctionBloat, lines []string, moduleNames map[string]bool) map[string]bool { + symbols := make(map[string]bool) + if isNamedFunction(fn.Name) { + symbols[fn.Name] = true + symbols["this."+fn.Name] = true + } + body := functionBody(fn, lines, 0) + addThisFields(symbols, body) + addModuleReferences(symbols, body, moduleNames) + return symbols +} + +func addThisFields(symbols map[string]bool, body string) { + for _, match := range jsPatterns.thisProp.FindAllStringSubmatch(body, -1) { + symbols["this."+match[1]] = true + } +} + +func addModuleReferences(symbols map[string]bool, body string, moduleNames map[string]bool) { + for _, word := range jsPatterns.identifier.FindAllString(body, -1) { + if moduleNames[word] { + symbols[word] = true + } + } +} + +func intersects(first, second map[string]bool) bool { + for symbol := range first { + if second[symbol] { + return true + } + } + return false +} + // DetectLowCohesionSmell converts cohesion analysis to a Smell. func DetectLowCohesionSmell(result CohesionResult, warningThreshold int, badThreshold int) *Smell { if !result.IsLowCohesion { @@ -89,7 +283,7 @@ func DetectLowCohesionSmell(result CohesionResult, warningThreshold int, badThre Name: "low_cohesion", Severity: sev, Message: fmt.Sprintf("Low cohesion: %d/%d functions are isolated (score: %.1f)", result.IsolatedFuncs, result.TotalFuncs, result.CohesionScore*100), - AIPrompt: fmt.Sprintf("WARNING: Low cohesion detected — %d of %d functions don't share types with others. Consider extracting unrelated functions into separate modules (SRP).", + AIPrompt: fmt.Sprintf("WARNING: Low cohesion detected — %d of %d functions don't share types or module symbols with others. Consider extracting unrelated functions into separate modules (SRP).", result.IsolatedFuncs, result.TotalFuncs), } } @@ -97,51 +291,25 @@ func DetectLowCohesionSmell(result CohesionResult, warningThreshold int, badThre // extractTypeReferences finds type-like identifiers in function signatures. func extractTypeReferences(text string) map[string]bool { types := make(map[string]bool) - - // Common type patterns in Go, C++, Python, etc. - // Look for capitalized words (likely types in most languages) - words := strings.Fields(text) - for _, w := range words { - // Strip punctuation - w = strings.Trim(w, "()[]{}*&,.;:\"'") - if len(w) < 3 { - continue - } - // Skip common keywords - lower := strings.ToLower(w) - switch lower { - case "func", "function", "def", "var", "const", "return", "if", "for", - "while", "switch", "case", "break", "continue", "else", "nil", - "null", "true", "false", "error", "err", "int", "string", - "float64", "float32", "bool", "byte", "void", "auto", "self", - "this", "new", "make", "len", "append", "range", "defer", "go": - continue - } - // Capitalized words are likely type names - if w[0] >= 'A' && w[0] <= 'Z' { - types[w] = true - } - // Pointer types: *Type - if strings.HasPrefix(w, "*") && len(w) > 1 { - typeName := strings.TrimPrefix(w, "*") - if typeName[0] >= 'A' && typeName[0] <= 'Z' { - types[typeName] = true - } + for _, word := range strings.Fields(text) { + if name, ok := typeName(word); ok { + types[name] = true } } return types } -func hasSharedType(fnName string, types map[string]bool, all map[string]map[string]bool) bool { - for otherName, otherTypes := range all { - if fnName == otherName { - continue - } - for t := range types { - if otherTypes[t] { - return true - } - } +// typeName returns a type-like word after stripping punctuation and keywords. +func typeName(word string) (string, bool) { + word = strings.Trim(word, "()[]{}*&,.;:\"'") + if len(word) < 3 { + return "", false } - return false + if typeKeywords[strings.ToLower(word)] { + return "", false + } + if word[0] < 'A' || word[0] > 'Z' { + return "", false + } + return word, true } diff --git a/internal/parser/cohesion_lang_test.go b/internal/parser/cohesion_lang_test.go new file mode 100644 index 0000000..a8a021b --- /dev/null +++ b/internal/parser/cohesion_lang_test.go @@ -0,0 +1,77 @@ +package parser_test + +import ( + "embed" + "reflect" + "strings" + "testing" + + "github.com/ailinter/ailinter/internal/parser" +) + +//go:embed testdata/cohesion/*.txt +var cohesionFixtures embed.FS + +func readCohesionFixture(t *testing.T, name string) string { + t.Helper() + data, err := cohesionFixtures.ReadFile("testdata/cohesion/" + name) + if err != nil { + t.Fatalf("read fixture %s: %v", name, err) + } + return string(data) +} + +type cohesionCase struct { + name string + lang string + fixture string + detect func([]string) []parser.FunctionBloat + low bool + min float64 +} + +func TestAnalyzeCohesionLang(t *testing.T) { + cases := []cohesionCase{ + {"JavascriptClass", "javascript", "js_cohesive_class.txt", parser.DetectFunctionBloatsTS, false, 1.0}, + {"JavascriptUnrelated", "javascript", "js_unrelated_functions.txt", parser.DetectFunctionBloatsTS, true, 0}, + {"JavascriptSharedHelpers", "javascript", "js_shared_helpers.txt", parser.DetectFunctionBloatsTS, false, 0.8}, + {"JavascriptMethodChain", "javascript", "js_method_chain.txt", parser.DetectFunctionBloatsTS, false, 0.8}, + {"TypeScriptClass", "typescript", "js_cohesive_class.txt", parser.DetectFunctionBloatsTS, false, 1.0}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + assertCohesion(t, tc) + }) + } +} + +func assertCohesion(t *testing.T, tc cohesionCase) { + t.Helper() + lines := strings.Split(readCohesionFixture(t, tc.fixture), "\n") + result := parser.AnalyzeCohesionLang(tc.lang, tc.detect(lines), lines) + if result.IsLowCohesion != tc.low { + t.Errorf("low cohesion = %v, want %v (%+v)", result.IsLowCohesion, tc.low, result) + } + if result.CohesionScore < tc.min { + t.Errorf("cohesion %.2f is below %.2f", result.CohesionScore, tc.min) + } +} + +func TestAnalyzeCohesionLang_TypedFallback(t *testing.T) { + goLines := strings.Split(readCohesionFixture(t, "go_shared_types.txt"), "\n") + goBloats := parser.DetectFunctionBloats(goLines) + wantGo := parser.AnalyzeCohesion(goBloats, goLines) + if got := parser.AnalyzeCohesionLang("go", goBloats, goLines); !reflect.DeepEqual(got, wantGo) { + t.Errorf("go must keep the type signal: got %+v, want %+v", got, wantGo) + } + if wantGo.IsLowCohesion { + t.Errorf("shared *Data should stay cohesive, got %+v", wantGo) + } + + jsLines := strings.Split(readCohesionFixture(t, "js_cohesive_class.txt"), "\n") + jsBloats := parser.DetectFunctionBloatsTS(jsLines) + wantUnknown := parser.AnalyzeCohesion(jsBloats, jsLines) + if got := parser.AnalyzeCohesionLang("", jsBloats, jsLines); !reflect.DeepEqual(got, wantUnknown) { + t.Errorf("unknown language must fall back: got %+v, want %+v", got, wantUnknown) + } +} diff --git a/internal/parser/testdata/cohesion/go_shared_types.txt b/internal/parser/testdata/cohesion/go_shared_types.txt new file mode 100644 index 0000000..5af85f1 --- /dev/null +++ b/internal/parser/testdata/cohesion/go_shared_types.txt @@ -0,0 +1,13 @@ +package main + +type Data struct{ N int } + +func ReadData(d *Data) int { return d.N } + +func WriteData(d *Data, n int) { d.N = n } + +func CopyData(d *Data) *Data { return &Data{N: d.N} } + +func ClearData(d *Data) { d.N = 0 } + +func SizeData(d *Data) int { return d.N } diff --git a/internal/parser/testdata/cohesion/js_cohesive_class.txt b/internal/parser/testdata/cohesion/js_cohesive_class.txt new file mode 100644 index 0000000..46eb4af --- /dev/null +++ b/internal/parser/testdata/cohesion/js_cohesive_class.txt @@ -0,0 +1,31 @@ +const LIMIT = 4; + +class Counter { + constructor() { + this.value = 0; + } + + inc() { + this.value = this.clamp(this.value + 1); + } + + dec() { + this.value = this.clamp(this.value - 1); + } + + clamp(value) { + return Math.min(LIMIT, value); + } + + reset() { + this.value = 0; + } + + read() { + return this.value; + } + + isZero() { + return this.value === 0; + } +} diff --git a/internal/parser/testdata/cohesion/js_method_chain.txt b/internal/parser/testdata/cohesion/js_method_chain.txt new file mode 100644 index 0000000..21f54cc --- /dev/null +++ b/internal/parser/testdata/cohesion/js_method_chain.txt @@ -0,0 +1,21 @@ +class Pipeline { + run() { + return this.prepare(); + } + + prepare() { + return this.execute(); + } + + execute() { + return this.audit(); + } + + audit() { + return this.report(); + } + + report() { + return 1; + } +} diff --git a/internal/parser/testdata/cohesion/js_shared_helpers.txt b/internal/parser/testdata/cohesion/js_shared_helpers.txt new file mode 100644 index 0000000..72fe0a2 --- /dev/null +++ b/internal/parser/testdata/cohesion/js_shared_helpers.txt @@ -0,0 +1,21 @@ +const SCALE = 2; + +function double(value) { + return value * SCALE; +} + +function quadruple(value) { + return double(double(value)); +} + +function describe(value) { + return String(quadruple(value)); +} + +function label(value) { + return "n=" + describe(value); +} + +function readout(value) { + return label(quadruple(value)); +} diff --git a/internal/parser/testdata/cohesion/js_unrelated_functions.txt b/internal/parser/testdata/cohesion/js_unrelated_functions.txt new file mode 100644 index 0000000..01ba12e --- /dev/null +++ b/internal/parser/testdata/cohesion/js_unrelated_functions.txt @@ -0,0 +1,23 @@ +function parseName(text) { + return text.trim(); +} + +function formatDate(date) { + return date.toISOString(); +} + +function readEnv(key) { + return key.length; +} + +function hashBytes(bytes) { + return bytes.length; +} + +function sortIds(ids) { + return ids.sort(); +} + +function logError(error) { + return String(error); +}