Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 66 additions & 19 deletions crates/tsrs_lint/src/rules/no_base_to_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
use rustc_hash::{FxHashMap, FxHashSet};
use tsrs_ast::{self as ast, Kind, Node};
use tsrs_checker::{self as checker, Checker, Type, TypeFlags};
use tsrs_compiler::Program;
use tsrs_core::{P, json::Value};

use crate::protocol::RuleMessage;
use crate::rule::{Listener, Rule, RuleContext, trim_node_range};
use crate::utils::{
get_constrained_type_at_location, get_type_name, is_builtin_symbol_like,
matches_type_or_base_type,
is_symbol_from_default_library, matches_type_or_base_type,
};

#[derive(Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -53,6 +54,33 @@ impl CertaintyMemo {
}
}

fn is_symbol_to_primitive_method(
program: &Program,
checker: &mut Checker,
declaration: P<Node>,
) -> bool {
if declaration.kind() != Kind::MethodSignature {
return false;
}
let Some(name) = declaration.name().filter(|&name| name.kind() == Kind::ComputedPropertyName)
else {
return false;
};
let expression = name.expression().unwrap();
if expression.kind() != Kind::PropertyAccessExpression {
return false;
}
let object = expression.expression().unwrap();
let name = expression.name().unwrap();
ast::is_identifier(object)
&& object.text() == "Symbol"
&& ast::is_identifier(name)
&& name.text() == "toPrimitive"
&& checker
.get_symbol_at_location_exported(object)
.is_some_and(|symbol| is_symbol_from_default_library(program, symbol))
}

