]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/nonstandard_macro_braces.rs
Lint inside macro when owned by current crate
[rust.git] / clippy_lints / src / nonstandard_macro_braces.rs
1 use std::{
2     fmt,
3     hash::{Hash, Hasher},
4 };
5
6 use clippy_utils::{diagnostics::span_lint_and_help, in_macro, is_direct_expn_of, source::snippet_opt};
7 use if_chain::if_chain;
8 use rustc_ast::ast;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_lint::{EarlyContext, EarlyLintPass};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::Span;
13 use serde::{de, Deserialize};
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks that common macros are used with consistent bracing.
17     ///
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.
20     ///
21     /// **Known problems:**
22     /// None
23     ///
24     /// **Example:**
25     ///
26     /// ```rust
27     /// vec!{1, 2, 3};
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// vec![1, 2, 3];
32     /// ```
33     pub NONSTANDARD_MACRO_BRACES,
34     nursery,
35     "check consistent use of braces in macro"
36 }
37
38 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
39
40 /// The (name, (open brace, close brace), source snippet)
41 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
42
43 #[derive(Clone, Debug, Default)]
44 pub struct MacroBraces {
45     macro_braces: FxHashMap<String, (String, String)>,
46     done: FxHashSet<Span>,
47 }
48
49 impl MacroBraces {
50     pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
51         let macro_braces = macro_braces(conf.clone());
52         Self {
53             macro_braces,
54             done: FxHashSet::default(),
55         }
56     }
57 }
58
59 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
60
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);
67         }
68     }
69
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);
75         }
76     }
77
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);
83         }
84     }
85
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);
91         }
92     }
93 }
94
95 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
96     let unnested_or_local = || {
97         let nested = in_macro(span.ctxt().outer_expn_data().call_site);
98         let in_local_macro = nested
99             && matches!(span.macro_backtrace().last().and_then(|e| e.macro_def_id), Some(defid) if defid.is_local());
100         !nested || in_local_macro
101     };
102     if_chain! {
103         // Make sure we are only one level deep otherwise there are to many FP's
104         if in_macro(span);
105         if let Some((name, braces)) = find_matching_macro(span, &mac_braces.macro_braces);
106         if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
107         // we must check only invocation sites
108         // https://github.com/rust-lang/rust-clippy/issues/7422
109         if snip.starts_with(&format!("{}!", name));
110         if unnested_or_local();
111         // make formatting consistent
112         let c = snip.replace(" ", "");
113         if !c.starts_with(&format!("{}!{}", name, braces.0));
114         if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
115         then {
116             Some((name, braces, snip))
117         } else {
118             None
119         }
120     }
121 }
122
123 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) {
124     let with_space = &format!("! {}", braces.0);
125     let without_space = &format!("!{}", braces.0);
126     let mut help = snip;
127     for b in BRACES.iter().filter(|b| b.0 != braces.0) {
128         help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
129         // Only `{` traditionally has space before the brace
130         if braces.0 != "{" && help.contains(with_space) {
131             help = help.replace(with_space, without_space);
132         } else if braces.0 == "{" && help.contains(without_space) {
133             help = help.replace(without_space, with_space);
134         }
135     }
136     span_lint_and_help(
137         cx,
138         NONSTANDARD_MACRO_BRACES,
139         span,
140         &format!("use of irregular braces for `{}!` macro", name),
141         Some(span),
142         &format!("consider writing `{}`", help),
143     );
144 }
145
146 fn find_matching_macro(
147     span: Span,
148     braces: &FxHashMap<String, (String, String)>,
149 ) -> Option<(&String, &(String, String))> {
150     braces
151         .iter()
152         .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
153 }
154
155 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
156     let mut braces = vec![
157         macro_matcher!(
158             name: "print",
159             braces: ("(", ")"),
160         ),
161         macro_matcher!(
162             name: "println",
163             braces: ("(", ")"),
164         ),
165         macro_matcher!(
166             name: "eprint",
167             braces: ("(", ")"),
168         ),
169         macro_matcher!(
170             name: "eprintln",
171             braces: ("(", ")"),
172         ),
173         macro_matcher!(
174             name: "write",
175             braces: ("(", ")"),
176         ),
177         macro_matcher!(
178             name: "writeln",
179             braces: ("(", ")"),
180         ),
181         macro_matcher!(
182             name: "format",
183             braces: ("(", ")"),
184         ),
185         macro_matcher!(
186             name: "format_args",
187             braces: ("(", ")"),
188         ),
189         macro_matcher!(
190             name: "vec",
191             braces: ("[", "]"),
192         ),
193     ]
194     .into_iter()
195     .collect::<FxHashMap<_, _>>();
196     // We want users items to override any existing items
197     for it in conf {
198         braces.insert(it.name, it.braces);
199     }
200     braces
201 }
202
203 macro_rules! macro_matcher {
204     (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
205         ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
206     };
207 }
208 pub(crate) use macro_matcher;
209
210 #[derive(Clone, Debug)]
211 pub struct MacroMatcher {
212     name: String,
213     braces: (String, String),
214 }
215
216 impl Hash for MacroMatcher {
217     fn hash<H: Hasher>(&self, state: &mut H) {
218         self.name.hash(state);
219     }
220 }
221
222 impl PartialEq for MacroMatcher {
223     fn eq(&self, other: &Self) -> bool {
224         self.name == other.name
225     }
226 }
227 impl Eq for MacroMatcher {}
228
229 impl<'de> Deserialize<'de> for MacroMatcher {
230     fn deserialize<D>(deser: D) -> Result<Self, D::Error>
231     where
232         D: de::Deserializer<'de>,
233     {
234         #[derive(Deserialize)]
235         #[serde(field_identifier, rename_all = "lowercase")]
236         enum Field {
237             Name,
238             Brace,
239         }
240         struct MacVisitor;
241         impl<'de> de::Visitor<'de> for MacVisitor {
242             type Value = MacroMatcher;
243
244             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
245                 formatter.write_str("struct MacroMatcher")
246             }
247
248             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
249             where
250                 V: de::MapAccess<'de>,
251             {
252                 let mut name = None;
253                 let mut brace: Option<&str> = None;
254                 while let Some(key) = map.next_key()? {
255                     match key {
256                         Field::Name => {
257                             if name.is_some() {
258                                 return Err(de::Error::duplicate_field("name"));
259                             }
260                             name = Some(map.next_value()?);
261                         },
262                         Field::Brace => {
263                             if brace.is_some() {
264                                 return Err(de::Error::duplicate_field("brace"));
265                             }
266                             brace = Some(map.next_value()?);
267                         },
268                     }
269                 }
270                 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
271                 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
272                 Ok(MacroMatcher {
273                     name,
274                     braces: BRACES
275                         .iter()
276                         .find(|b| b.0 == brace)
277                         .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
278                         .ok_or_else(|| {
279                             de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
280                         })?,
281                 })
282             }
283         }
284
285         const FIELDS: &[&str] = &["name", "brace"];
286         deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)
287     }
288 }