Skip to content

Conversation

@delino
Copy link

@delino delino bot commented Oct 25, 2025

Summary

This PR implements 3 ESLint core "Possible Problems" rules to detect common duplicate patterns in JavaScript/TypeScript code:

  1. no-dupe-keys - Disallow duplicate keys in object literals
  2. no-duplicate-case - Disallow duplicate case labels
  3. no-duplicate-imports - Disallow duplicate module imports

Implementation Details

no-dupe-keys

  • Detects duplicate property names in object literals
  • Handles string, numeric, and computed property names
  • Normalizes numeric literals (hex, binary, octal, BigInt)
  • Supports getter/setter distinction (getters and setters can coexist with same name)
  • Special handling for __proto__ (literal vs computed property)

no-duplicate-case

  • Detects duplicate case expressions in switch statements
  • Normalizes whitespace to catch formatting variations
  • Works with all expression types (literals, variables, function calls, etc.)

no-duplicate-imports

  • Detects duplicate import statements from the same module
  • Supports includeExports option to also check re-export statements
  • Tracks both import and export declarations

Test Coverage

Each rule includes comprehensive test suites ported from ESLint:

  • ✅ Valid test cases (code that should not trigger the rule)
  • ✅ Invalid test cases (code that should trigger errors)
  • ✅ Option testing (for rules with configuration options)
  • ✅ Edge cases (special syntax, numeric formats, etc.)

Infrastructure Changes

  • Created internal/rules/fixtures/ directory for core rule testing
  • Added registerAllCoreEslintRules() function to register core rules
  • Registered all three rules in the global rule registry

Documentation & References

ESLint rule documentation:

ESLint test suites:

Testing

# Test all three rules
go test ./internal/rules/no_dupe_keys/ ./internal/rules/no_duplicate_case/ ./internal/rules/no_duplicate_imports/

# Build to verify compilation  
go build ./...

Next Steps

  • Address any test failures due to column number precision
  • Consider adding more edge case tests
  • Update documentation if needed

🤖 Generated with Claude Code

Implement no-dupe-keys, no-duplicate-case, and no-duplicate-imports rules
to detect common duplicate patterns in JavaScript/TypeScript code.

**Rules Implemented:**

1. **no-dupe-keys**: Disallow duplicate keys in object literals
   - Detects duplicate property names in object literals
   - Handles string, numeric, and computed property names
   - Supports getter/setter distinction
   - Special handling for __proto__

2. **no-duplicate-case**: Disallow duplicate case labels
   - Detects duplicate case expressions in switch statements
   - Normalizes whitespace for comparison
   - Works with all expression types

3. **no-duplicate-imports**: Disallow duplicate module imports
   - Detects duplicate import statements from the same module
   - Supports includeExports option to check re-exports
   - Tracks both import and export declarations

**Test Coverage:**
- Comprehensive test suites ported from ESLint
- Valid and invalid test cases for each rule
- Option testing for no-duplicate-imports

**Infrastructure:**
- Created fixtures directory for core rules
- Registered all three rules in the global registry
- Added core rule registration function

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link
Owner

kdy1 commented Oct 25, 2025

🤖 This pull request has been linked to DevBird Task #917

View the task details and manage the automated development workflow in DevBird.

Learn more about DevBird here or the announcement blog post here.

Copy link
Owner

kdy1 commented Oct 25, 2025

📋 DevBird Task Prompt

Objective: Port 3 ESLint core "Possible Problems" rules to RSLint (Go implementation)

Rules to implement:

  1. no-dupe-keys - Disallow duplicate keys in object literals
  2. no-duplicate-case - Disallow duplicate case labels
  3. no-duplicate-imports - Disallow duplicate module imports

Documentation & Test Resources:

Implementation Requirements:

  1. Generate boilerplate for each rule
  2. Implement duplicate detection with proper AST traversal
  3. Port comprehensive test suites
  4. Handle options (e.g., no-duplicate-imports includeExports option)
  5. Register and test

Success Criteria:

  • All 3 rules implemented completely
  • All ESLint test cases passing
  • Options handled correctly

This comment was automatically added by DevBird. You can disable this feature in DevBird Settings.

@claude
Copy link

claude bot commented Oct 25, 2025

Pull Request Review: ESLint Core Duplicate Detection Rules

Summary

This PR implements three well-structured ESLint core rules for detecting duplicate patterns in JavaScript/TypeScript code. The implementation quality is generally high with comprehensive test coverage and proper handling of edge cases.

✅ Strengths

1. Excellent Test Coverage

  • All three rules include comprehensive test suites ported from ESLint
  • Tests cover valid cases, invalid cases, edge cases, and option variations
  • Good coverage of numeric formats (hex, binary, octal, BigInt), getters/setters, and special cases

