6 use clippy_utils::diagnostics::span_lint_and_sugg;
7 use clippy_utils::source::snippet_opt;
8 use if_chain::if_chain;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::Applicability;
12 use rustc_hir::def_id::DefId;
13 use rustc_lint::{EarlyContext, EarlyLintPass};
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
15 use rustc_span::hygiene::{ExpnKind, MacroKind};
17 use serde::{de, Deserialize};
19 declare_clippy_lint! {
21 /// Checks that common macros are used with consistent bracing.
23 /// ### Why is this bad?
24 /// This is mostly a consistency lint although using () or []
25 /// doesn't give you a semicolon in item position, which can be unexpected.
35 #[clippy::version = "1.55.0"]
36 pub NONSTANDARD_MACRO_BRACES,
38 "check consistent use of braces in macro"
41 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
43 /// The (callsite span, (open brace, close brace), source snippet)
44 type MacroInfo<'a> = (Span, &'a (String, String), String);
46 #[derive(Clone, Debug, Default)]
47 pub struct MacroBraces {
48 macro_braces: FxHashMap<String, (String, String)>,
49 done: FxHashSet<Span>,
53 pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
54 let macro_braces = macro_braces(conf.clone());
57 done: FxHashSet::default(),
62 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
64 impl EarlyLintPass for MacroBraces {
65 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
66 if let Some((span, braces, snip)) = is_offending_macro(cx, item.span, self) {
67 emit_help(cx, &snip, braces, span);
68 self.done.insert(span);
72 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
73 if let Some((span, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
74 emit_help(cx, &snip, braces, span);
75 self.done.insert(span);
79 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
80 if let Some((span, braces, snip)) = is_offending_macro(cx, expr.span, self) {
81 emit_help(cx, &snip, braces, span);
82 self.done.insert(span);
86 fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
87 if let Some((span, braces, snip)) = is_offending_macro(cx, ty.span, self) {
88 emit_help(cx, &snip, braces, 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 !span.ctxt().outer_expn_data().call_site.from_expansion()
100 .map_or(false, |e| e.macro_def_id.map_or(false, DefId::is_local))
102 let span_call_site = span.ctxt().outer_expn_data().call_site;
104 if let ExpnKind::Macro(MacroKind::Bang, mac_name) = span.ctxt().outer_expn_data().kind;
105 let name = mac_name.as_str();
106 if let Some(braces) = mac_braces.macro_braces.get(name);
107 if let Some(snip) = snippet_opt(cx, span_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_call_site);
117 Some((span_call_site, braces, snip))
124 fn emit_help(cx: &EarlyContext<'_>, snip: &str, braces: &(String, String), span: Span) {
125 if let Some((macro_name, macro_args_str)) = snip.split_once('!') {
126 let mut macro_args = macro_args_str.trim().to_string();
127 // now remove the wrong braces
128 macro_args.remove(0);
132 NONSTANDARD_MACRO_BRACES,
134 &format!("use of irregular braces for `{macro_name}!` macro"),
136 format!("{macro_name}!{}{macro_args}{}", braces.0, braces.1),
137 Applicability::MachineApplicable,
142 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
143 let mut braces = vec![
186 .collect::<FxHashMap<_, _>>();
187 // We want users items to override any existing items
189 braces.insert(it.name, it.braces);
194 macro_rules! macro_matcher {
195 (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
196 ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
199 pub(crate) use macro_matcher;
201 #[derive(Clone, Debug)]
202 pub struct MacroMatcher {
204 braces: (String, String),
207 impl Hash for MacroMatcher {
208 fn hash<H: Hasher>(&self, state: &mut H) {
209 self.name.hash(state);
213 impl PartialEq for MacroMatcher {
214 fn eq(&self, other: &Self) -> bool {
215 self.name == other.name
218 impl Eq for MacroMatcher {}
220 impl<'de> Deserialize<'de> for MacroMatcher {
221 fn deserialize<D>(deser: D) -> Result<Self, D::Error>
223 D: de::Deserializer<'de>,
225 #[derive(Deserialize)]
226 #[serde(field_identifier, rename_all = "lowercase")]
232 impl<'de> de::Visitor<'de> for MacVisitor {
233 type Value = MacroMatcher;
235 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
236 formatter.write_str("struct MacroMatcher")
239 fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
241 V: de::MapAccess<'de>,
244 let mut brace: Option<&str> = None;
245 while let Some(key) = map.next_key()? {
249 return Err(de::Error::duplicate_field("name"));
251 name = Some(map.next_value()?);
255 return Err(de::Error::duplicate_field("brace"));
257 brace = Some(map.next_value()?);
261 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
262 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
267 .find(|b| b.0 == brace)
268 .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
269 .ok_or_else(|| de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{brace}`")))?,
274 const FIELDS: &[&str] = &["name", "brace"];
275 deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)