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