]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/internal_lints.rs
Auto merge of #83870 - jackh726:binder-refactor-fix, r=nikomatsakis
[rust.git] / src / tools / clippy / clippy_lints / src / utils / internal_lints.rs
1 use crate::consts::{constant_simple, Constant};
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
3 use clippy_utils::source::snippet;
4 use clippy_utils::ty::match_type;
5 use clippy_utils::{
6     is_else_clause, is_expn_of, match_def_path, match_qpath, method_calls, path_to_res, paths, run_lints, SpanlessEq,
7 };
8 use if_chain::if_chain;
9 use rustc_ast::ast::{Crate as AstCrate, ItemKind, LitKind, ModKind, NodeId};
10 use rustc_ast::visit::FnKind;
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_errors::Applicability;
13 use rustc_hir as hir;
14 use rustc_hir::def::{DefKind, Res};
15 use rustc_hir::def_id::DefId;
16 use rustc_hir::hir_id::CRATE_HIR_ID;
17 use rustc_hir::intravisit::{NestedVisitorMap, Visitor};
18 use rustc_hir::{
19     BinOpKind, Block, Crate, Expr, ExprKind, HirId, Item, Local, MatchSource, MutTy, Mutability, Node, Path, Stmt,
20     StmtKind, Ty, TyKind, UnOp,
21 };
22 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
23 use rustc_middle::hir::map::Map;
24 use rustc_middle::mir::interpret::ConstValue;
25 use rustc_middle::ty;
26 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
27 use rustc_span::source_map::Spanned;
28 use rustc_span::symbol::{Symbol, SymbolStr};
29 use rustc_span::{BytePos, Span};
30 use rustc_typeck::hir_ty_to_ty;
31
32 use std::borrow::{Borrow, Cow};
33
34 declare_clippy_lint! {
35     /// **What it does:** Checks for various things we like to keep tidy in clippy.
36     ///
37     /// **Why is this bad?** We like to pretend we're an example of tidy code.
38     ///
39     /// **Known problems:** None.
40     ///
41     /// **Example:** Wrong ordering of the util::paths constants.
42     pub CLIPPY_LINTS_INTERNAL,
43     internal,
44     "various things that will negatively affect your clippy experience"
45 }
46
47 declare_clippy_lint! {
48     /// **What it does:** Ensures every lint is associated to a `LintPass`.
49     ///
50     /// **Why is this bad?** The compiler only knows lints via a `LintPass`. Without
51     /// putting a lint to a `LintPass::get_lints()`'s return, the compiler will not
52     /// know the name of the lint.
53     ///
54     /// **Known problems:** Only checks for lints associated using the
55     /// `declare_lint_pass!`, `impl_lint_pass!`, and `lint_array!` macros.
56     ///
57     /// **Example:**
58     /// ```rust,ignore
59     /// declare_lint! { pub LINT_1, ... }
60     /// declare_lint! { pub LINT_2, ... }
61     /// declare_lint! { pub FORGOTTEN_LINT, ... }
62     /// // ...
63     /// declare_lint_pass!(Pass => [LINT_1, LINT_2]);
64     /// // missing FORGOTTEN_LINT
65     /// ```
66     pub LINT_WITHOUT_LINT_PASS,
67     internal,
68     "declaring a lint without associating it in a LintPass"
69 }
70
71 declare_clippy_lint! {
72     /// **What it does:** Checks for calls to `cx.span_lint*` and suggests to use the `utils::*`
73     /// variant of the function.
74     ///
75     /// **Why is this bad?** The `utils::*` variants also add a link to the Clippy documentation to the
76     /// warning/error messages.
77     ///
78     /// **Known problems:** None.
79     ///
80     /// **Example:**
81     /// Bad:
82     /// ```rust,ignore
83     /// cx.span_lint(LINT_NAME, "message");
84     /// ```
85     ///
86     /// Good:
87     /// ```rust,ignore
88     /// utils::span_lint(cx, LINT_NAME, "message");
89     /// ```
90     pub COMPILER_LINT_FUNCTIONS,
91     internal,
92     "usage of the lint functions of the compiler instead of the utils::* variant"
93 }
94
95 declare_clippy_lint! {
96     /// **What it does:** Checks for calls to `cx.outer().expn_data()` and suggests to use
97     /// the `cx.outer_expn_data()`
98     ///
99     /// **Why is this bad?** `cx.outer_expn_data()` is faster and more concise.
100     ///
101     /// **Known problems:** None.
102     ///
103     /// **Example:**
104     /// Bad:
105     /// ```rust,ignore
106     /// expr.span.ctxt().outer().expn_data()
107     /// ```
108     ///
109     /// Good:
110     /// ```rust,ignore
111     /// expr.span.ctxt().outer_expn_data()
112     /// ```
113     pub OUTER_EXPN_EXPN_DATA,
114     internal,
115     "using `cx.outer_expn().expn_data()` instead of `cx.outer_expn_data()`"
116 }
117
118 declare_clippy_lint! {
119     /// **What it does:** Not an actual lint. This lint is only meant for testing our customized internal compiler
120     /// error message by calling `panic`.
121     ///
122     /// **Why is this bad?** ICE in large quantities can damage your teeth
123     ///
124     /// **Known problems:** None
125     ///
126     /// **Example:**
127     /// Bad:
128     /// ```rust,ignore
129     /// 🍦🍦🍦🍦🍦
130     /// ```
131     pub PRODUCE_ICE,
132     internal,
133     "this message should not appear anywhere as we ICE before and don't emit the lint"
134 }
135
136 declare_clippy_lint! {
137     /// **What it does:** Checks for cases of an auto-generated lint without an updated description,
138     /// i.e. `default lint description`.
139     ///
140     /// **Why is this bad?** Indicates that the lint is not finished.
141     ///
142     /// **Known problems:** None
143     ///
144     /// **Example:**
145     /// Bad:
146     /// ```rust,ignore
147     /// declare_lint! { pub COOL_LINT, nursery, "default lint description" }
148     /// ```
149     ///
150     /// Good:
151     /// ```rust,ignore
152     /// declare_lint! { pub COOL_LINT, nursery, "a great new lint" }
153     /// ```
154     pub DEFAULT_LINT,
155     internal,
156     "found 'default lint description' in a lint declaration"
157 }
158
159 declare_clippy_lint! {
160     /// **What it does:** Lints `span_lint_and_then` function calls, where the
161     /// closure argument has only one statement and that statement is a method
162     /// call to `span_suggestion`, `span_help`, `span_note` (using the same
163     /// span), `help` or `note`.
164     ///
165     /// These usages of `span_lint_and_then` should be replaced with one of the
166     /// wrapper functions `span_lint_and_sugg`, span_lint_and_help`, or
167     /// `span_lint_and_note`.
168     ///
169     /// **Why is this bad?** Using the wrapper `span_lint_and_*` functions, is more
170     /// convenient, readable and less error prone.
171     ///
172     /// **Known problems:** None
173     ///
174     /// *Example:**
175     /// Bad:
176     /// ```rust,ignore
177     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
178     ///     diag.span_suggestion(
179     ///         expr.span,
180     ///         help_msg,
181     ///         sugg.to_string(),
182     ///         Applicability::MachineApplicable,
183     ///     );
184     /// });
185     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
186     ///     diag.span_help(expr.span, help_msg);
187     /// });
188     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
189     ///     diag.help(help_msg);
190     /// });
191     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
192     ///     diag.span_note(expr.span, note_msg);
193     /// });
194     /// span_lint_and_then(cx, TEST_LINT, expr.span, lint_msg, |diag| {
195     ///     diag.note(note_msg);
196     /// });
197     /// ```
198     ///
199     /// Good:
200     /// ```rust,ignore
201     /// span_lint_and_sugg(
202     ///     cx,
203     ///     TEST_LINT,
204     ///     expr.span,
205     ///     lint_msg,
206     ///     help_msg,
207     ///     sugg.to_string(),
208     ///     Applicability::MachineApplicable,
209     /// );
210     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), help_msg);
211     /// span_lint_and_help(cx, TEST_LINT, expr.span, lint_msg, None, help_msg);
212     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, Some(expr.span), note_msg);
213     /// span_lint_and_note(cx, TEST_LINT, expr.span, lint_msg, None, note_msg);
214     /// ```
215     pub COLLAPSIBLE_SPAN_LINT_CALLS,
216     internal,
217     "found collapsible `span_lint_and_then` calls"
218 }
219
220 declare_clippy_lint! {
221     /// **What it does:** Checks for calls to `utils::match_type()` on a type diagnostic item
222     /// and suggests to use `utils::is_type_diagnostic_item()` instead.
223     ///
224     /// **Why is this bad?** `utils::is_type_diagnostic_item()` does not require hardcoded paths.
225     ///
226     /// **Known problems:** None.
227     ///
228     /// **Example:**
229     /// Bad:
230     /// ```rust,ignore
231     /// utils::match_type(cx, ty, &paths::VEC)
232     /// ```
233     ///
234     /// Good:
235     /// ```rust,ignore
236     /// utils::is_type_diagnostic_item(cx, ty, sym::vec_type)
237     /// ```
238     pub MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
239     internal,
240     "using `utils::match_type()` instead of `utils::is_type_diagnostic_item()`"
241 }
242
243 declare_clippy_lint! {
244     /// **What it does:**
245     /// Checks the paths module for invalid paths.
246     ///
247     /// **Why is this bad?**
248     /// It indicates a bug in the code.
249     ///
250     /// **Known problems:** None.
251     ///
252     /// **Example:** None.
253     pub INVALID_PATHS,
254     internal,
255     "invalid path"
256 }
257
258 declare_clippy_lint! {
259     /// **What it does:**
260     /// Checks for interning symbols that have already been pre-interned and defined as constants.
261     ///
262     /// **Why is this bad?**
263     /// It's faster and easier to use the symbol constant.
264     ///
265     /// **Known problems:** None.
266     ///
267     /// **Example:**
268     /// Bad:
269     /// ```rust,ignore
270     /// let _ = sym!(f32);
271     /// ```
272     ///
273     /// Good:
274     /// ```rust,ignore
275     /// let _ = sym::f32;
276     /// ```
277     pub INTERNING_DEFINED_SYMBOL,
278     internal,
279     "interning a symbol that is pre-interned and defined as a constant"
280 }
281
282 declare_clippy_lint! {
283     /// **What it does:** Checks for unnecessary conversion from Symbol to a string.
284     ///
285     /// **Why is this bad?** It's faster use symbols directly intead of strings.
286     ///
287     /// **Known problems:** None.
288     ///
289     /// **Example:**
290     /// Bad:
291     /// ```rust,ignore
292     /// symbol.as_str() == "clippy";
293     /// ```
294     ///
295     /// Good:
296     /// ```rust,ignore
297     /// symbol == sym::clippy;
298     /// ```
299     pub UNNECESSARY_SYMBOL_STR,
300     internal,
301     "unnecessary conversion between Symbol and string"
302 }
303
304 declare_clippy_lint! {
305     /// Finds unidiomatic usage of `if_chain!`
306     pub IF_CHAIN_STYLE,
307     internal,
308     "non-idiomatic `if_chain!` usage"
309 }
310
311 declare_lint_pass!(ClippyLintsInternal => [CLIPPY_LINTS_INTERNAL]);
312
313 impl EarlyLintPass for ClippyLintsInternal {
314     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &AstCrate) {
315         if let Some(utils) = krate.items.iter().find(|item| item.ident.name.as_str() == "utils") {
316             if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = utils.kind {
317                 if let Some(paths) = items.iter().find(|item| item.ident.name.as_str() == "paths") {
318                     if let ItemKind::Mod(_, ModKind::Loaded(ref items, ..)) = paths.kind {
319                         let mut last_name: Option<SymbolStr> = None;
320                         for item in items {
321                             let name = item.ident.as_str();
322                             if let Some(ref last_name) = last_name {
323                                 if **last_name > *name {
324                                     span_lint(
325                                         cx,
326                                         CLIPPY_LINTS_INTERNAL,
327                                         item.span,
328                                         "this constant should be before the previous constant due to lexical \
329                                          ordering",
330                                     );
331                                 }
332                             }
333                             last_name = Some(name);
334                         }
335                     }
336                 }
337             }
338         }
339     }
340 }
341
342 #[derive(Clone, Debug, Default)]
343 pub struct LintWithoutLintPass {
344     declared_lints: FxHashMap<Symbol, Span>,
345     registered_lints: FxHashSet<Symbol>,
346 }
347
348 impl_lint_pass!(LintWithoutLintPass => [DEFAULT_LINT, LINT_WITHOUT_LINT_PASS]);
349
350 impl<'tcx> LateLintPass<'tcx> for LintWithoutLintPass {
351     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
352         if !run_lints(cx, &[DEFAULT_LINT], item.hir_id()) {
353             return;
354         }
355
356         if let hir::ItemKind::Static(ty, Mutability::Not, body_id) = item.kind {
357             if is_lint_ref_type(cx, ty) {
358                 let expr = &cx.tcx.hir().body(body_id).value;
359                 if_chain! {
360                     if let ExprKind::AddrOf(_, _, inner_exp) = expr.kind;
361                     if let ExprKind::Struct(_, fields, _) = inner_exp.kind;
362                     let field = fields
363                         .iter()
364                         .find(|f| f.ident.as_str() == "desc")
365                         .expect("lints must have a description field");
366                     if let ExprKind::Lit(Spanned {
367                         node: LitKind::Str(ref sym, _),
368                         ..
369                     }) = field.expr.kind;
370                     if sym.as_str() == "default lint description";
371
372                     then {
373                         span_lint(
374                             cx,
375                             DEFAULT_LINT,
376                             item.span,
377                             &format!("the lint `{}` has the default lint description", item.ident.name),
378                         );
379                     }
380                 }
381                 self.declared_lints.insert(item.ident.name, item.span);
382             }
383         } else if is_expn_of(item.span, "impl_lint_pass").is_some()
384             || is_expn_of(item.span, "declare_lint_pass").is_some()
385         {
386             if let hir::ItemKind::Impl(hir::Impl {
387                 of_trait: None,
388                 items: impl_item_refs,
389                 ..
390             }) = item.kind
391             {
392                 let mut collector = LintCollector {
393                     output: &mut self.registered_lints,
394                     cx,
395                 };
396                 let body_id = cx.tcx.hir().body_owned_by(
397                     impl_item_refs
398                         .iter()
399                         .find(|iiref| iiref.ident.as_str() == "get_lints")
400                         .expect("LintPass needs to implement get_lints")
401                         .id
402                         .hir_id(),
403                 );
404                 collector.visit_expr(&cx.tcx.hir().body(body_id).value);
405             }
406         }
407     }
408
409     fn check_crate_post(&mut self, cx: &LateContext<'tcx>, _: &'tcx Crate<'_>) {
410         if !run_lints(cx, &[LINT_WITHOUT_LINT_PASS], CRATE_HIR_ID) {
411             return;
412         }
413
414         for (lint_name, &lint_span) in &self.declared_lints {
415             // When using the `declare_tool_lint!` macro, the original `lint_span`'s
416             // file points to "<rustc macros>".
417             // `compiletest-rs` thinks that's an error in a different file and
418             // just ignores it. This causes the test in compile-fail/lint_pass
419             // not able to capture the error.
420             // Therefore, we need to climb the macro expansion tree and find the
421             // actual span that invoked `declare_tool_lint!`:
422             let lint_span = lint_span.ctxt().outer_expn_data().call_site;
423
424             if !self.registered_lints.contains(lint_name) {
425                 span_lint(
426                     cx,
427                     LINT_WITHOUT_LINT_PASS,
428                     lint_span,
429                     &format!("the lint `{}` is not added to any `LintPass`", lint_name),
430                 );
431             }
432         }
433     }
434 }
435
436 fn is_lint_ref_type<'tcx>(cx: &LateContext<'tcx>, ty: &Ty<'_>) -> bool {
437     if let TyKind::Rptr(
438         _,
439         MutTy {
440             ty: inner,
441             mutbl: Mutability::Not,
442         },
443     ) = ty.kind
444     {
445         if let TyKind::Path(ref path) = inner.kind {
446             if let Res::Def(DefKind::Struct, def_id) = cx.qpath_res(path, inner.hir_id) {
447                 return match_def_path(cx, def_id, &paths::LINT);
448             }
449         }
450     }
451
452     false
453 }
454
455 struct LintCollector<'a, 'tcx> {
456     output: &'a mut FxHashSet<Symbol>,
457     cx: &'a LateContext<'tcx>,
458 }
459
460 impl<'a, 'tcx> Visitor<'tcx> for LintCollector<'a, 'tcx> {
461     type Map = Map<'tcx>;
462
463     fn visit_path(&mut self, path: &'tcx Path<'_>, _: HirId) {
464         if path.segments.len() == 1 {
465             self.output.insert(path.segments[0].ident.name);
466         }
467     }
468
469     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
470         NestedVisitorMap::All(self.cx.tcx.hir())
471     }
472 }
473
474 #[derive(Clone, Default)]
475 pub struct CompilerLintFunctions {
476     map: FxHashMap<&'static str, &'static str>,
477 }
478
479 impl CompilerLintFunctions {
480     #[must_use]
481     pub fn new() -> Self {
482         let mut map = FxHashMap::default();
483         map.insert("span_lint", "utils::span_lint");
484         map.insert("struct_span_lint", "utils::span_lint");
485         map.insert("lint", "utils::span_lint");
486         map.insert("span_lint_note", "utils::span_lint_and_note");
487         map.insert("span_lint_help", "utils::span_lint_and_help");
488         Self { map }
489     }
490 }
491
492 impl_lint_pass!(CompilerLintFunctions => [COMPILER_LINT_FUNCTIONS]);
493
494 impl<'tcx> LateLintPass<'tcx> for CompilerLintFunctions {
495     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
496         if !run_lints(cx, &[COMPILER_LINT_FUNCTIONS], expr.hir_id) {
497             return;
498         }
499
500         if_chain! {
501             if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
502             let fn_name = path.ident;
503             if let Some(sugg) = self.map.get(&*fn_name.as_str());
504             let ty = cx.typeck_results().expr_ty(&args[0]).peel_refs();
505             if match_type(cx, ty, &paths::EARLY_CONTEXT)
506                 || match_type(cx, ty, &paths::LATE_CONTEXT);
507             then {
508                 span_lint_and_help(
509                     cx,
510                     COMPILER_LINT_FUNCTIONS,
511                     path.ident.span,
512                     "usage of a compiler lint function",
513                     None,
514                     &format!("please use the Clippy variant of this function: `{}`", sugg),
515                 );
516             }
517         }
518     }
519 }
520
521 declare_lint_pass!(OuterExpnDataPass => [OUTER_EXPN_EXPN_DATA]);
522
523 impl<'tcx> LateLintPass<'tcx> for OuterExpnDataPass {
524     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
525         if !run_lints(cx, &[OUTER_EXPN_EXPN_DATA], expr.hir_id) {
526             return;
527         }
528
529         let (method_names, arg_lists, spans) = method_calls(expr, 2);
530         let method_names: Vec<SymbolStr> = method_names.iter().map(|s| s.as_str()).collect();
531         let method_names: Vec<&str> = method_names.iter().map(|s| &**s).collect();
532         if_chain! {
533             if let ["expn_data", "outer_expn"] = method_names.as_slice();
534             let args = arg_lists[1];
535             if args.len() == 1;
536             let self_arg = &args[0];
537             let self_ty = cx.typeck_results().expr_ty(self_arg).peel_refs();
538             if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT);
539             then {
540                 span_lint_and_sugg(
541                     cx,
542                     OUTER_EXPN_EXPN_DATA,
543                     spans[1].with_hi(expr.span.hi()),
544                     "usage of `outer_expn().expn_data()`",
545                     "try",
546                     "outer_expn_data()".to_string(),
547                     Applicability::MachineApplicable,
548                 );
549             }
550         }
551     }
552 }
553
554 declare_lint_pass!(ProduceIce => [PRODUCE_ICE]);
555
556 impl EarlyLintPass for ProduceIce {
557     fn check_fn(&mut self, _: &EarlyContext<'_>, fn_kind: FnKind<'_>, _: Span, _: NodeId) {
558         if is_trigger_fn(fn_kind) {
559             panic!("Would you like some help with that?");
560         }
561     }
562 }
563
564 fn is_trigger_fn(fn_kind: FnKind<'_>) -> bool {
565     match fn_kind {
566         FnKind::Fn(_, ident, ..) => ident.name.as_str() == "it_looks_like_you_are_trying_to_kill_clippy",
567         FnKind::Closure(..) => false,
568     }
569 }
570
571 declare_lint_pass!(CollapsibleCalls => [COLLAPSIBLE_SPAN_LINT_CALLS]);
572
573 impl<'tcx> LateLintPass<'tcx> for CollapsibleCalls {
574     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
575         if !run_lints(cx, &[COLLAPSIBLE_SPAN_LINT_CALLS], expr.hir_id) {
576             return;
577         }
578
579         if_chain! {
580             if let ExprKind::Call(func, and_then_args) = expr.kind;
581             if let ExprKind::Path(ref path) = func.kind;
582             if match_qpath(path, &["span_lint_and_then"]);
583             if and_then_args.len() == 5;
584             if let ExprKind::Closure(_, _, body_id, _, _) = &and_then_args[4].kind;
585             let body = cx.tcx.hir().body(*body_id);
586             if let ExprKind::Block(block, _) = &body.value.kind;
587             let stmts = &block.stmts;
588             if stmts.len() == 1 && block.expr.is_none();
589             if let StmtKind::Semi(only_expr) = &stmts[0].kind;
590             if let ExprKind::MethodCall(ps, _, span_call_args, _) = &only_expr.kind;
591             then {
592                 let and_then_snippets = get_and_then_snippets(cx, and_then_args);
593                 let mut sle = SpanlessEq::new(cx).deny_side_effects();
594                 match &*ps.ident.as_str() {
595                     "span_suggestion" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
596                         suggest_suggestion(cx, expr, &and_then_snippets, &span_suggestion_snippets(cx, span_call_args));
597                     },
598                     "span_help" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
599                         let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
600                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), true);
601                     },
602                     "span_note" if sle.eq_expr(&and_then_args[2], &span_call_args[1]) => {
603                         let note_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
604                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), true);
605                     },
606                     "help" => {
607                         let help_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
608                         suggest_help(cx, expr, &and_then_snippets, help_snippet.borrow(), false);
609                     }
610                     "note" => {
611                         let note_snippet = snippet(cx, span_call_args[1].span, r#""...""#);
612                         suggest_note(cx, expr, &and_then_snippets, note_snippet.borrow(), false);
613                     }
614                     _  => (),
615                 }
616             }
617         }
618     }
619 }
620
621 struct AndThenSnippets<'a> {
622     cx: Cow<'a, str>,
623     lint: Cow<'a, str>,
624     span: Cow<'a, str>,
625     msg: Cow<'a, str>,
626 }
627
628 fn get_and_then_snippets<'a, 'hir>(cx: &LateContext<'_>, and_then_snippets: &'hir [Expr<'hir>]) -> AndThenSnippets<'a> {
629     let cx_snippet = snippet(cx, and_then_snippets[0].span, "cx");
630     let lint_snippet = snippet(cx, and_then_snippets[1].span, "..");
631     let span_snippet = snippet(cx, and_then_snippets[2].span, "span");
632     let msg_snippet = snippet(cx, and_then_snippets[3].span, r#""...""#);
633
634     AndThenSnippets {
635         cx: cx_snippet,
636         lint: lint_snippet,
637         span: span_snippet,
638         msg: msg_snippet,
639     }
640 }
641
642 struct SpanSuggestionSnippets<'a> {
643     help: Cow<'a, str>,
644     sugg: Cow<'a, str>,
645     applicability: Cow<'a, str>,
646 }
647
648 fn span_suggestion_snippets<'a, 'hir>(
649     cx: &LateContext<'_>,
650     span_call_args: &'hir [Expr<'hir>],
651 ) -> SpanSuggestionSnippets<'a> {
652     let help_snippet = snippet(cx, span_call_args[2].span, r#""...""#);
653     let sugg_snippet = snippet(cx, span_call_args[3].span, "..");
654     let applicability_snippet = snippet(cx, span_call_args[4].span, "Applicability::MachineApplicable");
655
656     SpanSuggestionSnippets {
657         help: help_snippet,
658         sugg: sugg_snippet,
659         applicability: applicability_snippet,
660     }
661 }
662
663 fn suggest_suggestion(
664     cx: &LateContext<'_>,
665     expr: &Expr<'_>,
666     and_then_snippets: &AndThenSnippets<'_>,
667     span_suggestion_snippets: &SpanSuggestionSnippets<'_>,
668 ) {
669     span_lint_and_sugg(
670         cx,
671         COLLAPSIBLE_SPAN_LINT_CALLS,
672         expr.span,
673         "this call is collapsible",
674         "collapse into",
675         format!(
676             "span_lint_and_sugg({}, {}, {}, {}, {}, {}, {})",
677             and_then_snippets.cx,
678             and_then_snippets.lint,
679             and_then_snippets.span,
680             and_then_snippets.msg,
681             span_suggestion_snippets.help,
682             span_suggestion_snippets.sugg,
683             span_suggestion_snippets.applicability
684         ),
685         Applicability::MachineApplicable,
686     );
687 }
688
689 fn suggest_help(
690     cx: &LateContext<'_>,
691     expr: &Expr<'_>,
692     and_then_snippets: &AndThenSnippets<'_>,
693     help: &str,
694     with_span: bool,
695 ) {
696     let option_span = if with_span {
697         format!("Some({})", and_then_snippets.span)
698     } else {
699         "None".to_string()
700     };
701
702     span_lint_and_sugg(
703         cx,
704         COLLAPSIBLE_SPAN_LINT_CALLS,
705         expr.span,
706         "this call is collapsible",
707         "collapse into",
708         format!(
709             "span_lint_and_help({}, {}, {}, {}, {}, {})",
710             and_then_snippets.cx,
711             and_then_snippets.lint,
712             and_then_snippets.span,
713             and_then_snippets.msg,
714             &option_span,
715             help
716         ),
717         Applicability::MachineApplicable,
718     );
719 }
720
721 fn suggest_note(
722     cx: &LateContext<'_>,
723     expr: &Expr<'_>,
724     and_then_snippets: &AndThenSnippets<'_>,
725     note: &str,
726     with_span: bool,
727 ) {
728     let note_span = if with_span {
729         format!("Some({})", and_then_snippets.span)
730     } else {
731         "None".to_string()
732     };
733
734     span_lint_and_sugg(
735         cx,
736         COLLAPSIBLE_SPAN_LINT_CALLS,
737         expr.span,
738         "this call is collspible",
739         "collapse into",
740         format!(
741             "span_lint_and_note({}, {}, {}, {}, {}, {})",
742             and_then_snippets.cx,
743             and_then_snippets.lint,
744             and_then_snippets.span,
745             and_then_snippets.msg,
746             note_span,
747             note
748         ),
749         Applicability::MachineApplicable,
750     );
751 }
752
753 declare_lint_pass!(MatchTypeOnDiagItem => [MATCH_TYPE_ON_DIAGNOSTIC_ITEM]);
754
755 impl<'tcx> LateLintPass<'tcx> for MatchTypeOnDiagItem {
756     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
757         if !run_lints(cx, &[MATCH_TYPE_ON_DIAGNOSTIC_ITEM], expr.hir_id) {
758             return;
759         }
760
761         if_chain! {
762             // Check if this is a call to utils::match_type()
763             if let ExprKind::Call(fn_path, [context, ty, ty_path]) = expr.kind;
764             if let ExprKind::Path(fn_qpath) = &fn_path.kind;
765             if match_qpath(fn_qpath, &["utils", "match_type"]);
766             // Extract the path to the matched type
767             if let Some(segments) = path_to_matched_type(cx, ty_path);
768             let segments: Vec<&str> = segments.iter().map(|sym| &**sym).collect();
769             if let Some(ty_did) = path_to_res(cx, &segments[..]).opt_def_id();
770             // Check if the matched type is a diagnostic item
771             let diag_items = cx.tcx.diagnostic_items(ty_did.krate);
772             if let Some(item_name) = diag_items.iter().find_map(|(k, v)| if *v == ty_did { Some(k) } else { None });
773             then {
774                 let cx_snippet = snippet(cx, context.span, "_");
775                 let ty_snippet = snippet(cx, ty.span, "_");
776
777                 span_lint_and_sugg(
778                     cx,
779                     MATCH_TYPE_ON_DIAGNOSTIC_ITEM,
780                     expr.span,
781                     "usage of `utils::match_type()` on a type diagnostic item",
782                     "try",
783                     format!("utils::is_type_diagnostic_item({}, {}, sym::{})", cx_snippet, ty_snippet, item_name),
784                     Applicability::MaybeIncorrect,
785                 );
786             }
787         }
788     }
789 }
790
791 fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Vec<SymbolStr>> {
792     use rustc_hir::ItemKind;
793
794     match &expr.kind {
795         ExprKind::AddrOf(.., expr) => return path_to_matched_type(cx, expr),
796         ExprKind::Path(qpath) => match cx.qpath_res(qpath, expr.hir_id) {
797             Res::Local(hir_id) => {
798                 let parent_id = cx.tcx.hir().get_parent_node(hir_id);
799                 if let Some(Node::Local(local)) = cx.tcx.hir().find(parent_id) {
800                     if let Some(init) = local.init {
801                         return path_to_matched_type(cx, init);
802                     }
803                 }
804             },
805             Res::Def(DefKind::Const | DefKind::Static, def_id) => {
806                 if let Some(Node::Item(item)) = cx.tcx.hir().get_if_local(def_id) {
807                     if let ItemKind::Const(.., body_id) | ItemKind::Static(.., body_id) = item.kind {
808                         let body = cx.tcx.hir().body(body_id);
809                         return path_to_matched_type(cx, &body.value);
810                     }
811                 }
812             },
813             _ => {},
814         },
815         ExprKind::Array(exprs) => {
816             let segments: Vec<SymbolStr> = exprs
817                 .iter()
818                 .filter_map(|expr| {
819                     if let ExprKind::Lit(lit) = &expr.kind {
820                         if let LitKind::Str(sym, _) = lit.node {
821                             return Some(sym.as_str());
822                         }
823                     }
824
825                     None
826                 })
827                 .collect();
828
829             if segments.len() == exprs.len() {
830                 return Some(segments);
831             }
832         },
833         _ => {},
834     }
835
836     None
837 }
838
839 // This is not a complete resolver for paths. It works on all the paths currently used in the paths
840 // module.  That's all it does and all it needs to do.
841 pub fn check_path(cx: &LateContext<'_>, path: &[&str]) -> bool {
842     if path_to_res(cx, path) != Res::Err {
843         return true;
844     }
845
846     // Some implementations can't be found by `path_to_res`, particularly inherent
847     // implementations of native types. Check lang items.
848     let path_syms: Vec<_> = path.iter().map(|p| Symbol::intern(p)).collect();
849     let lang_items = cx.tcx.lang_items();
850     for item_def_id in lang_items.items().iter().flatten() {
851         let lang_item_path = cx.get_def_path(*item_def_id);
852         if path_syms.starts_with(&lang_item_path) {
853             if let [item] = &path_syms[lang_item_path.len()..] {
854                 for child in cx.tcx.item_children(*item_def_id) {
855                     if child.ident.name == *item {
856                         return true;
857                     }
858                 }
859             }
860         }
861     }
862
863     false
864 }
865
866 declare_lint_pass!(InvalidPaths => [INVALID_PATHS]);
867
868 impl<'tcx> LateLintPass<'tcx> for InvalidPaths {
869     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
870         let local_def_id = &cx.tcx.parent_module(item.hir_id());
871         let mod_name = &cx.tcx.item_name(local_def_id.to_def_id());
872         if_chain! {
873             if mod_name.as_str() == "paths";
874             if let hir::ItemKind::Const(ty, body_id) = item.kind;
875             let ty = hir_ty_to_ty(cx.tcx, ty);
876             if let ty::Array(el_ty, _) = &ty.kind();
877             if let ty::Ref(_, el_ty, _) = &el_ty.kind();
878             if el_ty.is_str();
879             let body = cx.tcx.hir().body(body_id);
880             let typeck_results = cx.tcx.typeck_body(body_id);
881             if let Some(Constant::Vec(path)) = constant_simple(cx, typeck_results, &body.value);
882             let path: Vec<&str> = path.iter().map(|x| {
883                     if let Constant::Str(s) = x {
884                         s.as_str()
885                     } else {
886                         // We checked the type of the constant above
887                         unreachable!()
888                     }
889                 }).collect();
890             if !check_path(cx, &path[..]);
891             then {
892                 span_lint(cx, CLIPPY_LINTS_INTERNAL, item.span, "invalid path");
893             }
894         }
895     }
896 }
897
898 #[derive(Default)]
899 pub struct InterningDefinedSymbol {
900     // Maps the symbol value to the constant DefId.
901     symbol_map: FxHashMap<u32, DefId>,
902 }
903
904 impl_lint_pass!(InterningDefinedSymbol => [INTERNING_DEFINED_SYMBOL, UNNECESSARY_SYMBOL_STR]);
905
906 impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol {
907     fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
908         if !self.symbol_map.is_empty() {
909             return;
910         }
911
912         for &module in &[&paths::KW_MODULE, &paths::SYM_MODULE] {
913             if let Some(def_id) = path_to_res(cx, module).opt_def_id() {
914                 for item in cx.tcx.item_children(def_id).iter() {
915                     if_chain! {
916                         if let Res::Def(DefKind::Const, item_def_id) = item.res;
917                         let ty = cx.tcx.type_of(item_def_id);
918                         if match_type(cx, ty, &paths::SYMBOL);
919                         if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id);
920                         if let Ok(value) = value.to_u32();
921                         then {
922                             self.symbol_map.insert(value, item_def_id);
923                         }
924                     }
925                 }
926             }
927         }
928     }
929
930     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
931         if_chain! {
932             if let ExprKind::Call(func, [arg]) = &expr.kind;
933             if let ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(func).kind();
934             if match_def_path(cx, *def_id, &paths::SYMBOL_INTERN);
935             if let Some(Constant::Str(arg)) = constant_simple(cx, cx.typeck_results(), arg);
936             let value = Symbol::intern(&arg).as_u32();
937             if let Some(&def_id) = self.symbol_map.get(&value);
938             then {
939                 span_lint_and_sugg(
940                     cx,
941                     INTERNING_DEFINED_SYMBOL,
942                     is_expn_of(expr.span, "sym").unwrap_or(expr.span),
943                     "interning a defined symbol",
944                     "try",
945                     cx.tcx.def_path_str(def_id),
946                     Applicability::MachineApplicable,
947                 );
948             }
949         }
950         if let ExprKind::Binary(op, left, right) = expr.kind {
951             if matches!(op.node, BinOpKind::Eq | BinOpKind::Ne) {
952                 let data = [
953                     (left, self.symbol_str_expr(left, cx)),
954                     (right, self.symbol_str_expr(right, cx)),
955                 ];
956                 match data {
957                     // both operands are a symbol string
958                     [(_, Some(left)), (_, Some(right))] => {
959                         span_lint_and_sugg(
960                             cx,
961                             UNNECESSARY_SYMBOL_STR,
962                             expr.span,
963                             "unnecessary `Symbol` to string conversion",
964                             "try",
965                             format!(
966                                 "{} {} {}",
967                                 left.as_symbol_snippet(cx),
968                                 op.node.as_str(),
969                                 right.as_symbol_snippet(cx),
970                             ),
971                             Applicability::MachineApplicable,
972                         );
973                     },
974                     // one of the operands is a symbol string
975                     [(expr, Some(symbol)), _] | [_, (expr, Some(symbol))] => {
976                         // creating an owned string for comparison
977                         if matches!(symbol, SymbolStrExpr::Expr { is_to_owned: true, .. }) {
978                             span_lint_and_sugg(
979                                 cx,
980                                 UNNECESSARY_SYMBOL_STR,
981                                 expr.span,
982                                 "unnecessary string allocation",
983                                 "try",
984                                 format!("{}.as_str()", symbol.as_symbol_snippet(cx)),
985                                 Applicability::MachineApplicable,
986                             );
987                         }
988                     },
989                     // nothing found
990                     [(_, None), (_, None)] => {},
991                 }
992             }
993         }
994     }
995 }
996
997 impl InterningDefinedSymbol {
998     fn symbol_str_expr<'tcx>(&self, expr: &'tcx Expr<'tcx>, cx: &LateContext<'tcx>) -> Option<SymbolStrExpr<'tcx>> {
999         static IDENT_STR_PATHS: &[&[&str]] = &[&paths::IDENT_AS_STR, &paths::TO_STRING_METHOD];
1000         static SYMBOL_STR_PATHS: &[&[&str]] = &[
1001             &paths::SYMBOL_AS_STR,
1002             &paths::SYMBOL_TO_IDENT_STRING,
1003             &paths::TO_STRING_METHOD,
1004         ];
1005         // SymbolStr might be de-referenced: `&*symbol.as_str()`
1006         let call = if_chain! {
1007             if let ExprKind::AddrOf(_, _, e) = expr.kind;
1008             if let ExprKind::Unary(UnOp::Deref, e) = e.kind;
1009             then { e } else { expr }
1010         };
1011         if_chain! {
1012             // is a method call
1013             if let ExprKind::MethodCall(_, _, [item], _) = call.kind;
1014             if let Some(did) = cx.typeck_results().type_dependent_def_id(call.hir_id);
1015             let ty = cx.typeck_results().expr_ty(item);
1016             // ...on either an Ident or a Symbol
1017             if let Some(is_ident) = if match_type(cx, ty, &paths::SYMBOL) {
1018                 Some(false)
1019             } else if match_type(cx, ty, &paths::IDENT) {
1020                 Some(true)
1021             } else {
1022                 None
1023             };
1024             // ...which converts it to a string
1025             let paths = if is_ident { IDENT_STR_PATHS } else { SYMBOL_STR_PATHS };
1026             if let Some(path) = paths.iter().find(|path| match_def_path(cx, did, path));
1027             then {
1028                 let is_to_owned = path.last().unwrap().ends_with("string");
1029                 return Some(SymbolStrExpr::Expr {
1030                     item,
1031                     is_ident,
1032                     is_to_owned,
1033                 });
1034             }
1035         }
1036         // is a string constant
1037         if let Some(Constant::Str(s)) = constant_simple(cx, cx.typeck_results(), expr) {
1038             let value = Symbol::intern(&s).as_u32();
1039             // ...which matches a symbol constant
1040             if let Some(&def_id) = self.symbol_map.get(&value) {
1041                 return Some(SymbolStrExpr::Const(def_id));
1042             }
1043         }
1044         None
1045     }
1046 }
1047
1048 enum SymbolStrExpr<'tcx> {
1049     /// a string constant with a corresponding symbol constant
1050     Const(DefId),
1051     /// a "symbol to string" expression like `symbol.as_str()`
1052     Expr {
1053         /// part that evaluates to `Symbol` or `Ident`
1054         item: &'tcx Expr<'tcx>,
1055         is_ident: bool,
1056         /// whether an owned `String` is created like `to_ident_string()`
1057         is_to_owned: bool,
1058     },
1059 }
1060
1061 impl<'tcx> SymbolStrExpr<'tcx> {
1062     /// Returns a snippet that evaluates to a `Symbol` and is const if possible
1063     fn as_symbol_snippet(&self, cx: &LateContext<'_>) -> Cow<'tcx, str> {
1064         match *self {
1065             Self::Const(def_id) => cx.tcx.def_path_str(def_id).into(),
1066             Self::Expr { item, is_ident, .. } => {
1067                 let mut snip = snippet(cx, item.span.source_callsite(), "..");
1068                 if is_ident {
1069                     // get `Ident.name`
1070                     snip.to_mut().push_str(".name");
1071                 }
1072                 snip
1073             },
1074         }
1075     }
1076 }
1077
1078 declare_lint_pass!(IfChainStyle => [IF_CHAIN_STYLE]);
1079
1080 impl<'tcx> LateLintPass<'tcx> for IfChainStyle {
1081     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx hir::Block<'_>) {
1082         let (local, after, if_chain_span) = if_chain! {
1083             if let [Stmt { kind: StmtKind::Local(local), .. }, after @ ..] = block.stmts;
1084             if let Some(if_chain_span) = is_expn_of(block.span, "if_chain");
1085             then { (local, after, if_chain_span) } else { return }
1086         };
1087         if is_first_if_chain_expr(cx, block.hir_id, if_chain_span) {
1088             span_lint(
1089                 cx,
1090                 IF_CHAIN_STYLE,
1091                 if_chain_local_span(cx, local, if_chain_span),
1092                 "`let` expression should be above the `if_chain!`",
1093             );
1094         } else if local.span.ctxt() == block.span.ctxt() && is_if_chain_then(after, block.expr, if_chain_span) {
1095             span_lint(
1096                 cx,
1097                 IF_CHAIN_STYLE,
1098                 if_chain_local_span(cx, local, if_chain_span),
1099                 "`let` expression should be inside `then { .. }`",
1100             )
1101         }
1102     }
1103
1104     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) {
1105         let (cond, then, els) = match expr.kind {
1106             ExprKind::If(cond, then, els) => (Some(cond), then, els.is_some()),
1107             ExprKind::Match(
1108                 _,
1109                 [arm, ..],
1110                 MatchSource::IfLetDesugar {
1111                     contains_else_clause: els,
1112                 },
1113             ) => (None, arm.body, els),
1114             _ => return,
1115         };
1116         let then_block = match then.kind {
1117             ExprKind::Block(block, _) => block,
1118             _ => return,
1119         };
1120         let if_chain_span = is_expn_of(expr.span, "if_chain");
1121         if !els {
1122             check_nested_if_chains(cx, expr, then_block, if_chain_span);
1123         }
1124         let if_chain_span = match if_chain_span {
1125             None => return,
1126             Some(span) => span,
1127         };
1128         // check for `if a && b;`
1129         if_chain! {
1130             if let Some(cond) = cond;
1131             if let ExprKind::Binary(op, _, _) = cond.kind;
1132             if op.node == BinOpKind::And;
1133             if cx.sess().source_map().is_multiline(cond.span);
1134             then {
1135                 span_lint(cx, IF_CHAIN_STYLE, cond.span, "`if a && b;` should be `if a; if b;`");
1136             }
1137         }
1138         if is_first_if_chain_expr(cx, expr.hir_id, if_chain_span)
1139             && is_if_chain_then(then_block.stmts, then_block.expr, if_chain_span)
1140         {
1141             span_lint(cx, IF_CHAIN_STYLE, expr.span, "`if_chain!` only has one `if`")
1142         }
1143     }
1144 }
1145
1146 fn check_nested_if_chains(
1147     cx: &LateContext<'_>,
1148     if_expr: &Expr<'_>,
1149     then_block: &Block<'_>,
1150     if_chain_span: Option<Span>,
1151 ) {
1152     #[rustfmt::skip]
1153     let (head, tail) = match *then_block {
1154         Block { stmts, expr: Some(tail), .. } => (stmts, tail),
1155         Block {
1156             stmts: &[
1157                 ref head @ ..,
1158                 Stmt { kind: StmtKind::Expr(tail) | StmtKind::Semi(tail), .. }
1159             ],
1160             ..
1161         } => (head, tail),
1162         _ => return,
1163     };
1164     if_chain! {
1165         if matches!(tail.kind,
1166             ExprKind::If(_, _, None)
1167             | ExprKind::Match(.., MatchSource::IfLetDesugar { contains_else_clause: false }));
1168         let sm = cx.sess().source_map();
1169         if head
1170             .iter()
1171             .all(|stmt| matches!(stmt.kind, StmtKind::Local(..)) && !sm.is_multiline(stmt.span));
1172         if if_chain_span.is_some() || !is_else_clause(cx.tcx, if_expr);
1173         then {} else { return }
1174     }
1175     let (span, msg) = match (if_chain_span, is_expn_of(tail.span, "if_chain")) {
1176         (None, Some(_)) => (if_expr.span, "this `if` can be part of the inner `if_chain!`"),
1177         (Some(_), None) => (tail.span, "this `if` can be part of the outer `if_chain!`"),
1178         (Some(a), Some(b)) if a != b => (b, "this `if_chain!` can be merged with the outer `if_chain!`"),
1179         _ => return,
1180     };
1181     span_lint_and_then(cx, IF_CHAIN_STYLE, span, msg, |diag| {
1182         let (span, msg) = match head {
1183             [] => return,
1184             [stmt] => (stmt.span, "this `let` statement can also be in the `if_chain!`"),
1185             [a, .., b] => (
1186                 a.span.to(b.span),
1187                 "these `let` statements can also be in the `if_chain!`",
1188             ),
1189         };
1190         diag.span_help(span, msg);
1191     });
1192 }
1193
1194 fn is_first_if_chain_expr(cx: &LateContext<'_>, hir_id: HirId, if_chain_span: Span) -> bool {
1195     cx.tcx
1196         .hir()
1197         .parent_iter(hir_id)
1198         .find(|(_, node)| {
1199             #[rustfmt::skip]
1200             !matches!(node, Node::Expr(Expr { kind: ExprKind::Block(..), .. }) | Node::Stmt(_))
1201         })
1202         .map_or(false, |(id, _)| {
1203             is_expn_of(cx.tcx.hir().span(id), "if_chain") != Some(if_chain_span)
1204         })
1205 }
1206
1207 /// Checks a trailing slice of statements and expression of a `Block` to see if they are part
1208 /// of the `then {..}` portion of an `if_chain!`
1209 fn is_if_chain_then(stmts: &[Stmt<'_>], expr: Option<&Expr<'_>>, if_chain_span: Span) -> bool {
1210     let span = if let [stmt, ..] = stmts {
1211         stmt.span
1212     } else if let Some(expr) = expr {
1213         expr.span
1214     } else {
1215         // empty `then {}`
1216         return true;
1217     };
1218     is_expn_of(span, "if_chain").map_or(true, |span| span != if_chain_span)
1219 }
1220
1221 /// Creates a `Span` for `let x = ..;` in an `if_chain!` call.
1222 fn if_chain_local_span(cx: &LateContext<'_>, local: &Local<'_>, if_chain_span: Span) -> Span {
1223     let mut span = local.pat.span;
1224     if let Some(init) = local.init {
1225         span = span.to(init.span);
1226     }
1227     span.adjust(if_chain_span.ctxt().outer_expn());
1228     let sm = cx.sess().source_map();
1229     let span = sm.span_extend_to_prev_str(span, "let", false);
1230     let span = sm.span_extend_to_next_char(span, ';', false);
1231     Span::new(span.lo() - BytePos(3), span.hi() + BytePos(1), span.ctxt())
1232 }