Skip to content

Commit e31690f

Browse files
committed
fix(lint): resolve static values only from effectively-const variables
1 parent 312ffc5 commit e31690f

13 files changed

Lines changed: 346 additions & 46 deletions

File tree

‎crates/tsrs_lint/src/rules/prefer_includes.rs‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ use tsrs_core::P;
44

55
use crate::protocol::{Fix, Range, RuleMessage, Suggestion};
66
use crate::rule::{Listener, Rule, RuleContext, trim_node_range};
7-
use crate::utils::{get_constrained_type_at_location, get_type_name, quote_single_string_literal};
7+
use crate::utils::{
8+
get_constant_variable_initializer, get_constrained_type_at_location, get_type_name,
9+
quote_single_string_literal,
10+
};
811

912
pub struct PreferIncludes;
1013

@@ -156,18 +159,7 @@ fn extract_reg_exp_constructor_pattern(node: P<Node>) -> &'static str {
156159
}
157160

158161
fn resolve_variable_pattern(checker: &mut Checker, node: P<Node>) -> &'static str {
159-
if !ast::is_identifier(node) {
160-
return "";
161-
}
162-
let Some(declaration) =
163-
checker.get_symbol_at_location_exported(node).and_then(|symbol| symbol.value_declaration())
164-
else {
165-
return "";
166-
};
167-
if declaration.kind() != Kind::VariableDeclaration {
168-
return "";
169-
}
170-
let Some(initializer) = declaration.initializer() else {
162+
let Some(initializer) = get_constant_variable_initializer(checker, node) else {
171163
return "";
172164
};
173165
let pattern = extract_regex_literal_pattern(initializer);

‎crates/tsrs_lint/src/rules/prefer_regexp_exec.rs‎

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
use rustc_hash::FxHashSet;
2-
use tsrs_ast::{self as ast, Kind, Node, NodeFlags, Symbol};
2+
use tsrs_ast::{self as ast, Kind, Node, Symbol};
33
use tsrs_checker::{Checker, Type};
44
use tsrs_core::P;
55

66
use crate::protocol::{Fix, RuleMessage};
77
use crate::rule::{Listener, Rule, RuleContext, replace_node, trim_node_range};
8-
use crate::utils::{get_type_name, is_strong_precedence_node, union_type_parts};
8+
use crate::utils::{
9+
get_constant_variable_initializer, get_type_name, is_strong_precedence_node, union_type_parts,
10+
};
911

1012
pub struct PreferRegexpExec;
1113

@@ -141,19 +143,8 @@ fn get_static_argument_value(
141143
if !visited.insert(symbol) {
142144
return StaticArgumentValue::Unknown;
143145
}
144-
let result = symbol.value_declaration().and_then(|declaration| {
145-
if declaration.kind() != Kind::VariableDeclaration
146-
|| declaration.parent().is_none_or(|parent| {
147-
parent.kind() != Kind::VariableDeclarationList
148-
|| !parent.flags().intersects(NodeFlags::Const)
149-
})
150-
{
151-
return None;
152-
}
153-
declaration
154-
.initializer()
155-
.map(|initializer| get_static_argument_value(checker, initializer, visited))
156-
});
146+
let result = get_constant_variable_initializer(checker, node)
147+
.map(|initializer| get_static_argument_value(checker, initializer, visited));
157148
visited.remove(&symbol);
158149
return result.unwrap_or_default();
159150
}

‎crates/tsrs_lint/src/rules/prefer_string_starts_ends_with.rs‎

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -98,20 +98,12 @@ fn static_number(node: P<Node>) -> Option<f64> {
9898
None
9999
}
100100

101-
fn variable_initializer(checker: &mut Checker, node: P<Node>) -> Option<P<Node>> {
102-
let declaration = checker.get_symbol_at_location_exported(node)?.value_declaration()?;
103-
if declaration.kind() != Kind::VariableDeclaration {
104-
return None;
105-
}
106-
declaration.initializer()
107-
}
108-
109101
fn static_string(checker: &mut Checker, node: P<Node>) -> Option<&'static str> {
110102
let node = ast::skip_parentheses(node);
111103
match node.kind() {
112104
Kind::StringLiteral | Kind::NoSubstitutionTemplateLiteral => Some(node.text()),
113105
Kind::Identifier => {
114-
let initializer = variable_initializer(checker, node)?;
106+
let initializer = utils::get_constant_variable_initializer(checker, node)?;
115107
static_string(checker, initializer)
116108
}
117109
_ => None,
@@ -129,7 +121,7 @@ fn get_nullish_kind(checker: &mut Checker, node: P<Node>) -> NullishKind {
129121
return NullishKind::Undefined;
130122
}
131123
if node.kind() == Kind::Identifier
132-
&& let Some(initializer) = variable_initializer(checker, node)
124+
&& let Some(initializer) = utils::get_constant_variable_initializer(checker, node)
133125
{
134126
return get_nullish_kind(checker, initializer);
135127
}
@@ -218,7 +210,7 @@ fn parse_reg_exp(checker: &mut Checker, node: P<Node>) -> Option<ParsedRegExp> {
218210
(args[0].text(), flags)
219211
}
220212
Kind::Identifier => {
221-
let initializer = variable_initializer(checker, node)?;
213+
let initializer = utils::get_constant_variable_initializer(checker, node)?;
222214
return parse_reg_exp(checker, initializer);
223215
}
224216
_ => return None,

‎crates/tsrs_lint/src/utils.rs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,56 @@ pub fn get_contextual_type(checker: &mut Checker, node: P<Node>) -> Option<P<Typ
588588
checker.get_contextual_type(node, tsrs_checker::ContextFlags::None)
589589
}
590590

591+
/// Returns the variable initializer that eslint-utils' `getStaticValue` would follow for `node`.
592+
///
593+
/// The variable must have a single declaration in the same file, bind a plain identifier, and be
594+
/// either `const` or never written after its initializer.
595+
pub fn get_constant_variable_initializer(checker: &mut Checker, node: P<Node>) -> Option<P<Node>> {
596+
if !ast::is_identifier(node) {
597+
return None;
598+
}
599+
let symbol = checker.get_symbol_at_location_exported(node)?;
600+
let &[declaration] = symbol.declarations() else {
601+
return None;
602+
};
603+
if declaration.kind() != Kind::VariableDeclaration
604+
|| !declaration.name().is_some_and(ast::is_identifier)
605+
{
606+
return None;
607+
}
608+
let initializer = declaration.initializer()?;
609+
let source_file = ast::get_source_file_of_node(declaration)?;
610+
if ast::get_source_file_of_node(node) != Some(source_file) {
611+
return None;
612+
}
613+
let name = declaration.name().unwrap().text();
614+
(ast::is_var_const(declaration)
615+
|| !has_write_reference(checker, source_file.as_node(), symbol, name))
616+
.then_some(initializer)
617+
}
618+
619+
fn has_write_reference(
620+
checker: &mut Checker,
621+
node: P<Node>,
622+
symbol: P<Symbol>,
623+
name: &str,
624+
) -> bool {
625+
node.for_each_child(&mut |child| {
626+
if !ast::is_identifier(child) {
627+
return has_write_reference(checker, child, symbol, name);
628+
}
629+
if child.text() != name || !ast::is_write_access(child) {
630+
return false;
631+
}
632+
if let Some(parent) =
633+
child.parent().filter(|&parent| ast::is_shorthand_property_assignment(parent))
634+
{
635+
return checker.get_shorthand_assignment_value_symbol(Some(parent)) == Some(symbol);
636+
}
637+
checker.get_symbol_at_location_exported(child) == Some(symbol)
638+
})
639+
}
640+
591641
pub fn get_this_expression(mut node: P<Node>) -> Option<P<Node>> {
592642
loop {
593643
node = ast::skip_parentheses(node);

‎crates/tsrs_lint/tests/baselines/PROGRESS.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,16 @@ and suggestions before its implementation commit. Upstream skips remain explicit
4848
| non-nullable-type-assertion-style | Updated to 020d62f7 | 27 current cases; UTF-8 suggestion ranges, independent flags, ignored options, assertion precedence, generic constraints and JavaScript JSDoc casts |
4949
| only-throw-error | Updated to Go HEAD | 112 current cases; UTF-8 ranges, per-file options, null defaults, invalid options, rethrow boundaries and independent flags |
5050
| prefer-find | Updated to Go HEAD | 47 current cases; constant/coercion evaluation, constrained array unions/intersections, conditional/comma suggestions, UTF-8 comment ranges and independent suggestion flags |
51-
| prefer-includes | Updated to c0c11eaa | 81 current cases; parameter-text compatibility, regexp patterns, UTF-8 ranges, ignored options and independent fix flags |
51+
| prefer-includes | Updated to b3c5445e | 83 current cases; effectively-const pattern variables, parameter-text compatibility, regexp patterns, UTF-8 ranges, ignored options and independent fix flags |
5252
| prefer-optional-chain | Updated to Go HEAD | 1178 current cases at tsgolint `6b043c5f3dd19e3a162b7f0edf587a9ae83bfe81`; structural chains, nullish guards, comment-preserving fixes, UTF-8 ranges, per-file options/state and independent fix/suggestion flags; 3 direct JSX-context controls and 5 callback cases from upstream #1335 |
5353
| prefer-nullish-coalescing | Updated to Go HEAD | 184 current cases, 2 upstream skips; UTF-8 suggestion ranges, independent flags, per-file options, Boolean shadowing, raw generic types and strictness diagnostics |
5454
| prefer-promise-reject-errors | Updated to Go HEAD | 161 current cases, 1 upstream skips; UTF-8 call ranges, per-file options, null defaults, invalid options, computed accesses, executor boundaries, readonly constraints and independent flags |
5555
| prefer-readonly-parameter-types | Updated to Go HEAD | 135 current cases; recursive readonly arrays/tuples/properties/indexes, branded literals, UTF-8 parameter ranges, per-file/null/invalid options and independent flags |
56-
| prefer-regexp-exec | Updated to Go HEAD | 36 current cases; regexp2 syntax, Unicode 17 predicates, conditional branch/reference regressions, const aliases/global flags, constrained strings, computed access, UTF-8 ranges, ignored options and independent fix flags |
56+
| prefer-regexp-exec | Updated to b3c5445e | 38 current cases; effectively-const argument variables, regexp2 syntax, Unicode 17 predicates, conditional branch/reference regressions, const aliases/global flags, constrained strings, computed access, UTF-8 ranges, ignored options and independent fix flags |
5757
| prefer-readonly | Updated to Go HEAD | 162 current cases; UTF-8 ranges, constructor/nested-class scope, type relations, enum shadowing, per-file options/state and independent fix/suggestion flags |
5858
| prefer-reduce-type-parameter | Updated to Go HEAD | 31 current cases; UTF-8 comment ranges, raw type trivia, computed members, readonly arrays, chained constraints, ignored options and independent fix/suggestion flags |
5959
| prefer-return-this-type | Updated to Go HEAD | 22 current cases; UTF-8 ranges, exact class/this type identity, nested return boundaries, ignored options, per-file isolation and independent fix/suggestion flags |
60-
| prefer-string-starts-ends-with | Updated to Go HEAD | 132 current cases; UTF-8 fix ranges, string constraints, regex flags/escapes, null defaults, per-file options, invalid options and independent fix/suggestion flags |
60+
| prefer-string-starts-ends-with | Updated to b3c5445e | 137 current cases; effectively-const static values, UTF-8 fix ranges, string constraints, regex flags/escapes, null defaults, per-file options, invalid options and independent fix/suggestion flags |
6161
| promise-function-async | Updated to Go HEAD | 53 current cases; UTF-8 ranges, inherited and generic return types, overloads, per-file/null/invalid options and independent fix/suggestion flags |
6262
| related-getter-setter-pairs | Updated to Go HEAD | 23 current cases; 26 oracle regressions for UTF-8 ranges, textual/computed/private names, duplicate source order, generic assignability, nested scopes, ignored options and independent fix/suggestion flags |
6363
| require-array-sort-compare | Updated to Go HEAD | 55 current cases; tuples, UTF-8 call ranges, computed/optional accesses, readonly tuples, generic constraints, array unions/intersections, per-file/null/invalid options and independent fix/suggestion flags |
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
tsgolint c0c11eaa08cb3995f5b7d4e95cf7ac15ebc05805
1+
tsgolint b3c5445e86da4c2b2abe514e79c89f4ca4d8bd84
22
typescript-go 2bd066d87f5bafd315be9f40889d0a60b9e58e0b

‎crates/tsrs_lint/tests/baselines/prefer-includes/baseline.json‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,17 @@
234234
"Tsx": false,
235235
"Files": {},
236236
"Diagnostics": []
237+
},
238+
{
239+
"Code": "\n let re = /abc/;\n re = /xyz/;\n export const found = re.test('xyz');\n ",
240+
"Only": false,
241+
"Skip": false,
242+
"FileName": "",
243+
"Options": null,
244+
"TSConfig": "",
245+
"Tsx": false,
246+
"Files": {},
247+
"Diagnostics": []
237248
}
238249
],
239250
"Invalid": [
@@ -4102,6 +4113,67 @@
41024113
]
41034114
}
41044115
]
4116+
},
4117+
{
4118+
"Code": "\n let re = /abc/;\n export const found = re.test('xyz');\n ",
4119+
"Only": false,
4120+
"Skip": false,
4121+
"FileName": "",
4122+
"Output": [
4123+
"\n let re = /abc/;\n export const found = 'xyz'.includes('abc');\n "
4124+
],
4125+
"Errors": [
4126+
{
4127+
"MessageId": "preferStringIncludes",
4128+
"Line": 3,
4129+
"Column": 30,
4130+
"EndLine": 0,
4131+
"EndColumn": 0,
4132+
"Suggestions": []
4133+
}
4134+
],
4135+
"TSConfig": "",
4136+
"Options": null,
4137+
"Tsx": false,
4138+
"Files": {},
4139+
"Diagnostics": [
4140+
{
4141+
"kind": 0,
4142+
"rule": "prefer-includes",
4143+
"message": {
4144+
"id": "preferStringIncludes",
4145+
"description": "Use `String#includes()` method with a string instead."
4146+
},
4147+
"file_path": "file.ts",
4148+
"range": {
4149+
"pos": 54,
4150+
"end": 68
4151+
},
4152+
"fixes": [
4153+
{
4154+
"text": "",
4155+
"range": {
4156+
"pos": 54,
4157+
"end": 62
4158+
}
4159+
},
4160+
{
4161+
"text": "",
4162+
"range": {
4163+
"pos": 67,
4164+
"end": 68
4165+
}
4166+
},
4167+
{
4168+
"text": ".includes('abc')",
4169+
"range": {
4170+
"pos": 67,
4171+
"end": 67
4172+
}
4173+
}
4174+
]
4175+
}
4176+
]
41054177
}
41064178
]
41074179
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
tsgolint 4ebf80fd2b166cba4890c6896220fec4a1462b29
1+
tsgolint b3c5445e86da4c2b2abe514e79c89f4ca4d8bd84
22
typescript-go 2bd066d87f5bafd315be9f40889d0a60b9e58e0b

