thailint 0.10.0__py3-none-any.whl → 0.12.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. src/__init__.py +1 -0
  2. src/cli/__init__.py +27 -0
  3. src/cli/__main__.py +22 -0
  4. src/cli/config.py +478 -0
  5. src/cli/linters/__init__.py +58 -0
  6. src/cli/linters/code_patterns.py +372 -0
  7. src/cli/linters/code_smells.py +450 -0
  8. src/cli/linters/documentation.py +155 -0
  9. src/cli/linters/shared.py +89 -0
  10. src/cli/linters/structure.py +313 -0
  11. src/cli/linters/structure_quality.py +316 -0
  12. src/cli/main.py +120 -0
  13. src/cli/utils.py +395 -0
  14. src/cli_main.py +34 -0
  15. src/core/types.py +13 -0
  16. src/core/violation_utils.py +69 -0
  17. src/linter_config/ignore.py +32 -16
  18. src/linters/collection_pipeline/linter.py +2 -2
  19. src/linters/dry/block_filter.py +97 -1
  20. src/linters/dry/cache.py +94 -6
  21. src/linters/dry/config.py +47 -10
  22. src/linters/dry/constant.py +92 -0
  23. src/linters/dry/constant_matcher.py +214 -0
  24. src/linters/dry/constant_violation_builder.py +98 -0
  25. src/linters/dry/linter.py +89 -48
  26. src/linters/dry/python_analyzer.py +12 -415
  27. src/linters/dry/python_constant_extractor.py +101 -0
  28. src/linters/dry/single_statement_detector.py +415 -0
  29. src/linters/dry/token_hasher.py +5 -5
  30. src/linters/dry/typescript_analyzer.py +5 -354
  31. src/linters/dry/typescript_constant_extractor.py +134 -0
  32. src/linters/dry/typescript_statement_detector.py +255 -0
  33. src/linters/dry/typescript_value_extractor.py +66 -0
  34. src/linters/file_header/linter.py +2 -2
  35. src/linters/file_placement/linter.py +2 -2
  36. src/linters/file_placement/pattern_matcher.py +19 -5
  37. src/linters/magic_numbers/linter.py +8 -67
  38. src/linters/magic_numbers/typescript_ignore_checker.py +81 -0
  39. src/linters/nesting/linter.py +12 -9
  40. src/linters/print_statements/linter.py +7 -24
  41. src/linters/srp/class_analyzer.py +9 -9
  42. src/linters/srp/heuristics.py +2 -2
  43. src/linters/srp/linter.py +2 -2
  44. src/linters/stateless_class/linter.py +2 -2
  45. src/linters/stringly_typed/__init__.py +36 -0
  46. src/linters/stringly_typed/config.py +190 -0
  47. src/linters/stringly_typed/context_filter.py +451 -0
  48. src/linters/stringly_typed/function_call_violation_builder.py +137 -0
  49. src/linters/stringly_typed/ignore_checker.py +102 -0
  50. src/linters/stringly_typed/ignore_utils.py +51 -0
  51. src/linters/stringly_typed/linter.py +344 -0
  52. src/linters/stringly_typed/python/__init__.py +33 -0
  53. src/linters/stringly_typed/python/analyzer.py +344 -0
  54. src/linters/stringly_typed/python/call_tracker.py +172 -0
  55. src/linters/stringly_typed/python/comparison_tracker.py +252 -0
  56. src/linters/stringly_typed/python/condition_extractor.py +131 -0
  57. src/linters/stringly_typed/python/conditional_detector.py +176 -0
  58. src/linters/stringly_typed/python/constants.py +21 -0
  59. src/linters/stringly_typed/python/match_analyzer.py +88 -0
  60. src/linters/stringly_typed/python/validation_detector.py +186 -0
  61. src/linters/stringly_typed/python/variable_extractor.py +96 -0
  62. src/linters/stringly_typed/storage.py +630 -0
  63. src/linters/stringly_typed/storage_initializer.py +45 -0
  64. src/linters/stringly_typed/typescript/__init__.py +28 -0
  65. src/linters/stringly_typed/typescript/analyzer.py +157 -0
  66. src/linters/stringly_typed/typescript/call_tracker.py +329 -0
  67. src/linters/stringly_typed/typescript/comparison_tracker.py +372 -0
  68. src/linters/stringly_typed/violation_generator.py +376 -0
  69. src/orchestrator/core.py +241 -12
  70. {thailint-0.10.0.dist-info → thailint-0.12.0.dist-info}/METADATA +9 -3
  71. {thailint-0.10.0.dist-info → thailint-0.12.0.dist-info}/RECORD +74 -28
  72. thailint-0.12.0.dist-info/entry_points.txt +4 -0
  73. src/cli.py +0 -2141
  74. thailint-0.10.0.dist-info/entry_points.txt +0 -4
  75. {thailint-0.10.0.dist-info → thailint-0.12.0.dist-info}/WHEEL +0 -0
  76. {thailint-0.10.0.dist-info → thailint-0.12.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,252 @@
1
+ """
2
+ Purpose: Detect scattered string comparisons in Python AST
3
+
4
+ Scope: Find equality/inequality comparisons with string literals across Python files
5
+
6
+ Overview: Provides ComparisonTracker class that traverses Python AST to find scattered
7
+ string comparisons like `if env == "production"`. Tracks the variable name, compared
8
+ string value, and operator to enable cross-file aggregation. When a variable is compared
9
+ to multiple unique string values across files, it suggests the variable should be an enum.
10
+ Excludes common false positives like `__name__ == "__main__"` and type name checks.
11
+
12
+ Dependencies: ast module for AST parsing, dataclasses for pattern structure
13
+
14
+ Exports: ComparisonTracker class, ComparisonPattern dataclass
15
+
16
+ Interfaces: ComparisonTracker.find_patterns(tree) -> list[ComparisonPattern]
17
+
18
+ Implementation: AST NodeVisitor pattern with Compare node handling for string comparisons
19
+ """
20
+
21
+ import ast
22
+ from dataclasses import dataclass
23
+
24
+
25
+ @dataclass
26
+ class ComparisonPattern:
27
+ """Represents a string comparison found in Python code.
28
+
29
+ Captures information about a comparison like `if (env == "production")` to
30
+ enable cross-file analysis for detecting scattered string comparisons that
31
+ suggest missing enums.
32
+ """
33
+
34
+ variable_name: str
35
+ """Variable name being compared (e.g., 'env' or 'self.status')."""
36
+
37
+ compared_value: str
38
+ """The string literal value being compared to."""
39
+
40
+ operator: str
41
+ """The comparison operator ('==' or '!=')."""
42
+
43
+ line_number: int
44
+ """Line number where the comparison occurs (1-indexed)."""
45
+
46
+ column: int
47
+ """Column number where the comparison starts (0-indexed)."""
48
+
49
+
50
+ # Excluded variable names that are common false positives
51
+ _EXCLUDED_VARIABLES = frozenset(
52
+ {
53
+ "__name__",
54
+ "__class__.__name__",
55
+ }
56
+ )
57
+
58
+ # Excluded values that are common in legitimate comparisons
59
+ _EXCLUDED_VALUES = frozenset(
60
+ {
61
+ "__main__",
62
+ }
63
+ )
64
+
65
+
66
+ class ComparisonTracker(ast.NodeVisitor): # thailint: ignore[srp]
67
+ """Tracks scattered string comparisons in Python AST.
68
+
69
+ Finds patterns like `if env == "production"` and `if status != "deleted"` where
70
+ string literals are used for comparisons that could use enums instead.
71
+
72
+ Note: Method count exceeds SRP limit because AST traversal requires multiple helper
73
+ methods for extracting variable names, attribute names, and pattern filtering. All
74
+ methods support the single responsibility of tracking string comparisons.
75
+ """
76
+
77
+ def __init__(self) -> None:
78
+ """Initialize the tracker."""
79
+ self.patterns: list[ComparisonPattern] = []
80
+
81
+ def find_patterns(self, tree: ast.AST) -> list[ComparisonPattern]:
82
+ """Find all string comparisons in the AST.
83
+
84
+ Args:
85
+ tree: The AST to analyze
86
+
87
+ Returns:
88
+ List of ComparisonPattern instances for each detected comparison
89
+ """
90
+ self.patterns = []
91
+ self.visit(tree)
92
+ return self.patterns
93
+
94
+ def visit_Compare(self, node: ast.Compare) -> None: # pylint: disable=invalid-name
95
+ """Visit a Compare node to check for string comparisons.
96
+
97
+ Handles both `var == "string"` and `"string" == var` patterns.
98
+
99
+ Args:
100
+ node: The Compare node to analyze
101
+ """
102
+ self._check_comparison(node)
103
+ self.generic_visit(node)
104
+
105
+ def _check_comparison(self, node: ast.Compare) -> None:
106
+ """Check if comparison is a string comparison to track.
107
+
108
+ Args:
109
+ node: The Compare node to check
110
+ """
111
+ # Only handle simple binary comparisons
112
+ if len(node.ops) != 1 or len(node.comparators) != 1:
113
+ return
114
+
115
+ operator = node.ops[0]
116
+ if not isinstance(operator, (ast.Eq, ast.NotEq)):
117
+ return
118
+
119
+ op_str = "==" if isinstance(operator, ast.Eq) else "!="
120
+ left = node.left
121
+ right = node.comparators[0]
122
+
123
+ # Try both orientations: var == "string" and "string" == var
124
+ self._try_extract_pattern(left, right, op_str, node)
125
+ self._try_extract_pattern(right, left, op_str, node)
126
+
127
+ def _try_extract_pattern(
128
+ self,
129
+ var_side: ast.expr,
130
+ string_side: ast.expr,
131
+ operator: str,
132
+ node: ast.Compare,
133
+ ) -> None:
134
+ """Try to extract a pattern from a comparison.
135
+
136
+ Args:
137
+ var_side: The expression that might be a variable
138
+ string_side: The expression that might be a string literal
139
+ operator: The comparison operator
140
+ node: The original Compare node for location info
141
+ """
142
+ # Check if string_side is a string literal
143
+ if not isinstance(string_side, ast.Constant):
144
+ return
145
+ if not isinstance(string_side.value, str):
146
+ return
147
+
148
+ string_value = string_side.value
149
+
150
+ # Extract variable name
151
+ var_name = self._extract_variable_name(var_side)
152
+ if var_name is None:
153
+ return
154
+
155
+ # Check for excluded patterns
156
+ if self._should_exclude(var_name, string_value):
157
+ return
158
+
159
+ self._add_pattern(var_name, string_value, operator, node)
160
+
161
+ def _extract_variable_name(self, node: ast.expr) -> str | None:
162
+ """Extract variable name from an expression.
163
+
164
+ Handles simple names (var) and attribute access (obj.attr).
165
+
166
+ Args:
167
+ node: The expression to extract from
168
+
169
+ Returns:
170
+ Variable name string or None if not extractable
171
+ """
172
+ if isinstance(node, ast.Name):
173
+ return node.id
174
+ if isinstance(node, ast.Attribute):
175
+ return self._extract_attribute_name(node)
176
+ return None
177
+
178
+ def _extract_attribute_name(self, node: ast.Attribute) -> str | None:
179
+ """Extract attribute name from an attribute access.
180
+
181
+ Builds qualified names like 'obj.attr' or 'a.b.attr'.
182
+
183
+ Args:
184
+ node: The Attribute node
185
+
186
+ Returns:
187
+ Qualified attribute name or None if too complex
188
+ """
189
+ parts: list[str] = [node.attr]
190
+ current = node.value
191
+
192
+ # Limit depth to avoid overly complex names
193
+ max_depth = 3
194
+ depth = 0
195
+
196
+ while depth < max_depth:
197
+ if isinstance(current, ast.Name):
198
+ parts.append(current.id)
199
+ break
200
+ if isinstance(current, ast.Attribute):
201
+ parts.append(current.attr)
202
+ current = current.value
203
+ depth += 1
204
+ else:
205
+ # Complex expression, still return what we have
206
+ parts.append("_")
207
+ break
208
+
209
+ return ".".join(reversed(parts))
210
+
211
+ def _should_exclude(self, var_name: str, string_value: str) -> bool:
212
+ """Check if this comparison should be excluded.
213
+
214
+ Filters out common patterns that are not stringly-typed code:
215
+ - __name__ == "__main__"
216
+ - __class__.__name__ checks
217
+
218
+ Args:
219
+ var_name: The variable name
220
+ string_value: The string value
221
+
222
+ Returns:
223
+ True if the comparison should be excluded
224
+ """
225
+ if var_name in _EXCLUDED_VARIABLES:
226
+ return True
227
+ if string_value in _EXCLUDED_VALUES:
228
+ return True
229
+ # Also exclude if the full qualified name ends with __name__
230
+ if var_name.endswith("__name__"):
231
+ return True
232
+ return False
233
+
234
+ def _add_pattern(
235
+ self, var_name: str, string_value: str, operator: str, node: ast.Compare
236
+ ) -> None:
237
+ """Create and add a comparison pattern to results.
238
+
239
+ Args:
240
+ var_name: The variable name
241
+ string_value: The string value being compared
242
+ operator: The comparison operator
243
+ node: The Compare node for location info
244
+ """
245
+ pattern = ComparisonPattern(
246
+ variable_name=var_name,
247
+ compared_value=string_value,
248
+ operator=operator,
249
+ line_number=node.lineno,
250
+ column=node.col_offset,
251
+ )
252
+ self.patterns.append(pattern)
@@ -0,0 +1,131 @@
1
+ """
2
+ Purpose: Extract string comparisons from Python condition expressions
3
+
4
+ Scope: Parse BoolOp and Compare nodes to extract string equality patterns
5
+
6
+ Overview: Provides functions to extract string comparisons from condition expressions
7
+ in Python AST. Handles simple comparisons, or-combined, and and-combined
8
+ conditions. Updates a collector object with extracted variable names and
9
+ string values. Separated from main detector to reduce complexity.
10
+
11
+ Dependencies: ast module, variable_extractor
12
+
13
+ Exports: extract_from_condition, is_simple_string_equality, get_string_constant
14
+
15
+ Interfaces: Functions for extracting string comparisons from AST nodes
16
+
17
+ Implementation: Recursive traversal of BoolOp nodes with Compare extraction
18
+ """
19
+
20
+ import ast
21
+
22
+ from .variable_extractor import extract_variable_name
23
+
24
+
25
+ def extract_from_condition(
26
+ test: ast.expr,
27
+ collector: object,
28
+ ) -> None:
29
+ """Extract string comparisons from a condition expression.
30
+
31
+ Handles simple comparisons, or-combined, and and-combined comparisons.
32
+
33
+ Args:
34
+ test: The test expression from an if/elif
35
+ collector: Collector to accumulate results into (must have variable_name
36
+ and string_values attributes)
37
+ """
38
+ if isinstance(test, ast.BoolOp):
39
+ _extract_from_bool_op(test, collector)
40
+ elif isinstance(test, ast.Compare):
41
+ _extract_from_compare(test, collector)
42
+
43
+
44
+ def _extract_from_bool_op(node: ast.BoolOp, collector: object) -> None:
45
+ """Extract from BoolOp (And/Or combined comparisons).
46
+
47
+ Args:
48
+ node: BoolOp node
49
+ collector: Collector to accumulate results into
50
+ """
51
+ for value in node.values:
52
+ _handle_bool_op_value(value, collector)
53
+
54
+
55
+ def _handle_bool_op_value(value: ast.expr, collector: object) -> None:
56
+ """Handle a single value from a BoolOp node.
57
+
58
+ Args:
59
+ value: Expression value from BoolOp
60
+ collector: Collector to accumulate results into
61
+ """
62
+ if isinstance(value, ast.Compare):
63
+ _extract_from_compare(value, collector)
64
+ elif isinstance(value, ast.BoolOp):
65
+ _extract_from_bool_op(value, collector)
66
+
67
+
68
+ def _extract_from_compare(node: ast.Compare, collector: object) -> None:
69
+ """Extract string value from a Compare node with Eq/NotEq.
70
+
71
+ Args:
72
+ node: Compare node to analyze
73
+ collector: Collector to accumulate results into
74
+ """
75
+ if not _is_simple_equality(node):
76
+ return
77
+
78
+ string_value = _get_string_constant(node)
79
+ if string_value is None:
80
+ return
81
+
82
+ var_name = extract_variable_name(node.left)
83
+ _update_collector(collector, var_name, string_value)
84
+
85
+
86
+ def _is_simple_equality(node: ast.Compare) -> bool:
87
+ """Check if Compare is a simple equality with one operator.
88
+
89
+ Args:
90
+ node: Compare node to check
91
+
92
+ Returns:
93
+ True if it's a simple x == y or x != y comparison
94
+ """
95
+ if len(node.ops) != 1:
96
+ return False
97
+ return isinstance(node.ops[0], (ast.Eq, ast.NotEq))
98
+
99
+
100
+ def _get_string_constant(node: ast.Compare) -> str | None:
101
+ """Get string constant from the right side of comparison.
102
+
103
+ Args:
104
+ node: Compare node to extract from
105
+
106
+ Returns:
107
+ String value if comparator is a string constant, None otherwise
108
+ """
109
+ comparator = node.comparators[0]
110
+ if isinstance(comparator, ast.Constant) and isinstance(comparator.value, str):
111
+ return comparator.value
112
+ return None
113
+
114
+
115
+ def _update_collector(
116
+ collector: object,
117
+ var_name: str | None,
118
+ string_value: str,
119
+ ) -> None:
120
+ """Update collector with extracted variable and value.
121
+
122
+ Args:
123
+ collector: Collector to update
124
+ var_name: Variable name from comparison
125
+ string_value: String value from comparison
126
+ """
127
+ if collector.variable_name is None: # type: ignore[attr-defined]
128
+ collector.variable_name = var_name # type: ignore[attr-defined]
129
+ # Only add if same variable (or no variable tracking)
130
+ if collector.variable_name == var_name or var_name is None: # type: ignore[attr-defined]
131
+ collector.string_values.add(string_value) # type: ignore[attr-defined]
@@ -0,0 +1,176 @@
1
+ """
2
+ Purpose: Detect equality chain patterns in Python AST
3
+
4
+ Scope: Find 'if x == "a" elif x == "b"', or-combined, and match statement patterns
5
+
6
+ Overview: Provides ConditionalPatternDetector class that traverses Python AST to find
7
+ equality chain patterns where strings are used instead of enums. Detects single
8
+ equality comparisons with string constants, aggregates values from if/elif chains,
9
+ handles or-combined comparisons, and supports Python 3.10+ match statements.
10
+ Returns structured EqualityChainPattern dataclass instances with aggregated
11
+ string values, pattern type, location, and optional variable name.
12
+
13
+ Dependencies: ast module for AST parsing, dataclasses for pattern structure,
14
+ condition_extractor for comparison extraction, match_analyzer for match statements
15
+
16
+ Exports: ConditionalPatternDetector class, EqualityChainPattern dataclass
17
+
18
+ Interfaces: ConditionalPatternDetector.find_patterns(tree) -> list[EqualityChainPattern]
19
+
20
+ Implementation: AST NodeVisitor pattern with If node chain traversal and Match statement handling
21
+ """
22
+
23
+ import ast
24
+ from dataclasses import dataclass, field
25
+ from typing import TYPE_CHECKING
26
+
27
+ from .condition_extractor import extract_from_condition
28
+ from .constants import MIN_VALUES_FOR_PATTERN
29
+ from .match_analyzer import analyze_match_statement
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Iterator
33
+
34
+
35
+ @dataclass
36
+ class EqualityChainPattern:
37
+ """Represents a detected equality chain pattern.
38
+
39
+ Captures information about stringly-typed equality checks including aggregated
40
+ string values from chains, pattern type, source location, and variable name.
41
+ """
42
+
43
+ string_values: set[str]
44
+ """Set of string values aggregated from the equality chain."""
45
+
46
+ pattern_type: str
47
+ """Type of pattern: 'equality_chain', 'or_combined', or 'match_statement'."""
48
+
49
+ line_number: int
50
+ """Line number where the pattern starts (1-indexed)."""
51
+
52
+ column: int
53
+ """Column number where the pattern starts (0-indexed)."""
54
+
55
+ variable_name: str | None
56
+ """Variable name being compared, if identifiable from a simple expression."""
57
+
58
+
59
+ @dataclass
60
+ class _ChainCollector:
61
+ """Internal collector for aggregating values from if/elif chains."""
62
+
63
+ variable_name: str | None = None
64
+ string_values: set[str] = field(default_factory=set)
65
+ line_number: int = 0
66
+ column: int = 0
67
+
68
+
69
+ class ConditionalPatternDetector(ast.NodeVisitor):
70
+ """Detects equality chain patterns in Python AST.
71
+
72
+ Finds patterns like 'if x == "a" elif x == "b"', or-combined comparisons,
73
+ and match statements where strings are used instead of proper enums.
74
+ """
75
+
76
+ def __init__(self) -> None:
77
+ """Initialize the detector."""
78
+ self.patterns: list[EqualityChainPattern] = []
79
+ self._processed_if_nodes: set[int] = set()
80
+
81
+ def find_patterns(self, tree: ast.AST) -> list[EqualityChainPattern]:
82
+ """Find all equality chain patterns in the AST.
83
+
84
+ Args:
85
+ tree: The AST to analyze
86
+
87
+ Returns:
88
+ List of EqualityChainPattern instances for each detected pattern
89
+ """
90
+ self.patterns = []
91
+ self._processed_if_nodes = set()
92
+ self.visit(tree)
93
+ return self.patterns
94
+
95
+ def visit_If(self, node: ast.If) -> None: # pylint: disable=invalid-name
96
+ """Visit an If node to check for equality chain patterns.
97
+
98
+ Args:
99
+ node: The If node to analyze
100
+ """
101
+ if id(node) not in self._processed_if_nodes:
102
+ self._analyze_if_chain(node)
103
+ self.generic_visit(node)
104
+
105
+ def visit_Match(self, node: ast.Match) -> None: # pylint: disable=invalid-name
106
+ """Visit a Match node to check for string case patterns.
107
+
108
+ Args:
109
+ node: The Match node to analyze
110
+ """
111
+ pattern = analyze_match_statement(node, EqualityChainPattern)
112
+ if pattern is not None:
113
+ self.patterns.append(pattern) # type: ignore[arg-type]
114
+ self.generic_visit(node)
115
+
116
+ def _analyze_if_chain(self, node: ast.If) -> None:
117
+ """Analyze an if/elif chain for equality patterns.
118
+
119
+ Args:
120
+ node: The starting If node of the chain
121
+ """
122
+ collector = _ChainCollector(line_number=node.lineno, column=node.col_offset)
123
+
124
+ for if_node in self._iter_if_chain(node):
125
+ self._processed_if_nodes.add(id(if_node))
126
+ extract_from_condition(if_node.test, collector)
127
+
128
+ self._emit_pattern_if_valid(collector)
129
+
130
+ def _iter_if_chain(self, node: ast.If) -> "Iterator[ast.If]":
131
+ """Iterate through an if/elif chain.
132
+
133
+ Args:
134
+ node: Starting If node
135
+
136
+ Yields:
137
+ Each If node in the chain including elif branches
138
+ """
139
+ yield node
140
+ current: ast.If | None = node
141
+
142
+ while current is not None:
143
+ current = self._get_next_elif(current)
144
+ if current is not None:
145
+ yield current
146
+
147
+ def _get_next_elif(self, node: ast.If) -> ast.If | None:
148
+ """Get the next elif node in a chain.
149
+
150
+ Args:
151
+ node: Current If node
152
+
153
+ Returns:
154
+ Next elif If node, or None if no elif exists
155
+ """
156
+ if len(node.orelse) == 1 and isinstance(node.orelse[0], ast.If):
157
+ return node.orelse[0]
158
+ return None
159
+
160
+ def _emit_pattern_if_valid(self, collector: _ChainCollector) -> None:
161
+ """Emit a pattern if collector has sufficient values.
162
+
163
+ Args:
164
+ collector: Collector with aggregated values
165
+ """
166
+ if len(collector.string_values) < MIN_VALUES_FOR_PATTERN:
167
+ return
168
+
169
+ pattern = EqualityChainPattern(
170
+ string_values=collector.string_values,
171
+ pattern_type="equality_chain",
172
+ line_number=collector.line_number,
173
+ column=collector.column,
174
+ variable_name=collector.variable_name,
175
+ )
176
+ self.patterns.append(pattern)
@@ -0,0 +1,21 @@
1
+ """
2
+ Purpose: Shared constants for stringly-typed Python detection
3
+
4
+ Scope: Common configuration values used across Python pattern detectors
5
+
6
+ Overview: Provides shared constants used by MembershipValidationDetector,
7
+ ConditionalPatternDetector, and other Python detection components.
8
+ Centralizes configuration values to ensure consistency and avoid
9
+ duplication across detector implementations.
10
+
11
+ Dependencies: None
12
+
13
+ Exports: MIN_VALUES_FOR_PATTERN constant
14
+
15
+ Interfaces: Constants only, no function interfaces
16
+
17
+ Implementation: Simple module-level constant definitions
18
+ """
19
+
20
+ # Minimum number of string values to consider as enum candidate
21
+ MIN_VALUES_FOR_PATTERN = 2
@@ -0,0 +1,88 @@
1
+ """
2
+ Purpose: Analyze Python match statements for stringly-typed patterns
3
+
4
+ Scope: Extract string values from match statement cases
5
+
6
+ Overview: Provides MatchStatementAnalyzer class that analyzes Python 3.10+ match
7
+ statements to detect stringly-typed patterns. Extracts string values from
8
+ case patterns and returns structured results. Separated from main detector
9
+ to maintain single responsibility and reduce class complexity.
10
+
11
+ Dependencies: ast module, constants module, variable_extractor
12
+
13
+ Exports: MatchStatementAnalyzer class
14
+
15
+ Interfaces: MatchStatementAnalyzer.analyze(node) -> EqualityChainPattern | None
16
+
17
+ Implementation: AST pattern matching for MatchValue nodes with string constants
18
+ """
19
+
20
+ import ast
21
+
22
+ from .constants import MIN_VALUES_FOR_PATTERN
23
+ from .variable_extractor import extract_variable_name
24
+
25
+
26
+ def analyze_match_statement(
27
+ node: ast.Match,
28
+ pattern_class: type,
29
+ ) -> object | None:
30
+ """Analyze a match statement for string case patterns.
31
+
32
+ Args:
33
+ node: Match statement node to analyze
34
+ pattern_class: The EqualityChainPattern class to use for results
35
+
36
+ Returns:
37
+ Pattern instance if valid match found, None otherwise
38
+ """
39
+ string_values = _collect_string_cases(node.cases)
40
+
41
+ if len(string_values) < MIN_VALUES_FOR_PATTERN:
42
+ return None
43
+
44
+ var_name = extract_variable_name(node.subject)
45
+ return pattern_class(
46
+ string_values=string_values,
47
+ pattern_type="match_statement",
48
+ line_number=node.lineno,
49
+ column=node.col_offset,
50
+ variable_name=var_name,
51
+ )
52
+
53
+
54
+ def _collect_string_cases(cases: list[ast.match_case]) -> set[str]:
55
+ """Collect string values from match cases.
56
+
57
+ Args:
58
+ cases: List of match_case nodes
59
+
60
+ Returns:
61
+ Set of string values from MatchValue patterns
62
+ """
63
+ string_values: set[str] = set()
64
+
65
+ for case in cases:
66
+ value = _extract_case_string_value(case.pattern)
67
+ if value is not None:
68
+ string_values.add(value)
69
+
70
+ return string_values
71
+
72
+
73
+ def _extract_case_string_value(pattern: ast.pattern) -> str | None:
74
+ """Extract string value from a case pattern.
75
+
76
+ Args:
77
+ pattern: Match case pattern node
78
+
79
+ Returns:
80
+ String value if pattern is a MatchValue with string, None otherwise
81
+ """
82
+ if not isinstance(pattern, ast.MatchValue):
83
+ return None
84
+ if not isinstance(pattern.value, ast.Constant):
85
+ return None
86
+ if not isinstance(pattern.value.value, str):
87
+ return None
88
+ return pattern.value.value