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! {
16 /// **What it does:** Checks that common macros are used with consistent bracing.
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.
21 /// **Known problems:**
33 pub NONSTANDARD_MACRO_BRACES,
35 "check consistent use of braces in macro"
38 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
40 /// The (name, (open brace, close brace), source snippet)
41 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
43 #[derive(Clone, Debug, Default)]
44 pub struct MacroBraces {
45 macro_braces: FxHashMap<String, (String, String)>,
46 done: FxHashSet<Span>,
50 pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
51 let macro_braces = macro_braces(conf.clone());
54 done: FxHashSet::default(),
59 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
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);
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);
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);
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);
95 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, this: &'a MacroBraces) -> Option<MacroInfo<'a>> {
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);
104 Some((name, braces, snip))
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);
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);
126 NONSTANDARD_MACRO_BRACES,
128 &format!("use of irregular braces for `{}!` macro", name),
130 &format!("consider writing `{}`", help),
134 fn find_matching_macro(
136 braces: &FxHashMap<String, (String, String)>,
137 ) -> Option<(&String, &(String, String))> {
140 .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
143 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
144 let mut braces = vec![
183 .collect::<FxHashMap<_, _>>();
184 // We want users items to override any existing items
186 braces.insert(it.name, it.braces);
191 macro_rules! macro_matcher {
192 (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
193 ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
196 pub(crate) use macro_matcher;
198 #[derive(Clone, Debug)]
199 pub struct MacroMatcher {
201 braces: (String, String),
204 impl Hash for MacroMatcher {
205 fn hash<H: Hasher>(&self, state: &mut H) {
206 self.name.hash(state);
210 impl PartialEq for MacroMatcher {
211 fn eq(&self, other: &Self) -> bool {
212 self.name == other.name
215 impl Eq for MacroMatcher {}
217 impl<'de> Deserialize<'de> for MacroMatcher {
218 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
220 D: de::Deserializer<'de>,
222 #[derive(Deserialize)]
223 #[serde(field_identifier, rename_all = "lowercase")]
229 impl<'de> de::Visitor<'de> for MacVisitor {
230 type Value = MacroMatcher;
232 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
233 formatter.write_str("struct MacroMatcher")
236 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
238 V: de::MapAccess<'de>,
241 let mut brace: Option<&str> = None;
242 while let Some(key) = map.next_key()? {
246 return Err(de::Error::duplicate_field("name"));
248 name = Some(map.next_value()?);
252 return Err(de::Error::duplicate_field("brace"));
254 brace = Some(map.next_value()?);
258 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
259 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
264 .find(|b| b.0 == brace)
265 .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
267 de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
273 const FIELDS: &[&str] = &["name", "brace"];
274 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)