]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/nonstandard_macro_braces.rs
Auto merge of #7503 - flip1995:rustup, r=flip1995
[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
17     /// Checks that common macros are used with consistent bracing.
18     ///
19     /// ### Why is this bad?
20     /// This is mostly a consistency lint although using () or []
21     /// doesn't give you a semicolon in item position, which can be unexpected.
22     ///
23     /// ### Example
24     /// ```rust
25     /// vec!{1, 2, 3};
26     /// ```
27     /// Use instead:
28     /// ```rust
29     /// vec![1, 2, 3];
30     /// ```
31     pub NONSTANDARD_MACRO_BRACES,
32     nursery,
33     "check consistent use of braces in macro"
34 }
35
36 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
37
38 /// The (name, (open brace, close brace), source snippet)
39 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
40
41 #[derive(Clone, Debug, Default)]
42 pub struct MacroBraces {
43     macro_braces: FxHashMap<String, (String, String)>,
44     done: FxHashSet<Span>,
45 }
46
47 impl MacroBraces {
48     pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
49         let macro_braces = macro_braces(conf.clone());
50         Self {
51             macro_braces,
52             done: FxHashSet::default(),
53         }
54     }
55 }
56
57 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
58
59 impl EarlyLintPass for MacroBraces {
60     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
61         if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) {
62             let span = item.span.ctxt().outer_expn_data().call_site;
63             emit_help(cx, snip, braces, name, span);
64             self.done.insert(span);
65         }
66     }
67
68     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
69         if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
70             let span = stmt.span.ctxt().outer_expn_data().call_site;
71             emit_help(cx, snip, braces, name, span);
72             self.done.insert(span);
73         }
74     }
75
76     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
77         if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) {
78             let span = expr.span.ctxt().outer_expn_data().call_site;
79             emit_help(cx, snip, braces, name, span);
80             self.done.insert(span);
81         }
82     }
83
84     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
85         if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) {
86             let span = ty.span.ctxt().outer_expn_data().call_site;
87             emit_help(cx, snip, braces, name, span);
88             self.done.insert(span);
89         }
90     }
91 }
92
93 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
94     if_chain! {
95         if in_macro(span);
96         if let Some((name, braces)) = find_matching_macro(span, &mac_braces.macro_braces);
97         if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
98         // we must check only invocation sites
99         // https://github.com/rust-lang/rust-clippy/issues/7422
100         if snip.starts_with(name);
101         // make formatting consistent
102         let c = snip.replace(" ", "");
103         if !c.starts_with(&format!("{}!{}", name, braces.0));
104         if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
105         then {
106             Some((name, braces, snip))
107         } else {
108             None
109         }
110     }
111 }
112
113 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) {
114     let with_space = &format!("! {}", braces.0);
115     let without_space = &format!("!{}", braces.0);
116     let mut help = snip;
117     for b in BRACES.iter().filter(|b| b.0 != braces.0) {
118         help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
119         // Only `{` traditionally has space before the brace
120         if braces.0 != "{" && help.contains(with_space) {
121             help = help.replace(with_space, without_space);
122         } else if braces.0 == "{" && help.contains(without_space) {
123             help = help.replace(without_space, with_space);
124         }
125     }
126     span_lint_and_help(
127         cx,
128         NONSTANDARD_MACRO_BRACES,
129         span,
130         &format!("use of irregular braces for `{}!` macro", name),
131         Some(span),
132         &format!("consider writing `{}`", help),
133     );
134 }
135
136 fn find_matching_macro(
137     span: Span,
138     braces: &FxHashMap<String, (String, String)>,
139 ) -> Option<(&String, &(String, String))> {
140     braces
141         .iter()
142         .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
143 }
144
145 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
146     let mut braces = vec![
147         macro_matcher!(
148             name: "print",
149             braces: ("(", ")"),
150         ),
151         macro_matcher!(
152             name: "println",
153             braces: ("(", ")"),
154         ),
155         macro_matcher!(
156             name: "eprint",
157             braces: ("(", ")"),
158         ),
159         macro_matcher!(
160             name: "eprintln",
161             braces: ("(", ")"),
162         ),
163         macro_matcher!(
164             name: "write",
165             braces: ("(", ")"),
166         ),
167         macro_matcher!(
168             name: "writeln",
169             braces: ("(", ")"),
170         ),
171         macro_matcher!(
172             name: "format",
173             braces: ("(", ")"),
174         ),
175         macro_matcher!(
176             name: "format_args",
177             braces: ("(", ")"),
178         ),
179         macro_matcher!(
180             name: "vec",
181             braces: ("[", "]"),
182         ),
183     ]
184     .into_iter()
185     .collect::<FxHashMap<_, _>>();
186     // We want users items to override any existing items
187     for it in conf {
188         braces.insert(it.name, it.braces);
189     }
190     braces
191 }
192
193 macro_rules! macro_matcher {
194     (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
195         ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
196     };
197 }
198 pub(crate) use macro_matcher;
199
200 #[derive(Clone, Debug)]
201 pub struct MacroMatcher {
202     name: String,
203     braces: (String, String),
204 }
205
206 impl Hash for MacroMatcher {
207     fn hash<H: Hasher>(&self, state: &mut H) {
208         self.name.hash(state);
209     }
210 }
211
212 impl PartialEq for MacroMatcher {
213     fn eq(&self, other: &Self) -> bool {
214         self.name == other.name
215     }
216 }
217 impl Eq for MacroMatcher {}
218
219 impl<'de> Deserialize<'de> for MacroMatcher {
220     fn deserialize<D>(deser: D) -> Result<Self, D::Error>
221     where
222         D: de::Deserializer<'de>,
223     {
224         #[derive(Deserialize)]
225         #[serde(field_identifier, rename_all = "lowercase")]
226         enum Field {
227             Name,
228             Brace,
229         }
230         struct MacVisitor;
231         impl<'de> de::Visitor<'de> for MacVisitor {
232             type Value = MacroMatcher;
233
234             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
235                 formatter.write_str("struct MacroMatcher")
236             }
237
238             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
239             where
240                 V: de::MapAccess<'de>,
241             {
242                 let mut name = None;
243                 let mut brace: Option<&str> = None;
244                 while let Some(key) = map.next_key()? {
245                     match key {
246                         Field::Name => {
247                             if name.is_some() {
248                                 return Err(de::Error::duplicate_field("name"));
249                             }
250                             name = Some(map.next_value()?);
251                         },
252                         Field::Brace => {
253                             if brace.is_some() {
254                                 return Err(de::Error::duplicate_field("brace"));
255                             }
256                             brace = Some(map.next_value()?);
257                         },
258                     }
259                 }
260                 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
261                 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
262                 Ok(MacroMatcher {
263                     name,
264                     braces: BRACES
265                         .iter()
266                         .find(|b| b.0 == brace)
267                         .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
268                         .ok_or_else(|| {
269                             de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
270                         })?,
271                 })
272             }
273         }
274
275         const FIELDS: &[&str] = &["name", "brace"];
276         deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)
277     }
278 }