6 use clippy_utils::{diagnostics::span_lint_and_help, in_macro, is_direct_expn_of, source::snippet_opt};
7 use if_chain::if_chain;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_lint::{EarlyContext, EarlyLintPass};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
13 use serde::{de, Deserialize};
15 declare_clippy_lint! {
17 /// Checks that common macros are used with consistent bracing.
19 /// ### Why is this bad?
20 /// This is mostly a consistency lint although using () or []
21 /// doesn't give you a semicolon in item position, which can be unexpected.
31 pub NONSTANDARD_MACRO_BRACES,
33 "check consistent use of braces in macro"
36 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
38 /// The (name, (open brace, close brace), source snippet)
39 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
41 #[derive(Clone, Debug, Default)]
42 pub struct MacroBraces {
43 macro_braces: FxHashMap<String, (String, String)>,
44 done: FxHashSet<Span>,
48 pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
49 let macro_braces = macro_braces(conf.clone());
52 done: FxHashSet::default(),
57 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
59 impl EarlyLintPass for MacroBraces {
60 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
61 if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) {
62 let span = item.span.ctxt().outer_expn_data().call_site;
63 emit_help(cx, snip, braces, name, span);
64 self.done.insert(span);
68 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
69 if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
70 let span = stmt.span.ctxt().outer_expn_data().call_site;
71 emit_help(cx, snip, braces, name, span);
72 self.done.insert(span);
76 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
77 if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) {
78 let span = expr.span.ctxt().outer_expn_data().call_site;
79 emit_help(cx, snip, braces, name, span);
80 self.done.insert(span);
84 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
85 if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) {
86 let span = ty.span.ctxt().outer_expn_data().call_site;
87 emit_help(cx, snip, braces, name, span);
88 self.done.insert(span);
93 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
96 if let Some((name, braces)) = find_matching_macro(span, &mac_braces.macro_braces);
97 if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
98 // we must check only invocation sites
99 // https://github.com/rust-lang/rust-clippy/issues/7422
100 if snip.starts_with(name);
101 // make formatting consistent
102 let c = snip.replace(" ", "");
103 if !c.starts_with(&format!("{}!{}", name, braces.0));
104 if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
106 Some((name, braces, snip))
113 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) {
114 let with_space = &format!("! {}", braces.0);
115 let without_space = &format!("!{}", braces.0);
117 for b in BRACES.iter().filter(|b| b.0 != braces.0) {
118 help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
119 // Only `{` traditionally has space before the brace
120 if braces.0 != "{" && help.contains(with_space) {
121 help = help.replace(with_space, without_space);
122 } else if braces.0 == "{" && help.contains(without_space) {
123 help = help.replace(without_space, with_space);
128 NONSTANDARD_MACRO_BRACES,
130 &format!("use of irregular braces for `{}!` macro", name),
132 &format!("consider writing `{}`", help),
136 fn find_matching_macro(
138 braces: &FxHashMap<String, (String, String)>,
139 ) -> Option<(&String, &(String, String))> {
142 .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
145 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
146 let mut braces = vec![
185 .collect::<FxHashMap<_, _>>();
186 // We want users items to override any existing items
188 braces.insert(it.name, it.braces);
193 macro_rules! macro_matcher {
194 (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
195 ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
198 pub(crate) use macro_matcher;
200 #[derive(Clone, Debug)]
201 pub struct MacroMatcher {
203 braces: (String, String),
206 impl Hash for MacroMatcher {
207 fn hash<H: Hasher>(&self, state: &mut H) {
208 self.name.hash(state);
212 impl PartialEq for MacroMatcher {
213 fn eq(&self, other: &Self) -> bool {
214 self.name == other.name
217 impl Eq for MacroMatcher {}
219 impl<'de> Deserialize<'de> for MacroMatcher {
220 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
222 D: de::Deserializer<'de>,
224 #[derive(Deserialize)]
225 #[serde(field_identifier, rename_all = "lowercase")]
231 impl<'de> de::Visitor<'de> for MacVisitor {
232 type Value = MacroMatcher;
234 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
235 formatter.write_str("struct MacroMatcher")
238 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
240 V: de::MapAccess<'de>,
243 let mut brace: Option<&str> = None;
244 while let Some(key) = map.next_key()? {
248 return Err(de::Error::duplicate_field("name"));
250 name = Some(map.next_value()?);
254 return Err(de::Error::duplicate_field("brace"));
256 brace = Some(map.next_value()?);
260 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
261 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
266 .find(|b| b.0 == brace)
267 .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
269 de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
275 const FIELDS: &[&str] = &["name", "brace"];
276 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)