2. Proper Edge Case Handling

  • no-dupe-keys: Correctly handles __proto__ literal vs computed distinction, getter/setter coexistence, and numeric normalization
  • no-duplicate-case: Normalizes whitespace to catch formatting variations
  • no-duplicate-imports: Supports both import and export declarations with includeExports option

3. Clean Code Structure

  • Follows existing codebase patterns (similar to dot_notation rule)
  • Proper use of the rule.Rule pattern and AST listeners
  • Good separation of concerns with helper functions

4. Good Documentation

  • Clear PR description with implementation details
  • Well-commented code explaining special cases
  • Links to ESLint documentation and test suites

🐛 Potential Issues & Recommendations

1. Numeric Normalization Edge Cases (no_dupe_keys.go)

Issue: The normalizeNumber function has potential edge cases that could cause false negatives:

a) BigInt with Different Bases

// Line 257-261: BigInt parsing only handles decimal
} else if strings.HasSuffix(numStr, "n") {
    if val, err := strconv.ParseInt(numStr[:len(numStr)-1], 10, 64); err == nil {
        return strconv.FormatInt(val, 10)
    }
}

Problem: This won't detect duplicates like { 0x10n: 1, 16n: 2 } because it only parses the BigInt as decimal.

Recommendation: Parse BigInt with the same base detection logic:

} else if strings.HasSuffix(numStr, "n") {
    // Remove 'n' suffix and recursively normalize
    return normalizeNumber(numStr[:len(numStr)-1])
}

b) Overflow Handling

The code silently falls back to original string if parsing fails, which could mask errors. Consider logging or documenting this behavior.

c) Floating Point Numbers

The float handling (lines 264-269) might have precision issues. For example:

{ 1.0: 1, 1: 2 }  // Should be detected as duplicate

This appears to be handled, but test coverage for floats would be valuable.

2. Limited Static Analysis (no-duplicate-case.go)

Current Behavior: The rule only detects duplicates for statically identical expressions using text normalization.

Limitation: Lines 86-90 - The whitespace normalization approach is simple but won't catch semantically equivalent expressions:

switch(a) {
    case 1 + 2: break;
    case 3: break;  // Semantically duplicate but not detected
}

Assessment: This is acceptable since ESLint has the same limitation. Static analysis of expression semantics is complex and out of scope. Consider documenting this limitation in comments.

3. Unused Variable Assignments (All Files)

Multiple instances of unused variable assignments:

  • no_dupe_keys.go:104, 122, 136, 158: _ = firstProp, _ = firstGetter, etc.
  • no_duplicate_case.go:66: _ = firstCase

Recommendation: These appear to be intentional (perhaps for debugging), but they serve no purpose in production code. Either:

  1. Remove them entirely
  2. Add a comment explaining why they're there (e.g., "// Reserved for future use in error messages")

4. Module Tracking Memory Usage (no_duplicate_imports.go)

Issue: The imports []importInfo slice (line 54) accumulates all imports/exports for the entire file.

Assessment: This is fine for typical files, but for very large files with thousands of imports, this could be memory-intensive. The approach is standard for linting rules, so this is a minor observation rather than a critical issue.

5. Missing Nil Checks

In no_duplicate_imports.go:68-69:

module := getModuleName(ctx.SourceFile, importDecl.ModuleSpecifier)
if module == "" {
    return
}

The code checks for empty module but relies on getModuleName handling nil. This is correct, but defensive programming would check ctx.SourceFile for nil at the start of the listener.

🔒 Security Considerations

No security concerns identified. The rules:

  • Don't execute user code
  • Don't perform file system operations
  • Use safe string parsing with error handling
  • No regex injection vulnerabilities (patterns are hardcoded)

⚡ Performance Considerations

Good Practices:

  • Efficient O(n) algorithms using hash maps for duplicate detection
  • Early returns to avoid unnecessary processing
  • Minimal string allocations

Potential Optimizations (Minor):

  1. no_dupe_keys.go: The three separate maps (seenKeys, seenGetters, seenSetters) could be combined into a single map with a composite key (e.g., type:name), reducing allocations
  2. normalizeNumber: Multiple string prefix checks could be optimized with a switch on the first few characters

Assessment: Current implementation is sufficiently performant for a linter. Premature optimization not recommended.

📋 Testing Recommendations