‎crates/tsrs_lint/tests/baselines/prefer-regexp-exec/baseline.json‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,17 @@
278278
"Tsx": false,
279279
"Files": {},
280280
"Diagnostics": []
281+
},
282+
{
283+
"Code": "\nlet pattern = /a/;\npattern = /b/;\n'aa'.match(pattern);\n ",
284+
"Only": false,
285+
"Skip": false,
286+
"FileName": "",
287+
"Options": null,
288+
"TSConfig": "",
289+
"Tsx": false,
290+
"Files": {},
291+
"Diagnostics": []
281292
}
282293
],
283294
"Invalid": [
@@ -827,6 +838,53 @@
827838
"rule": "prefer-regexp-exec"
828839
}
829840
]
841+
},
842+
{
843+
"Code": "\nlet pattern = /a/;\n'aa'.match(pattern);\n ",
844+
"Only": false,
845+
"Skip": false,
846+
"FileName": "",
847+
"Output": [
848+
"\nlet pattern = /a/;\npattern.exec('aa');\n "
849+
],
850+
"Errors": [
851+
{
852+
"MessageId": "regExpExecOverStringMatch",
853+
"Line": 3,
854+
"Column": 6,
855+
"EndLine": 0,
856+
"EndColumn": 0,
857+
"Suggestions": []
858+
}
859+
],
860+
"TSConfig": "",
861+
"Options": null,
862+
"Tsx": false,
863+
"Files": {},
864+
"Diagnostics": [
865+
{
866+
"range": {
867+
"pos": 25,
868+
"end": 30
869+
},
870+
"fixes": [
871+
{
872+
"text": "pattern.exec('aa')",
873+
"range": {
874+
"pos": 20,
875+
"end": 39
876+
}
877+
}
878+
],
879+
"kind": 0,
880+
"rule": "prefer-regexp-exec",
881+
"message": {
882+
"id": "regExpExecOverStringMatch",
883+
"description": "Use the `RegExp#exec()` method instead."
884+
},
885+
"file_path": "file.ts"
886+
}
887+
]
830888
}
831889
]
832890
}
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
tsgolint 4ebf80fd2b166cba4890c6896220fec4a1462b29
1+
tsgolint b3c5445e86da4c2b2abe514e79c89f4ca4d8bd84
22
typescript-go 2bd066d87f5bafd315be9f40889d0a60b9e58e0b

0 commit comments

Comments
 (0)