Skip to content

Commit c3b6eee

Browse files
committed
Add keyword whitelist to similar_names lint
changelog: [`similar_names`] lint no longer warns when an underscore was added to a name to avoid a keyword clash
1 parent 10db5a6 commit c3b6eee

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

clippy_lints/src/non_expressive_names.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,16 @@ fn allowed_to_be_similar(interned_name: &str, list: &[&str]) -> bool {
168168
.any(|&name| interned_name.starts_with(name) || interned_name.ends_with(name))
169169
}
170170

171+
fn avoiding_keyword_clash(maybe_keyword: &str) -> bool {
172+
let rust_keywords = [
173+
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl",
174+
"in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct",
175+
"super", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn", "abstract",
176+
"become", "box", "do", "final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "union",
177+
];
178+
rust_keywords.iter().any(|kw| *kw == maybe_keyword)
179+
}
180+
171181
impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
172182
fn check_short_ident(&mut self, ident: Ident) {
173183
// Ignore shadowing
@@ -205,6 +215,13 @@ impl<'a, 'tcx, 'b> SimilarNamesNameVisitor<'a, 'tcx, 'b> {
205215
// these bindings are typically unused or represent an ignored portion of a destructuring pattern
206216
return;
207217
}
218+
if interned_name
219+
.strip_suffix('_')
220+
.map_or(false, |maybe_keyword| avoiding_keyword_clash(&maybe_keyword))
221+
{
222+
// do not warn if an underscore was added to avoid a keyword clash, e.g. types = [..] and type_ = x
223+
return;
224+
}
208225
let count = interned_name.chars().count();
209226
if count < 3 {
210227
if count == 1 {

tests/ui/similar_names.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,3 +106,16 @@ fn ignore_underscore_prefix() {
106106
let hello: ();
107107
let _hello: ();
108108
}
109+
110+
fn ignore_keywords_with_underscore_suffix() {
111+
let types: ();
112+
let type_: ();
113+
let continues: ();
114+
let continue_: ();
115+
let ifa: ();
116+
let if_: ();
117+
let structs: ();
118+
let struct_: ();
119+
let ins: ();
120+
let in_: ();
121+
}

0 commit comments

Comments
 (0)