6 use clippy_utils::diagnostics::span_lint_and_help;
7 use clippy_utils::source::snippet_opt;
8 use if_chain::if_chain;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::def_id::DefId;
12 use rustc_lint::{EarlyContext, EarlyLintPass};
13 use rustc_session::{declare_tool_lint, impl_lint_pass};
14 use rustc_span::hygiene::{ExpnKind, MacroKind};
15 use rustc_span::{Span, Symbol};
16 use serde::{de, Deserialize};
18 declare_clippy_lint! {
20 /// Checks that common macros are used with consistent bracing.
22 /// ### Why is this bad?
23 /// This is mostly a consistency lint although using () or []
24 /// doesn't give you a semicolon in item position, which can be unexpected.
34 pub NONSTANDARD_MACRO_BRACES,
36 "check consistent use of braces in macro"
39 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
41 /// The (name, (open brace, close brace), source snippet)
42 type MacroInfo<'a> = (Symbol, &'a (String, String), String);
44 #[derive(Clone, Debug, Default)]
45 pub struct MacroBraces {
46 macro_braces: FxHashMap<String, (String, String)>,
47 done: FxHashSet<Span>,
51 pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
52 let macro_braces = macro_braces(conf.clone());
55 done: FxHashSet::default(),
60 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
62 impl EarlyLintPass for MacroBraces {
63 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
64 if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) {
65 let span = item.span.ctxt().outer_expn_data().call_site;
66 emit_help(cx, snip, braces, name, span);
67 self.done.insert(span);
71 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
72 if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
73 let span = stmt.span.ctxt().outer_expn_data().call_site;
74 emit_help(cx, snip, braces, name, span);
75 self.done.insert(span);
79 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
80 if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) {
81 let span = expr.span.ctxt().outer_expn_data().call_site;
82 emit_help(cx, snip, braces, name, span);
83 self.done.insert(span);
87 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
88 if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) {
89 let span = ty.span.ctxt().outer_expn_data().call_site;
90 emit_help(cx, snip, braces, name, span);
91 self.done.insert(span);
96 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
97 let unnested_or_local = || {
98 !span.ctxt().outer_expn_data().call_site.from_expansion()
102 .map_or(false, |e| e.macro_def_id.map_or(false, DefId::is_local))
105 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = span.ctxt().outer_expn_data().kind;
106 let name = &*mac_name.as_str();
107 if let Some(braces) = mac_braces.macro_braces.get(name);
108 if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
109 // we must check only invocation sites
110 // https://github.com/rust-lang/rust-clippy/issues/7422
111 if snip.starts_with(&format!("{}!", name));
112 if unnested_or_local();
113 // make formatting consistent
114 let c = snip.replace(" ", "");
115 if !c.starts_with(&format!("{}!{}", name, braces.0));
116 if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
118 Some((mac_name, braces, snip))
125 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: Symbol, span: Span) {
126 let with_space = &format!("! {}", braces.0);
127 let without_space = &format!("!{}", braces.0);
129 for b in BRACES.iter().filter(|b| b.0 != braces.0) {
130 help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
131 // Only `{` traditionally has space before the brace
132 if braces.0 != "{" && help.contains(with_space) {
133 help = help.replace(with_space, without_space);
134 } else if braces.0 == "{" && help.contains(without_space) {
135 help = help.replace(without_space, with_space);
140 NONSTANDARD_MACRO_BRACES,
142 &format!("use of irregular braces for `{}!` macro", name),
144 &format!("consider writing `{}`", help),
148 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
149 let mut braces = vec![
188 .collect::<FxHashMap<_, _>>();
189 // We want users items to override any existing items
191 braces.insert(it.name, it.braces);
196 macro_rules! macro_matcher {
197 (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
198 ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
201 pub(crate) use macro_matcher;
203 #[derive(Clone, Debug)]
204 pub struct MacroMatcher {
206 braces: (String, String),
209 impl Hash for MacroMatcher {
210 fn hash<H: Hasher>(&self, state: &mut H) {
211 self.name.hash(state);
215 impl PartialEq for MacroMatcher {
216 fn eq(&self, other: &Self) -> bool {
217 self.name == other.name
220 impl Eq for MacroMatcher {}
222 impl<'de> Deserialize<'de> for MacroMatcher {
223 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
225 D: de::Deserializer<'de>,
227 #[derive(Deserialize)]
228 #[serde(field_identifier, rename_all = "lowercase")]
234 impl<'de> de::Visitor<'de> for MacVisitor {
235 type Value = MacroMatcher;
237 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
238 formatter.write_str("struct MacroMatcher")
241 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
243 V: de::MapAccess<'de>,
246 let mut brace: Option<&str> = None;
247 while let Some(key) = map.next_key()? {
251 return Err(de::Error::duplicate_field("name"));
253 name = Some(map.next_value()?);
257 return Err(de::Error::duplicate_field("brace"));
259 brace = Some(map.next_value()?);
263 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
264 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
269 .find(|b| b.0 == brace)
270 .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
272 de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
278 const FIELDS: &[&str] = &["name", "brace"];
279 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)