-
-
Notifications
You must be signed in to change notification settings - Fork 0
Enable test for class-methods-use-this rule #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
## Summary - Uncommented the test file for the `class-methods-use-this` rule in `rstest.config.mts` to enable testing - Implemented the class-methods-use-this rule in Go - Registered the rule in the configuration ## Context This PR is a follow-up to #151 which enabled the `ban-tslint-comment` rule. This PR enables the `class-methods-use-this` rule which detects class methods that don't use `this` and could be made static. ## Changes 1. **Test Configuration** (rstest.config.mts:37) - Uncommented the line enabling the class-methods-use-this-core test file 2. **Implementation** (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) - Created new Go implementation for the class-methods-use-this rule - Detects class methods, getters, setters, and class fields that don't use `this` or `super` - Supports options: - `exceptMethods`: array of method names to ignore - `enforceForClassFields`: boolean to control checking of class fields (default: true) - Properly handles: - Instance methods, getters, setters - Private methods (with # prefix) - Generator methods - Arrow functions and function expressions in class fields - Nested functions and arrow functions (correctly scoping `this`) - Skips constructors, static methods, and abstract methods 3. **Registration** (internal/config/config.go) - Added import for the class_methods_use_this package - Registered the rule as `@typescript-eslint/class-methods-use-this` ## Implementation Details The rule implementation: - Traverses class members (methods, getters, setters, properties) - Checks if each member's body uses `this` or `super` keywords - Handles nested function scoping correctly (doesn't look inside nested function expressions, but does check arrow functions as they capture `this`) - Respects exception list for method names - Reports errors with messageId 'missingThis' and appropriate description ## Test Plan - [ ] Run `npm test` to verify all tests pass - [ ] Check CI pipeline for any failures - [ ] Fix any implementation issues if tests fail in CI ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Code Review: Enable test for class-methods-use-this ruleSummaryThis PR implements the Critical Issues1. Incorrect AST Traversal Logic (Bug)Location: The // Don't descend into nested function expressions or arrow functions
// unless they're arrow functions (which capture 'this')
if child.Kind == ast.KindFunctionExpression || child.Kind == ast.KindFunctionDeclaration {
functionDepth++
if functionDepth > 0 {
return false // Don't descend
}
}Problem: The if child.Kind == ast.KindFunctionExpression || child.Kind == ast.KindFunctionDeclaration {
return false // Don't descend into nested functions
}The 2. Arrow Function Traversal Logic IssueLocation: The current implementation calls if child.Kind == ast.KindArrowFunction {
// Check if the arrow function uses 'this'
if containsThisInArrow(child) {
found = true
return false
}
return true // Continue checking
}Problem: After calling if child.Kind == ast.KindArrowFunction {
if containsThisInArrow(child) {
found = true
}
return false // Don't descend, we already checked it
}3. Incomplete Handling of Arrow Function BodiesLocation: When checking property declarations with arrow functions, the code only handles block bodies: if init.Kind == ast.KindArrowFunction {
fn := init.AsArrowFunction()
if fn != nil && fn.Body != nil && fn.Body.Kind == ast.KindBlock {
body = fn.Body
}
}Problem: Arrow functions can have expression bodies (e.g., if init.Kind == ast.KindArrowFunction {
fn := init.AsArrowFunction()
if fn != nil && fn.Body != nil {
body = fn.Body
}
}Code Quality & Best Practices4. Inconsistent Return Type from GetNameFromMemberLocation: The name, isPrivate := utils.GetNameFromMember(ctx.SourceFile, method.Name())
if isPrivate {
// ... handle private
}Issue: The variable is named Suggestion: Use a more descriptive variable name: name, nameType := utils.GetNameFromMember(ctx.SourceFile, method.Name())
if nameType == utils.MemberNameTypePrivate {
// ... handle private
}5. Repetitive Method Name Extraction LogicLocation: The logic for getting method names and building display names is duplicated across multiple sections of the code. Suggestion: Extract into helper functions at the package level to improve maintainability: func getMethodNameFromNode(ctx rule.RuleContext, node *ast.Node) string {
// Consolidate the name extraction logic
}Performance Considerations6. Inefficient String ConcatenationLocation: Multiple locations in The function builds strings using concatenation in multiple places: return "private getter " + name
return "getter '" + name + "'"Impact: For this use case (small strings, infrequent calls), the performance impact is negligible. However, for consistency with Go best practices, consider using return fmt.Sprintf("private getter %s", name)
return fmt.Sprintf("getter '%s'", name)7. Traversal EfficiencyThe The current implementation does return Security ConcernsNo significant security issues identified. The rule implementation:
Test Coverage8. Test File EnabledThe PR correctly enables the test file in './tests/typescript-eslint/rules/class-methods-use-this/class-methods-use-this-core.test.ts',Good: The test file includes comprehensive test cases covering:
9. Missing TypeScript-Specific TestsLocation: The file Question: Are there TypeScript-specific test cases in the commented test file that should also be enabled? The PR description doesn't explain why only the core tests are enabled. Additional Observations10. Good Practices Followed✅ Proper option parsing with defaults 11. DocumentationThe PR description is excellent and provides:
Suggestion: Consider adding code comments explaining the nuanced behavior around nested functions vs arrow functions, as this is a subtle aspect of JavaScript's RecommendationsHigh Priority (Must Fix)
Medium Priority (Should Fix)
Low Priority (Nice to Have)
Test Plan VerificationBefore merging:
Great work on this implementation! The overall structure is solid and follows the repository patterns well. Once the critical bugs are fixed, this should work correctly. Let me know if you need clarification on any of the feedback. |
- Change GetNameFromMember return type handling from bool to MemberNameType - Use proper comparison with utils.MemberNameTypePrivate constant
|
🤖 This pull request has been linked to DevBird Task #1534 View the task details and manage the automated development workflow in DevBird. Learn more about DevBird here or the announcement blog post here. |
📋 DevBird Task PromptEnable the test for the ObjectiveUncomment the test file Documentation & Resources
Implementation Steps
Critical RequirementIf CI fails, implement the class-methods-use-this rule from scratch:
Success Criteria
This comment was automatically added by DevBird. You can disable this feature in DevBird Settings. |
Pull Request Review: class-methods-use-this Rule ImplementationOverall AssessmentThis PR implements the Code Quality & Best PracticesStrengths ✅
Areas for Improvement 🔧1. Potential Logic Issue with Arrow Functions in Class Fields (class_methods_use_this.go:352)// Arrow function listener (exits property initializer if needed)
rule.ListenerOnExit(ast.KindArrowFunction): exitPropertyInit,Issue: This listener calls Expected behavior:
Suggested fix: Add a check in exitPropertyInit := func(node *ast.Node) {
if currentScope != nil && currentScope.node == node {
// Only exit if this arrow function is a direct initializer
parent := node.Parent
if parent != nil && parent.Kind == ast.KindPropertyDeclaration {
// ... existing code ...
}
currentScope = currentScope.upper
}
}2. Missing Listener for FunctionExpression Exit in Property Initializers (class_methods_use_this.go:346-347)The code has entry listeners for function expressions in properties (
Issue: Function expressions as property initializers should use Test case to verify: Line 227-237 in test file expects error for 3. Redundant isInClass Check (class_methods_use_this.go:176-178)The 4. Variable Shadowing in Options Parsing (class_methods_use_this.go:32)if opts, ok := optsArray[0].(map[string]interface{}); ok {
optsMap = opts // 'opts' shadows the outer 'opts' variable
}While this works, it's a subtle naming issue that could be clearer: if optsData, ok := optsArray[0].(map[string]interface{}); ok {
optsMap = optsData
}Potential Bugs 🐛Critical Issues1. Arrow Functions in Class Fields May Not Be Properly Handled Scenario that might fail: class A {
foo() {
const callback = () => this; // This 'this' should mark foo() as using 'this'
return callback();
}
}Expected: No error (method uses 2. Nested Function Scope Handling Scenario: class A {
foo() {
const arrow = () => this; // Should mark foo() as using 'this'
}
}The code correctly doesn't create a boundary for arrow functions (line 316 only checks for Performance Considerations ⚡Current PerformanceThe implementation is efficient:
Minor Optimizations
exceptMethodsMap := make(map[string]bool)
for _, method := range opts.ExceptMethods {
exceptMethodsMap[method] = true
}
isExceptedMethod := func(methodName string) bool {
return exceptMethodsMap[methodName]
}This matters if
Security Concerns 🔒No security issues identified. ✅ The implementation:
Test Coverage 🧪Test File AnalysisThe test file ( Valid cases (15 tests): ✅
Invalid cases (31 tests): ✅
Edge Cases Well Covered
RecommendationThe test coverage appears excellent. When the PR runs CI, monitor for:
Recommendations SummaryHigh Priority 🔴
Medium Priority 🟡
Low Priority 🟢
ConclusionThis is a solid implementation with good test coverage. The main concerns are around the arrow function exit listener which could cause scope tracking issues. I recommend:
The implementation demonstrates good understanding of the TypeScript-ESLint rule and Go patterns. With the suggested fixes, this will be a robust addition to the codebase. Great work! 🎉 |
…ut 'this' The rule was not correctly detecting class methods that don't use 'this'. The issue was that property initializers (function/arrow expressions) were being handled incorrectly - they were creating nested function scopes that marked hasThis=true, preventing errors from being reported. Changes: - Refactored enterProperty to enterPropertyInit that processes function/arrow expressions that are property initializers - Updated enterNestedFunction to skip property initializers (handled separately) - Updated exitNestedFunction to skip property initializers - Modified listeners to call both enterPropertyInit and enterNestedFunction for function expressions, ensuring proper scope handling This ensures that: 1. Regular methods are checked for 'this' usage 2. Property initializers with functions/arrows are checked separately 3. Nested functions inside methods create proper boundaries 4. Arrow functions in properties inherit parent scope correctly 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Code Review: Enable test for class-methods-use-this ruleThank you for implementing the Strengths
Issues to Address1. Potential bug with arrow function scope handling (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go:367-371)Arrow functions don't create their own ast.KindArrowFunction: func(node *ast.Node) {
enterPropertyInit(node)
},When an arrow function appears inside a method body (not as a property initializer), it should NOT create a scope boundary because it lexically captures // Arrow functions lexically capture 'this' from enclosing scope,
// so we don't create a boundary for nested arrows (only property initializers)
ast.KindArrowFunction: func(node *ast.Node) {
enterPropertyInit(node)
},2. Redundant method.Kind checks (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go:82-88, 92-107)In if node.Kind == ast.KindMethodDeclaration {
method := node.AsMethodDeclaration()
if method != nil && method.Name() != nil {
name, nameType := utils.GetNameFromMember(ctx.SourceFile, method.Name())
if nameType == utils.MemberNameTypePrivate {
// Remove these incorrect checks:
// if method.Kind == ast.KindGetAccessor { ... }
// if method.Kind == ast.KindSetAccessor { ... }
if method.AsteriskToken != nil {
return "private generator method " + name
}
return "private method " + name
}
// Similar cleanup for non-private branch
}
}3. Options field naming inconsistencyThe struct field is EnforceForClassFields bool `json:"enforceForClassFields"`While this works, check if other rules in the codebase use camelCase or PascalCase for JSON tags. Looking at 4. Missing documentation commentsFollowing Go best practices, exported types and variables should have documentation comments: // ClassMethodsUseThisOptions configures the class-methods-use-this rule
type ClassMethodsUseThisOptions struct {
// ExceptMethods is a list of method names that are exempt from the rule
ExceptMethods []string `json:"exceptMethods"`
// EnforceForClassFields determines whether to check class field initializers
EnforceForClassFields bool `json:"enforceForClassFields"`
}
// ClassMethodsUseThisRule enforces that class methods utilize 'this' or 'super'
var ClassMethodsUseThisRule = rule.CreateRule(...)Performance Considerations
exceptedMethods := make(map[string]bool)
for _, method := range opts.ExceptMethods {
exceptedMethods[method] = true
}
isExceptedMethod := func(methodName string) bool {
return exceptedMethods[methodName]
}This changes O(n) lookup to O(1). However, for typical usage with 1-5 excepted methods, the current approach is fine.
Security ConsiderationsNo security concerns identified. The implementation:
Test CoverageThe PR enables the test file
Additional Suggestions
SummaryThis is a solid implementation with good structure and comprehensive handling of edge cases. The main issues are:
The implementation correctly handles the complex scoping rules for Recommendation: Address the issues mentioned above, particularly the redundant method.Kind checks, before merging. |
## Summary
- Uncommented the full test file for class-methods-use-this rule in rstest.config.mts
- Extended implementation to support `ignoreClassesThatImplementAnInterface` option (boolean or "public-fields")
- Extended implementation to support `ignoreOverrideMethods` option
- All tests now pass successfully
## Changes
### Test Configuration (rstest.config.mts:38)
- Uncommented the line enabling the class-methods-use-this full test file
### Implementation (class_methods_use_this.go)
Extended the rule to support advanced TypeScript-ESLint options:
1. **ignoreClassesThatImplementAnInterface**:
- When `true`: ignores all members of classes that implement interfaces
- When `"public-fields"`: only ignores public members, still checks private/protected members
- When `false`: checks all members (default behavior)
2. **ignoreOverrideMethods**:
- When `true`: ignores methods with the `override` modifier
- When `false`: checks override methods (default behavior)
3. **Implementation details**:
- Added helper functions to check if a class implements an interface
- Added helper to check if a member has the override modifier
- Added logic to determine whether to ignore members based on:
- Class interface implementation status
- Member visibility (public/private/protected)
- Override modifier presence
- Applied these checks to both methods and property initializers
### Test Snapshots
- Created snapshot file with 40 test cases covering:
- Basic method detection
- Private/protected methods
- Getter/setter detection
- Classes implementing interfaces
- Override methods
- Property initializers
- Combination of options
## Context
This PR is a follow-up to #152 and #153, which enabled the core test. This PR enables the full test suite with advanced TypeScript-specific features.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
## Summary - Uncommented the full test file for class-methods-use-this rule in `rstest.config.mts` - Extended implementation to support `ignoreClassesThatImplementAnInterface` option (boolean or "public-fields") - Extended implementation to support `ignoreOverrideMethods` option - All tests now pass successfully ## Context This PR is a follow-up to #152 and #153, which enabled the core test. This PR enables the full test suite with advanced TypeScript-specific features. ## Changes ### Test Configuration (rstest.config.mts:38) - Uncommented the line enabling the class-methods-use-this full test file ### Implementation (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) Extended the rule to support advanced TypeScript-ESLint options: 1. **ignoreClassesThatImplementAnInterface**: - When `true`: ignores all members of classes that implement interfaces - When `"public-fields"`: only ignores public members, still checks private/protected members - When `false`: checks all members (default behavior) 2. **ignoreOverrideMethods**: - When `true`: ignores methods with the `override` modifier - When `false`: checks override methods (default behavior) 3. **Implementation details**: - Added helper functions to check if a class implements an interface - Added helper to check if a member has the override modifier - Added logic to determine whether to ignore members based on: - Class interface implementation status - Member visibility (public/private/protected) - Override modifier presence - Applied these checks to both methods and property initializers ### Test Snapshots - Created snapshot file with 40 test cases covering: - Basic method detection - Private/protected methods - Getter/setter detection - Classes implementing interfaces - Override methods - Property initializers - Combination of options ## Test Results All tests pass successfully: - Valid test cases: ✓ (3.53s) - Invalid test cases: ✓ (4.06s) - Total: 2 passed ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the test file for the `class-methods-use-this` rule in `rstest.config.mts` to enable testing - Implemented the class-methods-use-this rule in Go - Registered the rule in the configuration ## Context This PR is a follow-up to #151 which enabled the `ban-tslint-comment` rule. This PR enables the `class-methods-use-this` rule which detects class methods that don't use `this` and could be made static. ## Changes 1. **Test Configuration** (rstest.config.mts:37) - Uncommented the line enabling the class-methods-use-this-core test file 2. **Implementation** (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) - Created new Go implementation for the class-methods-use-this rule - Detects class methods, getters, setters, and class fields that don't use `this` or `super` - Supports options: - `exceptMethods`: array of method names to ignore - `enforceForClassFields`: boolean to control checking of class fields (default: true) - Properly handles: - Instance methods, getters, setters - Private methods (with # prefix) - Generator methods - Arrow functions and function expressions in class fields - Nested functions and arrow functions (correctly scoping `this`) - Skips constructors, static methods, and abstract methods 3. **Registration** (internal/config/config.go) - Added import for the class_methods_use_this package - Registered the rule as `@typescript-eslint/class-methods-use-this` ## Implementation Details The rule implementation: - Traverses class members (methods, getters, setters, properties) - Checks if each member's body uses `this` or `super` keywords - Handles nested function scoping correctly (doesn't look inside nested function expressions, but does check arrow functions as they capture `this`) - Respects exception list for method names - Reports errors with messageId 'missingThis' and appropriate description ## Test Plan - [ ] Run `npm test` to verify all tests pass - [ ] Check CI pipeline for any failures - [ ] Fix any implementation issues if tests fail in CI ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the full test file for class-methods-use-this rule in `rstest.config.mts` - Extended implementation to support `ignoreClassesThatImplementAnInterface` option (boolean or "public-fields") - Extended implementation to support `ignoreOverrideMethods` option - All tests now pass successfully ## Context This PR is a follow-up to #152 and #153, which enabled the core test. This PR enables the full test suite with advanced TypeScript-specific features. ## Changes ### Test Configuration (rstest.config.mts:38) - Uncommented the line enabling the class-methods-use-this full test file ### Implementation (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) Extended the rule to support advanced TypeScript-ESLint options: 1. **ignoreClassesThatImplementAnInterface**: - When `true`: ignores all members of classes that implement interfaces - When `"public-fields"`: only ignores public members, still checks private/protected members - When `false`: checks all members (default behavior) 2. **ignoreOverrideMethods**: - When `true`: ignores methods with the `override` modifier - When `false`: checks override methods (default behavior) 3. **Implementation details**: - Added helper functions to check if a class implements an interface - Added helper to check if a member has the override modifier - Added logic to determine whether to ignore members based on: - Class interface implementation status - Member visibility (public/private/protected) - Override modifier presence - Applied these checks to both methods and property initializers ### Test Snapshots - Created snapshot file with 40 test cases covering: - Basic method detection - Private/protected methods - Getter/setter detection - Classes implementing interfaces - Override methods - Property initializers - Combination of options ## Test Results All tests pass successfully: - Valid test cases: ✓ (3.53s) - Invalid test cases: ✓ (4.06s) - Total: 2 passed ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the test file for the `class-methods-use-this` rule in `rstest.config.mts` to enable testing - Implemented the class-methods-use-this rule in Go - Registered the rule in the configuration ## Context This PR is a follow-up to #151 which enabled the `ban-tslint-comment` rule. This PR enables the `class-methods-use-this` rule which detects class methods that don't use `this` and could be made static. ## Changes 1. **Test Configuration** (rstest.config.mts:37) - Uncommented the line enabling the class-methods-use-this-core test file 2. **Implementation** (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) - Created new Go implementation for the class-methods-use-this rule - Detects class methods, getters, setters, and class fields that don't use `this` or `super` - Supports options: - `exceptMethods`: array of method names to ignore - `enforceForClassFields`: boolean to control checking of class fields (default: true) - Properly handles: - Instance methods, getters, setters - Private methods (with # prefix) - Generator methods - Arrow functions and function expressions in class fields - Nested functions and arrow functions (correctly scoping `this`) - Skips constructors, static methods, and abstract methods 3. **Registration** (internal/config/config.go) - Added import for the class_methods_use_this package - Registered the rule as `@typescript-eslint/class-methods-use-this` ## Implementation Details The rule implementation: - Traverses class members (methods, getters, setters, properties) - Checks if each member's body uses `this` or `super` keywords - Handles nested function scoping correctly (doesn't look inside nested function expressions, but does check arrow functions as they capture `this`) - Respects exception list for method names - Reports errors with messageId 'missingThis' and appropriate description ## Test Plan - [ ] Run `npm test` to verify all tests pass - [ ] Check CI pipeline for any failures - [ ] Fix any implementation issues if tests fail in CI ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the full test file for class-methods-use-this rule in `rstest.config.mts` - Extended implementation to support `ignoreClassesThatImplementAnInterface` option (boolean or "public-fields") - Extended implementation to support `ignoreOverrideMethods` option - All tests now pass successfully ## Context This PR is a follow-up to #152 and #153, which enabled the core test. This PR enables the full test suite with advanced TypeScript-specific features. ## Changes ### Test Configuration (rstest.config.mts:38) - Uncommented the line enabling the class-methods-use-this full test file ### Implementation (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) Extended the rule to support advanced TypeScript-ESLint options: 1. **ignoreClassesThatImplementAnInterface**: - When `true`: ignores all members of classes that implement interfaces - When `"public-fields"`: only ignores public members, still checks private/protected members - When `false`: checks all members (default behavior) 2. **ignoreOverrideMethods**: - When `true`: ignores methods with the `override` modifier - When `false`: checks override methods (default behavior) 3. **Implementation details**: - Added helper functions to check if a class implements an interface - Added helper to check if a member has the override modifier - Added logic to determine whether to ignore members based on: - Class interface implementation status - Member visibility (public/private/protected) - Override modifier presence - Applied these checks to both methods and property initializers ### Test Snapshots - Created snapshot file with 40 test cases covering: - Basic method detection - Private/protected methods - Getter/setter detection - Classes implementing interfaces - Override methods - Property initializers - Combination of options ## Test Results All tests pass successfully: - Valid test cases: ✓ (3.53s) - Invalid test cases: ✓ (4.06s) - Total: 2 passed ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the test file for the `class-methods-use-this` rule in `rstest.config.mts` to enable testing - Implemented the class-methods-use-this rule in Go - Registered the rule in the configuration ## Context This PR is a follow-up to #151 which enabled the `ban-tslint-comment` rule. This PR enables the `class-methods-use-this` rule which detects class methods that don't use `this` and could be made static. ## Changes 1. **Test Configuration** (rstest.config.mts:37) - Uncommented the line enabling the class-methods-use-this-core test file 2. **Implementation** (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) - Created new Go implementation for the class-methods-use-this rule - Detects class methods, getters, setters, and class fields that don't use `this` or `super` - Supports options: - `exceptMethods`: array of method names to ignore - `enforceForClassFields`: boolean to control checking of class fields (default: true) - Properly handles: - Instance methods, getters, setters - Private methods (with # prefix) - Generator methods - Arrow functions and function expressions in class fields - Nested functions and arrow functions (correctly scoping `this`) - Skips constructors, static methods, and abstract methods 3. **Registration** (internal/config/config.go) - Added import for the class_methods_use_this package - Registered the rule as `@typescript-eslint/class-methods-use-this` ## Implementation Details The rule implementation: - Traverses class members (methods, getters, setters, properties) - Checks if each member's body uses `this` or `super` keywords - Handles nested function scoping correctly (doesn't look inside nested function expressions, but does check arrow functions as they capture `this`) - Respects exception list for method names - Reports errors with messageId 'missingThis' and appropriate description ## Test Plan - [ ] Run `npm test` to verify all tests pass - [ ] Check CI pipeline for any failures - [ ] Fix any implementation issues if tests fail in CI ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
## Summary - Uncommented the full test file for class-methods-use-this rule in `rstest.config.mts` - Extended implementation to support `ignoreClassesThatImplementAnInterface` option (boolean or "public-fields") - Extended implementation to support `ignoreOverrideMethods` option - All tests now pass successfully ## Context This PR is a follow-up to #152 and #153, which enabled the core test. This PR enables the full test suite with advanced TypeScript-specific features. ## Changes ### Test Configuration (rstest.config.mts:38) - Uncommented the line enabling the class-methods-use-this full test file ### Implementation (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go) Extended the rule to support advanced TypeScript-ESLint options: 1. **ignoreClassesThatImplementAnInterface**: - When `true`: ignores all members of classes that implement interfaces - When `"public-fields"`: only ignores public members, still checks private/protected members - When `false`: checks all members (default behavior) 2. **ignoreOverrideMethods**: - When `true`: ignores methods with the `override` modifier - When `false`: checks override methods (default behavior) 3. **Implementation details**: - Added helper functions to check if a class implements an interface - Added helper to check if a member has the override modifier - Added logic to determine whether to ignore members based on: - Class interface implementation status - Member visibility (public/private/protected) - Override modifier presence - Applied these checks to both methods and property initializers ### Test Snapshots - Created snapshot file with 40 test cases covering: - Basic method detection - Private/protected methods - Getter/setter detection - Classes implementing interfaces - Override methods - Property initializers - Combination of options ## Test Results All tests pass successfully: - Valid test cases: ✓ (3.53s) - Invalid test cases: ✓ (4.06s) - Total: 2 passed ## TypeScript-ESLint Reference The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule: https://typescript-eslint.io/rules/class-methods-use-this/ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: claude[bot] <41898282+claude[bot]@users.noreply.github.com> Co-authored-by: Claude <noreply@anthropic.com>
Summary
class-methods-use-thisrule inrstest.config.mtsto enable testingContext
This PR is a follow-up to #151 which enabled the
ban-tslint-commentrule. This PR enables theclass-methods-use-thisrule which detects class methods that don't usethisand could be made static.Changes
Test Configuration (rstest.config.mts:37)
Implementation (internal/plugins/typescript/rules/class_methods_use_this/class_methods_use_this.go)
thisorsuperexceptMethods: array of method names to ignoreenforceForClassFields: boolean to control checking of class fields (default: true)this)Registration (internal/config/config.go)
@typescript-eslint/class-methods-use-thisImplementation Details
The rule implementation:
thisorsuperkeywordsthis)Test Plan
npm testto verify all tests passTypeScript-ESLint Reference
The implementation follows the behavior of the TypeScript-ESLint class-methods-use-this rule:
https://typescript-eslint.io/rules/class-methods-use-this/
🤖 Generated with Claude Code