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_hir::def_id::DefId;
11 use rustc_lint::{EarlyContext, EarlyLintPass};
12 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use serde::{de, Deserialize};
16 declare_clippy_lint! {
18 /// Checks that common macros are used with consistent bracing.
20 /// ### Why is this bad?
21 /// This is mostly a consistency lint although using () or []
22 /// doesn't give you a semicolon in item position, which can be unexpected.
32 pub NONSTANDARD_MACRO_BRACES,
34 "check consistent use of braces in macro"
37 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
39 /// The (name, (open brace, close brace), source snippet)
40 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
42 #[derive(Clone, Debug, Default)]
43 pub struct MacroBraces {
44 macro_braces: FxHashMap<String, (String, String)>,
45 done: FxHashSet<Span>,
49 pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
50 let macro_braces = macro_braces(conf.clone());
53 done: FxHashSet::default(),
58 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
60 impl EarlyLintPass for MacroBraces {
61 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
62 if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) {
63 let span = item.span.ctxt().outer_expn_data().call_site;
64 emit_help(cx, snip, braces, name, span);
65 self.done.insert(span);
69 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
70 if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
71 let span = stmt.span.ctxt().outer_expn_data().call_site;
72 emit_help(cx, snip, braces, name, span);
73 self.done.insert(span);
77 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
78 if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) {
79 let span = expr.span.ctxt().outer_expn_data().call_site;
80 emit_help(cx, snip, braces, name, span);
81 self.done.insert(span);
85 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
86 if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) {
87 let span = ty.span.ctxt().outer_expn_data().call_site;
88 emit_help(cx, snip, braces, name, span);
89 self.done.insert(span);
94 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
95 let unnested_or_local = || {
96 let nested = in_macro(span.ctxt().outer_expn_data().call_site);
101 .map_or(false, |e| e.macro_def_id.map_or(false, DefId::is_local))
104 // Make sure we are only one level deep otherwise there are to many FP's
106 if let Some((name, braces)) = find_matching_macro(span, &mac_braces.macro_braces);
107 if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
108 // we must check only invocation sites
109 // https://github.com/rust-lang/rust-clippy/issues/7422
110 if snip.starts_with(&format!("{}!", name));
111 if unnested_or_local();
112 // make formatting consistent
113 let c = snip.replace(" ", "");
114 if !c.starts_with(&format!("{}!{}", name, braces.0));
115 if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
117 Some((name, braces, snip))
124 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) {
125 let with_space = &format!("! {}", braces.0);
126 let without_space = &format!("!{}", braces.0);
128 for b in BRACES.iter().filter(|b| b.0 != braces.0) {
129 help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
130 // Only `{` traditionally has space before the brace
131 if braces.0 != "{" && help.contains(with_space) {
132 help = help.replace(with_space, without_space);
133 } else if braces.0 == "{" && help.contains(without_space) {
134 help = help.replace(without_space, with_space);
139 NONSTANDARD_MACRO_BRACES,
141 &format!("use of irregular braces for `{}!` macro", name),
143 &format!("consider writing `{}`", help),
147 fn find_matching_macro(
149 braces: &FxHashMap<String, (String, String)>,
150 ) -> Option<(&String, &(String, String))> {
153 .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
156 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
157 let mut braces = vec![
196 .collect::<FxHashMap<_, _>>();
197 // We want users items to override any existing items
199 braces.insert(it.name, it.braces);
204 macro_rules! macro_matcher {
205 (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
206 ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
209 pub(crate) use macro_matcher;
211 #[derive(Clone, Debug)]
212 pub struct MacroMatcher {
214 braces: (String, String),
217 impl Hash for MacroMatcher {
218 fn hash<H: Hasher>(&self, state: &mut H) {
219 self.name.hash(state);
223 impl PartialEq for MacroMatcher {
224 fn eq(&self, other: &Self) -> bool {
225 self.name == other.name
228 impl Eq for MacroMatcher {}
230 impl<'de> Deserialize<'de> for MacroMatcher {
231 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
233 D: de::Deserializer<'de>,
235 #[derive(Deserialize)]
236 #[serde(field_identifier, rename_all = "lowercase")]
242 impl<'de> de::Visitor<'de> for MacVisitor {
243 type Value = MacroMatcher;
245 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
246 formatter.write_str("struct MacroMatcher")
249 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
251 V: de::MapAccess<'de>,
254 let mut brace: Option<&str> = None;
255 while let Some(key) = map.next_key()? {
259 return Err(de::Error::duplicate_field("name"));
261 name = Some(map.next_value()?);
265 return Err(de::Error::duplicate_field("brace"));
267 brace = Some(map.next_value()?);
271 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
272 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
277 .find(|b| b.0 == brace)
278 .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
280 de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
286 const FIELDS: &[&str] = &["name", "brace"];
287 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)