|
| 1 | +use std::{ |
| 2 | + fmt, |
| 3 | + hash::{Hash, Hasher}, |
| 4 | +}; |
| 5 | + |
| 6 | +use clippy_utils::{diagnostics::span_lint_and_help, in_macro, is_direct_expn_of, source::snippet_opt}; |
| 7 | +use if_chain::if_chain; |
| 8 | +use rustc_ast::ast; |
| 9 | +use rustc_data_structures::fx::{FxHashMap, FxHashSet}; |
| 10 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 11 | +use rustc_session::{declare_tool_lint, impl_lint_pass}; |
| 12 | +use rustc_span::Span; |
| 13 | +use serde::{de, Deserialize}; |
| 14 | + |
| 15 | +declare_clippy_lint! { |
| 16 | + /// **What it does:** Checks that common macros are used with consistent bracing. |
| 17 | + /// |
| 18 | + /// **Why is this bad?** This is mostly a consistency lint although using () or [] |
| 19 | + /// doesn't give you a semicolon in item position, which can be unexpected. |
| 20 | + /// |
| 21 | + /// **Known problems:** |
| 22 | + /// None |
| 23 | + /// |
| 24 | + /// **Example:** |
| 25 | + /// |
| 26 | + /// ```rust |
| 27 | + /// vec!{1, 2, 3}; |
| 28 | + /// ``` |
| 29 | + /// Use instead: |
| 30 | + /// ```rust |
| 31 | + /// vec![1, 2, 3]; |
| 32 | + /// ``` |
| 33 | + pub NONSTANDARD_MACRO_BRACES, |
| 34 | + style, |
| 35 | + "check consistent use of braces in macro" |
| 36 | +} |
| 37 | + |
| 38 | +const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")]; |
| 39 | + |
| 40 | +/// The (name, (open brace, close brace), source snippet) |
| 41 | +type MacroInfo<'a> = (&'a str, &'a (String, String), String); |
| 42 | + |
| 43 | +#[derive(Clone, Debug, Default)] |
| 44 | +pub struct MacroBraces { |
| 45 | + macro_braces: FxHashMap<String, (String, String)>, |
| 46 | + done: FxHashSet<Span>, |
| 47 | +} |
| 48 | + |
| 49 | +impl MacroBraces { |
| 50 | + pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self { |
| 51 | + let macro_braces = macro_braces(conf.clone()); |
| 52 | + Self { |
| 53 | + macro_braces, |
| 54 | + done: FxHashSet::default(), |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]); |
| 60 | + |
| 61 | +impl EarlyLintPass for MacroBraces { |
| 62 | + fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) { |
| 63 | + if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) { |
| 64 | + let span = item.span.ctxt().outer_expn_data().call_site; |
| 65 | + emit_help(cx, snip, braces, name, span); |
| 66 | + self.done.insert(span); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { |
| 71 | + if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) { |
| 72 | + let span = stmt.span.ctxt().outer_expn_data().call_site; |
| 73 | + emit_help(cx, snip, braces, name, span); |
| 74 | + self.done.insert(span); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { |
| 79 | + if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) { |
| 80 | + let span = expr.span.ctxt().outer_expn_data().call_site; |
| 81 | + emit_help(cx, snip, braces, name, span); |
| 82 | + self.done.insert(span); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) { |
| 87 | + if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) { |
| 88 | + let span = ty.span.ctxt().outer_expn_data().call_site; |
| 89 | + emit_help(cx, snip, braces, name, span); |
| 90 | + self.done.insert(span); |
| 91 | + } |
| 92 | + } |
| 93 | +} |
| 94 | + |
| 95 | +fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, this: &'a MacroBraces) -> Option<MacroInfo<'a>> { |
| 96 | + if_chain! { |
| 97 | + if in_macro(span); |
| 98 | + if let Some((name, braces)) = find_matching_macro(span, &this.macro_braces); |
| 99 | + if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site); |
| 100 | + let c = snip.replace(" ", ""); // make formatting consistent |
| 101 | + if !c.starts_with(&format!("{}!{}", name, braces.0)); |
| 102 | + if !this.done.contains(&span.ctxt().outer_expn_data().call_site); |
| 103 | + then { |
| 104 | + Some((name, braces, snip)) |
| 105 | + } else { |
| 106 | + None |
| 107 | + } |
| 108 | + } |
| 109 | +} |
| 110 | + |
| 111 | +fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) { |
| 112 | + let with_space = &format!("! {}", braces.0); |
| 113 | + let without_space = &format!("!{}", braces.0); |
| 114 | + let mut help = snip; |
| 115 | + for b in BRACES.iter().filter(|b| b.0 != braces.0) { |
| 116 | + help = help.replace(b.0, &braces.0).replace(b.1, &braces.1); |
| 117 | + // Only `{` traditionally has space before the brace |
| 118 | + if braces.0 != "{" && help.contains(with_space) { |
| 119 | + help = help.replace(with_space, without_space); |
| 120 | + } else if braces.0 == "{" && help.contains(without_space) { |
| 121 | + help = help.replace(without_space, with_space); |
| 122 | + } |
| 123 | + } |
| 124 | + span_lint_and_help( |
| 125 | + cx, |
| 126 | + NONSTANDARD_MACRO_BRACES, |
| 127 | + span, |
| 128 | + &format!("use of irregular braces for `{}!` macro", name), |
| 129 | + Some(span), |
| 130 | + &format!("consider writing `{}`", help), |
| 131 | + ); |
| 132 | +} |
| 133 | + |
| 134 | +fn find_matching_macro( |
| 135 | + span: Span, |
| 136 | + braces: &FxHashMap<String, (String, String)>, |
| 137 | +) -> Option<(&String, &(String, String))> { |
| 138 | + braces |
| 139 | + .iter() |
| 140 | + .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some()) |
| 141 | +} |
| 142 | + |
| 143 | +fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> { |
| 144 | + let mut braces = vec![ |
| 145 | + macro_matcher!( |
| 146 | + name: "print", |
| 147 | + braces: ("(", ")"), |
| 148 | + ), |
| 149 | + macro_matcher!( |
| 150 | + name: "println", |
| 151 | + braces: ("(", ")"), |
| 152 | + ), |
| 153 | + macro_matcher!( |
| 154 | + name: "eprint", |
| 155 | + braces: ("(", ")"), |
| 156 | + ), |
| 157 | + macro_matcher!( |
| 158 | + name: "eprintln", |
| 159 | + braces: ("(", ")"), |
| 160 | + ), |
| 161 | + macro_matcher!( |
| 162 | + name: "write", |
| 163 | + braces: ("(", ")"), |
| 164 | + ), |
| 165 | + macro_matcher!( |
| 166 | + name: "writeln", |
| 167 | + braces: ("(", ")"), |
| 168 | + ), |
| 169 | + macro_matcher!( |
| 170 | + name: "format", |
| 171 | + braces: ("(", ")"), |
| 172 | + ), |
| 173 | + macro_matcher!( |
| 174 | + name: "format_args", |
| 175 | + braces: ("(", ")"), |
| 176 | + ), |
| 177 | + macro_matcher!( |
| 178 | + name: "vec", |
| 179 | + braces: ("[", "]"), |
| 180 | + ), |
| 181 | + ] |
| 182 | + .into_iter() |
| 183 | + .collect::<FxHashMap<_, _>>(); |
| 184 | + // We want users items to override any existing items |
| 185 | + for it in conf { |
| 186 | + braces.insert(it.name, it.braces); |
| 187 | + } |
| 188 | + braces |
| 189 | +} |
| 190 | + |
| 191 | +macro_rules! macro_matcher { |
| 192 | + (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => { |
| 193 | + ($name.to_owned(), ($open.to_owned(), $close.to_owned())) |
| 194 | + }; |
| 195 | +} |
| 196 | +pub(crate) use macro_matcher; |
| 197 | + |
| 198 | +#[derive(Clone, Debug)] |
| 199 | +pub struct MacroMatcher { |
| 200 | + name: String, |
| 201 | + braces: (String, String), |
| 202 | +} |
| 203 | + |
| 204 | +impl Hash for MacroMatcher { |
| 205 | + fn hash<H: Hasher>(&self, state: &mut H) { |
| 206 | + self.name.hash(state); |
| 207 | + } |
| 208 | +} |
| 209 | + |
| 210 | +impl PartialEq for MacroMatcher { |
| 211 | + fn eq(&self, other: &Self) -> bool { |
| 212 | + self.name == other.name |
| 213 | + } |
| 214 | +} |
| 215 | +impl Eq for MacroMatcher {} |
| 216 | + |
| 217 | +impl<'de> Deserialize<'de> for MacroMatcher { |
| 218 | + fn deserialize<D>(deser: D) -> Result<Self, D::Error> |
| 219 | + where |
| 220 | + D: de::Deserializer<'de>, |
| 221 | + { |
| 222 | + #[derive(Deserialize)] |
| 223 | + #[serde(field_identifier, rename_all = "lowercase")] |
| 224 | + enum Field { |
| 225 | + Name, |
| 226 | + Brace, |
| 227 | + } |
| 228 | + struct MacVisitor; |
| 229 | + impl<'de> de::Visitor<'de> for MacVisitor { |
| 230 | + type Value = MacroMatcher; |
| 231 | + |
| 232 | + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 233 | + formatter.write_str("struct MacroMatcher") |
| 234 | + } |
| 235 | + |
| 236 | + fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> |
| 237 | + where |
| 238 | + V: de::MapAccess<'de>, |
| 239 | + { |
| 240 | + let mut name = None; |
| 241 | + let mut brace: Option<&str> = None; |
| 242 | + while let Some(key) = map.next_key()? { |
| 243 | + match key { |
| 244 | + Field::Name => { |
| 245 | + if name.is_some() { |
| 246 | + return Err(de::Error::duplicate_field("name")); |
| 247 | + } |
| 248 | + name = Some(map.next_value()?); |
| 249 | + }, |
| 250 | + Field::Brace => { |
| 251 | + if brace.is_some() { |
| 252 | + return Err(de::Error::duplicate_field("brace")); |
| 253 | + } |
| 254 | + brace = Some(map.next_value()?); |
| 255 | + }, |
| 256 | + } |
| 257 | + } |
| 258 | + let name = name.ok_or_else(|| de::Error::missing_field("name"))?; |
| 259 | + let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?; |
| 260 | + Ok(MacroMatcher { |
| 261 | + name, |
| 262 | + braces: BRACES |
| 263 | + .iter() |
| 264 | + .find(|b| b.0 == brace) |
| 265 | + .map(|(o, c)| ((*o).to_owned(), (*c).to_owned())) |
| 266 | + .ok_or_else(|| { |
| 267 | + de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace)) |
| 268 | + })?, |
| 269 | + }) |
| 270 | + } |
| 271 | + } |
| 272 | + |
| 273 | + const FIELDS: &[&str] = &["name", "brace"]; |
| 274 | + deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor) |
| 275 | + } |
| 276 | +} |
0 commit comments