pub struct NoBaseToString {
check_unknown: bool,
ignored_type_names: Vec<String>,
Expand Down Expand Up @@ -96,6 +124,7 @@ impl NoBaseToString {

fn collect_union_type_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
Expand All @@ -105,9 +134,9 @@ impl NoBaseToString {
let mut all_always = true;
for &part in t.types() {
let value = if join {
self.collect_join_certainty(checker, part, visited)
self.collect_join_certainty(program, checker, part, visited)
} else {
self.collect_to_string_certainty(checker, part, visited)
self.collect_to_string_certainty(program, checker, part, visited)
};
all_never &= value == Usefulness::Never;
all_always &= value == Usefulness::Always;
Expand All @@ -123,16 +152,17 @@ impl NoBaseToString {

fn collect_intersection_type_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
join: bool,
) -> Usefulness {
if t.types().iter().any(|&part| {
let value = if join {
self.collect_join_certainty(checker, part, visited)
self.collect_join_certainty(program, checker, part, visited)
} else {
self.collect_to_string_certainty(checker, part, visited)
self.collect_to_string_certainty(program, checker, part, visited)
};
value == Usefulness::Always
}) {
Expand All @@ -144,14 +174,15 @@ impl NoBaseToString {

fn collect_tuple_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
) -> Usefulness {
let mut never = false;
let mut sometimes = false;
for &argument in checker.get_type_arguments(t) {
let value = self.collect_to_string_certainty(checker, argument, visited);
let value = self.collect_to_string_certainty(program, checker, argument, visited);
never |= value == Usefulness::Never;
sometimes |= value == Usefulness::Sometimes;
}
Expand All @@ -166,18 +197,20 @@ impl NoBaseToString {

fn collect_array_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
) -> Usefulness {
let element = checker
.get_index_type_of_type(t, checker.number_type)
.expect("array should have number index type");
self.collect_to_string_certainty(checker, element, visited)
self.collect_to_string_certainty(program, checker, element, visited)
}

fn collect_join_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
Expand All @@ -186,13 +219,13 @@ impl NoBaseToString {
return value;
}
let value = if t.flags().intersects(TypeFlags::Union) {
self.collect_union_type_certainty(checker, t, visited, true)
self.collect_union_type_certainty(program, checker, t, visited, true)
} else if t.flags().intersects(TypeFlags::Intersection) {
self.collect_intersection_type_certainty(checker, t, visited, true)
self.collect_intersection_type_certainty(program, checker, t, visited, true)
} else if checker::is_tuple_type_exported(t) {
self.collect_tuple_certainty(checker, t, visited)
self.collect_tuple_certainty(program, checker, t, visited)
} else if checker.is_array_type(t) {
self.collect_array_certainty(checker, t, visited)
self.collect_array_certainty(program, checker, t, visited)
} else {
Usefulness::Always
};
Expand All @@ -201,6 +234,7 @@ impl NoBaseToString {

fn collect_to_string_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
Expand All @@ -211,19 +245,20 @@ impl NoBaseToString {
if let Some(value) = self.to_string_memo.start(t) {
return value;
}
let value = self.compute_to_string_certainty(checker, t, visited);
let value = self.compute_to_string_certainty(program, checker, t, visited);
self.to_string_memo.finish(t, value)
}

fn compute_to_string_certainty(
&mut self,
program: &Program,
checker: &mut Checker,
t: P<Type>,
visited: &[P<Type>],
) -> Usefulness {
if t.flags().intersects(TypeFlags::TypeParameter) {
return if let Some(constraint) = checker.get_base_constraint_of_type(t) {
self.collect_to_string_certainty(checker, constraint, visited)
self.collect_to_string_certainty(program, checker, constraint, visited)
} else if self.check_unknown {
Usefulness::Sometimes
} else {
Expand All @@ -240,20 +275,27 @@ impl NoBaseToString {
return Usefulness::Always;
}
if t.flags().intersects(TypeFlags::Intersection) {
return self.collect_intersection_type_certainty(checker, t, visited, false);
return self.collect_intersection_type_certainty(program, checker, t, visited, false);
}
if t.flags().intersects(TypeFlags::Union) {
return self.collect_union_type_certainty(checker, t, visited, false);
return self.collect_union_type_certainty(program, checker, t, visited, false);
}
if checker::is_tuple_type_exported(t) || checker.is_array_type(t) {
let mut visited = visited.to_vec();
visited.push(t);
return if checker::is_tuple_type_exported(t) {
self.collect_tuple_certainty(checker, t, &visited)
self.collect_tuple_certainty(program, checker, t, &visited)
} else {
self.collect_array_certainty(checker, t, &visited)
self.collect_array_certainty(program, checker, t, &visited)
};
}
if checker.get_properties_of_type(t).iter().any(|property| {
property.value_declaration().is_some_and(|declaration| {
is_symbol_to_primitive_method(program, checker, declaration)
})
}) {
return Usefulness::Always;
}
let mut found_fallback_on_object = false;
for name in ["toString", "toLocaleString", "valueOf"] {
let Some(property) = checker.get_property_of_type(t, name) else {
Expand Down Expand Up @@ -320,7 +362,7 @@ impl NoBaseToString {
return;
}
let t = t.unwrap_or_else(|| context.checker.get_type_at_location(node));
let certainty = self.collect_to_string_certainty(context.checker, t, &[]);
let certainty = self.collect_to_string_certainty(context.program, context.checker, t, &[]);
Self::report(node, certainty, false, context);
}
}
Expand Down Expand Up @@ -384,7 +426,12 @@ impl Rule for NoBaseToString {
context.checker,
member.expression,
);
let certainty = self.collect_join_certainty(context.checker, t, &[]);
let certainty = self.collect_join_certainty(
context.program,
context.checker,
t,
&[],
);
Self::report(member.expression, certainty, true, context);
}
"toLocaleString" | "toString" => {
Expand Down
2 changes: 1 addition & 1 deletion crates/tsrs_lint/tests/baselines/PROGRESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ and suggestions before its implementation commit. Upstream skips remain explicit
| consistent-type-exports | Updated to Go HEAD | 49 current cases; source overrides and both mixed-export fix modes |
| dot-notation | Updated to Go HEAD | 75 current cases; Go regex quoting, groups, classes, repetitions, Unicode properties, and octal escapes |
| no-array-delete | Updated to Go HEAD | 31 current cases; suggestion flags and UTF-8 ranges |
| no-base-to-string | Updated to Go HEAD | 380 current cases, 1 upstream skips; conversions/joins, recursive types, ignored names, checkUnknown |
| no-base-to-string | Updated to 7f5c22e5 | 384 current cases, 1 upstream skips; `Symbol.toPrimitive` methods, conversions/joins, recursive types, ignored names, checkUnknown |
| no-confusing-void-expression | Updated to Go HEAD | 109 current cases, 1 upstream skips; arrow/return fixes, contextual void, option combinations |
| no-deprecated | Updated to Go HEAD | 242 current cases, 12 upstream skips; aliases, circular alias chains, signatures, contextual properties, destructuring, allow specifiers |
| no-duplicate-type-constituents | Updated to 840816e9 | 89 current cases, 2 upstream skips; nested unions/intersections, optional parameter fixes, multiline JSDoc ranges and fixes after template literal types |
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
tsgolint 4ebf80fd2b166cba4890c6896220fec4a1462b29
tsgolint 7f5c22e5ef395c19f854d5c84c195025c4480a53
typescript-go 2bd066d87f5bafd315be9f40889d0a60b9e58e0b
96 changes: 96 additions & 0 deletions crates/tsrs_lint/tests/baselines/no-base-to-string/baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -2116,6 +2116,28 @@
"Files": {},
"Diagnostics": []
},
{
"Code": "\ndeclare const a: {\n [Symbol.toPrimitive](): string;\n};\n\n`${a}`;\n ",
"Only": false,
"Skip": false,
"FileName": "",
"Options": null,
"TSConfig": "",
"Tsx": false,
"Files": {},
"Diagnostics": []
},
{
"Code": "\ndeclare const a: {\n valueOf(): string;\n};\n\n`${a}`;\n ",
"Only": false,
"Skip": false,
"FileName": "",
"Options": null,
"TSConfig": "",
"Tsx": false,
"Files": {},
"Diagnostics": []
},
{
"Code": "\nfunction someFunction() {}\nsomeFunction.toString();\nlet text = `${someFunction}`;\n ",
"Only": false,
Expand Down Expand Up @@ -5117,6 +5139,80 @@
}
]
},
{
"Code": "\n declare const a:\n | {\n [Symbol.toPrimitive](): string;\n }\n | {\n other: true;\n };\n\n `${a}`;\n ",
"Only": false,
"Skip": false,
"FileName": "",
"Output": [],
"Errors": [
{
"MessageId": "baseToString",
"Line": 10,
"Column": 12,
"EndLine": 0,
"EndColumn": 0,
"Suggestions": []
}
],
"TSConfig": "",
"Options": null,
"Tsx": false,
"Files": {},
"Diagnostics": [
{
"kind": 0,
"rule": "no-base-to-string",
"message": {
"id": "baseToString",
"description": "'a' may use Object's default stringification format ('[object Object]') when stringified.",
"help": "Consider picking a property (e.g. `user.name`), using a formatter (or `JSON.stringify`), or implementing a custom `toString()`/`toLocaleString()` on the type."
},
"file_path": "file.ts",
"range": {
"pos": 168,
"end": 169
}
}
]
},
{
"Code": "\n declare const a:\n | {\n valueOf(): string;\n }\n | {\n other: true;\n };\n\n `${a}`;\n ",
"Only": false,
"Skip": false,
"FileName": "",
"Output": [],
"Errors": [
{
"MessageId": "baseToString",
"Line": 10,
"Column": 12,
"EndLine": 0,
"EndColumn": 0,
"Suggestions": []
}
],
"TSConfig": "",
"Options": null,
"Tsx": false,
"Files": {},
"Diagnostics": [
{
"kind": 0,
"rule": "no-base-to-string",
"message": {
"id": "baseToString",
"description": "'a' may use Object's default stringification format ('[object Object]') when stringified.",
"help": "Consider picking a property (e.g. `user.name`), using a formatter (or `JSON.stringify`), or implementing a custom `toString()`/`toLocaleString()` on the type."
},
"file_path": "file.ts",
"range": {
"pos": 155,
"end": 156
}
}
]
},
{
"Code": "\n [{}, {}].toString();\n ",
"Only": false,
Expand Down
Loading
Loading