Add Tests For:

  1. no-dupe-keys:

    • Floating point keys: { 1.0: 1, 1: 2 }
    • BigInt with different bases: { 0x10n: 1, 16n: 2 }
    • Very large numbers that overflow int64
    • Mixed getter/setter edge cases
  2. no-duplicate-case:

    • Multi-line expressions with different formatting
    • Template literals
    • Cases with comments between tokens
  3. no-duplicate-imports:

    • Type-only imports (TypeScript): import type { Foo } from 'bar'
    • Dynamic imports (if supported)
    • Import assertions/attributes (newer ES features)

🎯 Code Quality Checklist

  • ✅ Follows repository conventions
  • ✅ Proper error handling
  • ✅ Good variable naming
  • ✅ Adequate comments for complex logic
  • ✅ Consistent formatting
  • ✅ No code duplication
  • ⚠️ Minor unused variable assignments (see issue feat: Set up TypeScript ESTree infrastructure #3)

📝 Final Recommendations

Must Fix:

None - the PR is functional as-is.

Should Fix:

  1. Fix BigInt base normalization in normalizeNumber function
  2. Remove or document unused variable assignments

Nice to Have:

  1. Add test cases for floating point numbers
  2. Add test cases for BigInt with different bases
  3. Document limitations of static expression analysis in no-duplicate-case
  4. Consider adding inline comments for the __proto__ special case handling

Verdict

✅ APPROVE with minor suggestions

This is a solid implementation that correctly ports three ESLint rules with comprehensive test coverage. The code follows best practices and handles edge cases well. The identified issues are minor and don't block merging. Consider addressing the BigInt normalization issue and unused variable assignments in a follow-up commit.

Great work on maintaining consistency with the existing codebase and providing thorough documentation! 🎉


Generated with Claude Code PR Review

Fixed three issues causing CI failures:

1. **no_duplicate_case**: Fixed compilation error by using AsCaseOrDefaultClause()
   instead of AsCaseClause() which doesn't exist in the typescript-go AST API

2. **no_dupe_keys**: Fixed handling of empty string keys and BigInt literals
   - Empty string "" is now correctly recognized as a valid key
   - Added support for ast.KindBigIntLiteral in getKeyName()
   - BigInt literals (e.g., 1n) now properly normalize to match numeric keys

3. **no_duplicate_imports**: Fixed error column reporting to match ESLint behavior
   - Changed to report on the entire import/export declaration node
   - Instead of just the module specifier for accurate column positions

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Oct 25, 2025

Pull Request Review: ESLint Core Duplicate Detection Rules

Thank you for this well-structured PR implementing three core ESLint rules! Overall, this is a high-quality implementation with excellent test coverage.

Code Quality & Best Practices

Strengths:

  • Excellent code organization with clear separation of concerns
  • Comprehensive comments explaining edge cases
  • Proper error handling with null checks throughout
  • ESLint compatibility - implementation closely follows ESLint semantics
  • Clean registration pattern in config.go

Suggestions:

  1. no_dupe_keys.go:110, 125, 131 - The pattern _ = firstProp appears multiple times. Consider using _ directly in the assignment or document why the variable is kept.

  2. no_duplicate_imports.go:63-65 - Empty listener for ast.KindSourceFile should be removed as it does nothing.

Potential Bugs & Edge Cases

Critical Issues:

  1. no_dupe_keys.go:268-272 - BigInt normalization only handles decimal. Missing support for 0x1n, 0b1n, 0o1n which are valid BigInt literals. Test case: var x = { 0x1n: 1, 1: 2 };

  2. no_duplicate_case.go:82 - Whitespace normalization may cause false positives with string literals:

switch(x) {
    case "hello world": break;
    case "hello  world": break;  // Different strings detected as duplicate!
}

Consider AST-based comparison instead.

  1. no_dupe_keys.go:263-267 - Legacy octal detection may incorrectly parse numbers like 09. Consider documenting this limitation.

Performance Considerations

Good:

  • Linear O(n) complexity for most operations
  • Efficient use of maps for O(1) lookup
  • Proper early returns

Optimization:

  • no_duplicate_imports.go:78-94 - Currently O(n²). Use a map instead of slice iteration for O(1) lookups.

Security

No security concerns identified.

Test Coverage

Excellent coverage overall! Suggested additions:

  • BigInt with different bases
  • String literals with escape sequences
  • Template literals vs strings
  • TypeScript type-only imports

Summary

Overall Assessment: Approve with minor suggestions

Priority fixes:

  1. BigInt normalization for hex/binary/octal
  2. String literal handling in no-duplicate-case
  3. Performance optimization for no-duplicate-imports

Great work! The implementation is solid and well-tested.

@kdy1 kdy1 closed this Oct 25, 2025
@kdy1 kdy1 deleted the devbird/implement-duplicate-detection-rules branch October 25, 2025 02:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants