]> git.proxmox.com Git - rustc.git/blob - src/librustc_lint/context.rs
New upstream version 1.42.0+dfsg1
[rustc.git] / src / librustc_lint / context.rs
1 //! Implementation of lint checking.
2 //!
3 //! The lint checking is mostly consolidated into one pass which runs
4 //! after all other analyses. Throughout compilation, lint warnings
5 //! can be added via the `add_lint` method on the Session structure. This
6 //! requires a span and an ID of the node that the lint is being added to. The
7 //! lint isn't actually emitted at that time because it is unknown what the
8 //! actual lint level at that location is.
9 //!
10 //! To actually emit lint warnings/errors, a separate pass is used.
11 //! A context keeps track of the current state of all lint levels.
12 //! Upon entering a node of the ast which can modify the lint settings, the
13 //! previous lint state is pushed onto a stack and the ast is then recursed
14 //! upon. As the ast is traversed, this keeps track of the current lint level
15 //! for all lint attributes.
16
17 use self::TargetLint::*;
18
19 use crate::levels::LintLevelsBuilder;
20 use crate::passes::{EarlyLintPassObject, LateLintPassObject};
21 use rustc::hir::map::definitions::{DefPathData, DisambiguatedDefPathData};
22 use rustc::lint::add_elided_lifetime_in_path_suggestion;
23 use rustc::middle::privacy::AccessLevels;
24 use rustc::middle::stability;
25 use rustc::ty::layout::{LayoutError, LayoutOf, TyLayout};
26 use rustc::ty::{self, print::Printer, subst::GenericArg, Ty, TyCtxt};
27 use rustc_data_structures::fx::FxHashMap;
28 use rustc_data_structures::sync;
29 use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder};
30 use rustc_hir as hir;
31 use rustc_hir::def_id::{CrateNum, DefId};
32 use rustc_session::lint::BuiltinLintDiagnostics;
33 use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId};
34 use rustc_session::Session;
35 use rustc_span::{symbol::Symbol, MultiSpan, Span, DUMMY_SP};
36 use syntax::ast;
37 use syntax::util::lev_distance::find_best_match_for_name;
38
39 use std::slice;
40
41 /// Information about the registered lints.
42 ///
43 /// This is basically the subset of `Context` that we can
44 /// build early in the compile pipeline.
45 pub struct LintStore {
46 /// Registered lints.
47 lints: Vec<&'static Lint>,
48
49 /// Constructor functions for each variety of lint pass.
50 ///
51 /// These should only be called once, but since we want to avoid locks or
52 /// interior mutability, we don't enforce this (and lints should, in theory,
53 /// be compatible with being constructed more than once, though not
54 /// necessarily in a sane manner. This is safe though.)
55 pub pre_expansion_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
56 pub early_passes: Vec<Box<dyn Fn() -> EarlyLintPassObject + sync::Send + sync::Sync>>,
57 pub late_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
58 /// This is unique in that we construct them per-module, so not once.
59 pub late_module_passes: Vec<Box<dyn Fn() -> LateLintPassObject + sync::Send + sync::Sync>>,
60
61 /// Lints indexed by name.
62 by_name: FxHashMap<String, TargetLint>,
63
64 /// Map of registered lint groups to what lints they expand to.
65 lint_groups: FxHashMap<&'static str, LintGroup>,
66 }
67
68 /// The target of the `by_name` map, which accounts for renaming/deprecation.
69 enum TargetLint {
70 /// A direct lint target
71 Id(LintId),
72
73 /// Temporary renaming, used for easing migration pain; see #16545
74 Renamed(String, LintId),
75
76 /// Lint with this name existed previously, but has been removed/deprecated.
77 /// The string argument is the reason for removal.
78 Removed(String),
79 }
80
81 pub enum FindLintError {
82 NotFound,
83 Removed,
84 }
85
86 struct LintAlias {
87 name: &'static str,
88 /// Whether deprecation warnings should be suppressed for this alias.
89 silent: bool,
90 }
91
92 struct LintGroup {
93 lint_ids: Vec<LintId>,
94 from_plugin: bool,
95 depr: Option<LintAlias>,
96 }
97
98 pub enum CheckLintNameResult<'a> {
99 Ok(&'a [LintId]),
100 /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name.
101 NoLint(Option<Symbol>),
102 /// The lint is either renamed or removed. This is the warning
103 /// message, and an optional new name (`None` if removed).
104 Warning(String, Option<String>),
105 /// The lint is from a tool. If the Option is None, then either
106 /// the lint does not exist in the tool or the code was not
107 /// compiled with the tool and therefore the lint was never
108 /// added to the `LintStore`. Otherwise the `LintId` will be
109 /// returned as if it where a rustc lint.
110 Tool(Result<&'a [LintId], (Option<&'a [LintId]>, String)>),
111 }
112
113 impl LintStore {
114 pub fn new() -> LintStore {
115 LintStore {
116 lints: vec![],
117 pre_expansion_passes: vec![],
118 early_passes: vec![],
119 late_passes: vec![],
120 late_module_passes: vec![],
121 by_name: Default::default(),
122 lint_groups: Default::default(),
123 }
124 }
125
126 pub fn get_lints<'t>(&'t self) -> &'t [&'static Lint] {
127 &self.lints
128 }
129
130 pub fn get_lint_groups<'t>(&'t self) -> Vec<(&'static str, Vec<LintId>, bool)> {
131 self.lint_groups
132 .iter()
133 .filter(|(_, LintGroup { depr, .. })| {
134 // Don't display deprecated lint groups.
135 depr.is_none()
136 })
137 .map(|(k, LintGroup { lint_ids, from_plugin, .. })| {
138 (*k, lint_ids.clone(), *from_plugin)
139 })
140 .collect()
141 }
142
143 pub fn register_early_pass(
144 &mut self,
145 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
146 ) {
147 self.early_passes.push(Box::new(pass));
148 }
149
150 pub fn register_pre_expansion_pass(
151 &mut self,
152 pass: impl Fn() -> EarlyLintPassObject + 'static + sync::Send + sync::Sync,
153 ) {
154 self.pre_expansion_passes.push(Box::new(pass));
155 }
156
157 pub fn register_late_pass(
158 &mut self,
159 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
160 ) {
161 self.late_passes.push(Box::new(pass));
162 }
163
164 pub fn register_late_mod_pass(
165 &mut self,
166 pass: impl Fn() -> LateLintPassObject + 'static + sync::Send + sync::Sync,
167 ) {
168 self.late_module_passes.push(Box::new(pass));
169 }
170
171 // Helper method for register_early/late_pass
172 pub fn register_lints(&mut self, lints: &[&'static Lint]) {
173 for lint in lints {
174 self.lints.push(lint);
175
176 let id = LintId::of(lint);
177 if self.by_name.insert(lint.name_lower(), Id(id)).is_some() {
178 bug!("duplicate specification of lint {}", lint.name_lower())
179 }
180
181 if let Some(FutureIncompatibleInfo { edition, .. }) = lint.future_incompatible {
182 if let Some(edition) = edition {
183 self.lint_groups
184 .entry(edition.lint_name())
185 .or_insert(LintGroup {
186 lint_ids: vec![],
187 from_plugin: lint.is_plugin,
188 depr: None,
189 })
190 .lint_ids
191 .push(id);
192 }
193
194 self.lint_groups
195 .entry("future_incompatible")
196 .or_insert(LintGroup {
197 lint_ids: vec![],
198 from_plugin: lint.is_plugin,
199 depr: None,
200 })
201 .lint_ids
202 .push(id);
203 }
204 }
205 }
206
207 pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) {
208 self.lint_groups.insert(
209 alias,
210 LintGroup {
211 lint_ids: vec![],
212 from_plugin: false,
213 depr: Some(LintAlias { name: lint_name, silent: true }),
214 },
215 );
216 }
217
218 pub fn register_group(
219 &mut self,
220 from_plugin: bool,
221 name: &'static str,
222 deprecated_name: Option<&'static str>,
223 to: Vec<LintId>,
224 ) {
225 let new = self
226 .lint_groups
227 .insert(name, LintGroup { lint_ids: to, from_plugin, depr: None })
228 .is_none();
229 if let Some(deprecated) = deprecated_name {
230 self.lint_groups.insert(
231 deprecated,
232 LintGroup {
233 lint_ids: vec![],
234 from_plugin,
235 depr: Some(LintAlias { name, silent: false }),
236 },
237 );
238 }
239
240 if !new {
241 bug!("duplicate specification of lint group {}", name);
242 }
243 }
244
245 pub fn register_renamed(&mut self, old_name: &str, new_name: &str) {
246 let target = match self.by_name.get(new_name) {
247 Some(&Id(lint_id)) => lint_id,
248 _ => bug!("invalid lint renaming of {} to {}", old_name, new_name),
249 };
250 self.by_name.insert(old_name.to_string(), Renamed(new_name.to_string(), target));
251 }
252
253 pub fn register_removed(&mut self, name: &str, reason: &str) {
254 self.by_name.insert(name.into(), Removed(reason.into()));
255 }
256
257 pub fn find_lints(&self, mut lint_name: &str) -> Result<Vec<LintId>, FindLintError> {
258 match self.by_name.get(lint_name) {
259 Some(&Id(lint_id)) => Ok(vec![lint_id]),
260 Some(&Renamed(_, lint_id)) => Ok(vec![lint_id]),
261 Some(&Removed(_)) => Err(FindLintError::Removed),
262 None => loop {
263 return match self.lint_groups.get(lint_name) {
264 Some(LintGroup { lint_ids, depr, .. }) => {
265 if let Some(LintAlias { name, .. }) = depr {
266 lint_name = name;
267 continue;
268 }
269 Ok(lint_ids.clone())
270 }
271 None => Err(FindLintError::Removed),
272 };
273 },
274 }
275 }
276
277 /// Checks the validity of lint names derived from the command line
278 pub fn check_lint_name_cmdline(&self, sess: &Session, lint_name: &str, level: Level) {
279 let db = match self.check_lint_name(lint_name, None) {
280 CheckLintNameResult::Ok(_) => None,
281 CheckLintNameResult::Warning(ref msg, _) => Some(sess.struct_warn(msg)),
282 CheckLintNameResult::NoLint(suggestion) => {
283 let mut err =
284 struct_span_err!(sess, DUMMY_SP, E0602, "unknown lint: `{}`", lint_name);
285
286 if let Some(suggestion) = suggestion {
287 err.help(&format!("did you mean: `{}`", suggestion));
288 }
289
290 Some(err)
291 }
292 CheckLintNameResult::Tool(result) => match result {
293 Err((Some(_), new_name)) => Some(sess.struct_warn(&format!(
294 "lint name `{}` is deprecated \
295 and does not have an effect anymore. \
296 Use: {}",
297 lint_name, new_name
298 ))),
299 _ => None,
300 },
301 };
302
303 if let Some(mut db) = db {
304 let msg = format!(
305 "requested on the command line with `{} {}`",
306 match level {
307 Level::Allow => "-A",
308 Level::Warn => "-W",
309 Level::Deny => "-D",
310 Level::Forbid => "-F",
311 },
312 lint_name
313 );
314 db.note(&msg);
315 db.emit();
316 }
317 }
318
319 /// Checks the name of a lint for its existence, and whether it was
320 /// renamed or removed. Generates a DiagnosticBuilder containing a
321 /// warning for renamed and removed lints. This is over both lint
322 /// names from attributes and those passed on the command line. Since
323 /// it emits non-fatal warnings and there are *two* lint passes that
324 /// inspect attributes, this is only run from the late pass to avoid
325 /// printing duplicate warnings.
326 pub fn check_lint_name(
327 &self,
328 lint_name: &str,
329 tool_name: Option<Symbol>,
330 ) -> CheckLintNameResult<'_> {
331 let complete_name = if let Some(tool_name) = tool_name {
332 format!("{}::{}", tool_name, lint_name)
333 } else {
334 lint_name.to_string()
335 };
336 // If the lint was scoped with `tool::` check if the tool lint exists
337 if let Some(_) = tool_name {
338 match self.by_name.get(&complete_name) {
339 None => match self.lint_groups.get(&*complete_name) {
340 None => return CheckLintNameResult::Tool(Err((None, String::new()))),
341 Some(LintGroup { lint_ids, .. }) => {
342 return CheckLintNameResult::Tool(Ok(&lint_ids));
343 }
344 },
345 Some(&Id(ref id)) => return CheckLintNameResult::Tool(Ok(slice::from_ref(id))),
346 // If the lint was registered as removed or renamed by the lint tool, we don't need
347 // to treat tool_lints and rustc lints different and can use the code below.
348 _ => {}
349 }
350 }
351 match self.by_name.get(&complete_name) {
352 Some(&Renamed(ref new_name, _)) => CheckLintNameResult::Warning(
353 format!("lint `{}` has been renamed to `{}`", complete_name, new_name),
354 Some(new_name.to_owned()),
355 ),
356 Some(&Removed(ref reason)) => CheckLintNameResult::Warning(
357 format!("lint `{}` has been removed: `{}`", complete_name, reason),
358 None,
359 ),
360 None => match self.lint_groups.get(&*complete_name) {
361 // If neither the lint, nor the lint group exists check if there is a `clippy::`
362 // variant of this lint
363 None => self.check_tool_name_for_backwards_compat(&complete_name, "clippy"),
364 Some(LintGroup { lint_ids, depr, .. }) => {
365 // Check if the lint group name is deprecated
366 if let Some(LintAlias { name, silent }) = depr {
367 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
368 return if *silent {
369 CheckLintNameResult::Ok(&lint_ids)
370 } else {
371 CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
372 };
373 }
374 CheckLintNameResult::Ok(&lint_ids)
375 }
376 },
377 Some(&Id(ref id)) => CheckLintNameResult::Ok(slice::from_ref(id)),
378 }
379 }
380
381 fn check_tool_name_for_backwards_compat(
382 &self,
383 lint_name: &str,
384 tool_name: &str,
385 ) -> CheckLintNameResult<'_> {
386 let complete_name = format!("{}::{}", tool_name, lint_name);
387 match self.by_name.get(&complete_name) {
388 None => match self.lint_groups.get(&*complete_name) {
389 // Now we are sure, that this lint exists nowhere
390 None => {
391 let symbols =
392 self.by_name.keys().map(|name| Symbol::intern(&name)).collect::<Vec<_>>();
393
394 let suggestion =
395 find_best_match_for_name(symbols.iter(), &lint_name.to_lowercase(), None);
396
397 CheckLintNameResult::NoLint(suggestion)
398 }
399 Some(LintGroup { lint_ids, depr, .. }) => {
400 // Reaching this would be weird, but let's cover this case anyway
401 if let Some(LintAlias { name, silent }) = depr {
402 let LintGroup { lint_ids, .. } = self.lint_groups.get(name).unwrap();
403 return if *silent {
404 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
405 } else {
406 CheckLintNameResult::Tool(Err((Some(&lint_ids), name.to_string())))
407 };
408 }
409 CheckLintNameResult::Tool(Err((Some(&lint_ids), complete_name)))
410 }
411 },
412 Some(&Id(ref id)) => {
413 CheckLintNameResult::Tool(Err((Some(slice::from_ref(id)), complete_name)))
414 }
415 _ => CheckLintNameResult::NoLint(None),
416 }
417 }
418 }
419
420 /// Context for lint checking after type checking.
421 pub struct LateContext<'a, 'tcx> {
422 /// Type context we're checking in.
423 pub tcx: TyCtxt<'tcx>,
424
425 /// Side-tables for the body we are in.
426 // FIXME: Make this lazy to avoid running the TypeckTables query?
427 pub tables: &'a ty::TypeckTables<'tcx>,
428
429 /// Parameter environment for the item we are in.
430 pub param_env: ty::ParamEnv<'tcx>,
431
432 /// Items accessible from the crate being checked.
433 pub access_levels: &'a AccessLevels,
434
435 /// The store of registered lints and the lint levels.
436 pub lint_store: &'tcx LintStore,
437
438 pub last_node_with_lint_attrs: hir::HirId,
439
440 /// Generic type parameters in scope for the item we are in.
441 pub generics: Option<&'tcx hir::Generics<'tcx>>,
442
443 /// We are only looking at one module
444 pub only_module: bool,
445 }
446
447 /// Context for lint checking of the AST, after expansion, before lowering to
448 /// HIR.
449 pub struct EarlyContext<'a> {
450 /// Type context we're checking in.
451 pub sess: &'a Session,
452
453 /// The crate being checked.
454 pub krate: &'a ast::Crate,
455
456 pub builder: LintLevelsBuilder<'a>,
457
458 /// The store of registered lints and the lint levels.
459 pub lint_store: &'a LintStore,
460
461 pub buffered: LintBuffer,
462 }
463
464 pub trait LintPassObject: Sized {}
465
466 impl LintPassObject for EarlyLintPassObject {}
467
468 impl LintPassObject for LateLintPassObject {}
469
470 pub trait LintContext: Sized {
471 type PassObject: LintPassObject;
472
473 fn sess(&self) -> &Session;
474 fn lints(&self) -> &LintStore;
475
476 fn lookup_and_emit<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: Option<S>, msg: &str) {
477 self.lookup(lint, span, msg).emit();
478 }
479
480 fn lookup_and_emit_with_diagnostics<S: Into<MultiSpan>>(
481 &self,
482 lint: &'static Lint,
483 span: Option<S>,
484 msg: &str,
485 diagnostic: BuiltinLintDiagnostics,
486 ) {
487 let mut db = self.lookup(lint, span, msg);
488
489 let sess = self.sess();
490 match diagnostic {
491 BuiltinLintDiagnostics::Normal => (),
492 BuiltinLintDiagnostics::BareTraitObject(span, is_global) => {
493 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
494 Ok(s) if is_global => {
495 (format!("dyn ({})", s), Applicability::MachineApplicable)
496 }
497 Ok(s) => (format!("dyn {}", s), Applicability::MachineApplicable),
498 Err(_) => ("dyn <type>".to_string(), Applicability::HasPlaceholders),
499 };
500 db.span_suggestion(span, "use `dyn`", sugg, app);
501 }
502 BuiltinLintDiagnostics::AbsPathWithModule(span) => {
503 let (sugg, app) = match sess.source_map().span_to_snippet(span) {
504 Ok(ref s) => {
505 // FIXME(Manishearth) ideally the emitting code
506 // can tell us whether or not this is global
507 let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" };
508
509 (format!("crate{}{}", opt_colon, s), Applicability::MachineApplicable)
510 }
511 Err(_) => ("crate::<path>".to_string(), Applicability::HasPlaceholders),
512 };
513 db.span_suggestion(span, "use `crate`", sugg, app);
514 }
515 BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback(span) => {
516 db.span_label(
517 span,
518 "names from parent modules are not accessible without an explicit import",
519 );
520 }
521 BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def) => {
522 db.span_note(span_def, "the macro is defined here");
523 }
524 BuiltinLintDiagnostics::ElidedLifetimesInPaths(
525 n,
526 path_span,
527 incl_angl_brckt,
528 insertion_span,
529 anon_lts,
530 ) => {
531 add_elided_lifetime_in_path_suggestion(
532 sess,
533 &mut db,
534 n,
535 path_span,
536 incl_angl_brckt,
537 insertion_span,
538 anon_lts,
539 );
540 }
541 BuiltinLintDiagnostics::UnknownCrateTypes(span, note, sugg) => {
542 db.span_suggestion(span, &note, sugg, Applicability::MaybeIncorrect);
543 }
544 BuiltinLintDiagnostics::UnusedImports(message, replaces) => {
545 if !replaces.is_empty() {
546 db.tool_only_multipart_suggestion(
547 &message,
548 replaces,
549 Applicability::MachineApplicable,
550 );
551 }
552 }
553 BuiltinLintDiagnostics::RedundantImport(spans, ident) => {
554 for (span, is_imported) in spans {
555 let introduced = if is_imported { "imported" } else { "defined" };
556 db.span_label(
557 span,
558 format!("the item `{}` is already {} here", ident, introduced),
559 );
560 }
561 }
562 BuiltinLintDiagnostics::DeprecatedMacro(suggestion, span) => {
563 stability::deprecation_suggestion(&mut db, suggestion, span)
564 }
565 }
566
567 db.emit();
568 }
569
570 fn lookup<S: Into<MultiSpan>>(
571 &self,
572 lint: &'static Lint,
573 span: Option<S>,
574 msg: &str,
575 ) -> DiagnosticBuilder<'_>;
576
577 /// Emit a lint at the appropriate level, for a particular span.
578 fn span_lint<S: Into<MultiSpan>>(&self, lint: &'static Lint, span: S, msg: &str) {
579 self.lookup_and_emit(lint, Some(span), msg);
580 }
581
582 fn struct_span_lint<S: Into<MultiSpan>>(
583 &self,
584 lint: &'static Lint,
585 span: S,
586 msg: &str,
587 ) -> DiagnosticBuilder<'_> {
588 self.lookup(lint, Some(span), msg)
589 }
590
591 /// Emit a lint and note at the appropriate level, for a particular span.
592 fn span_lint_note(
593 &self,
594 lint: &'static Lint,
595 span: Span,
596 msg: &str,
597 note_span: Span,
598 note: &str,
599 ) {
600 let mut err = self.lookup(lint, Some(span), msg);
601 if note_span == span {
602 err.note(note);
603 } else {
604 err.span_note(note_span, note);
605 }
606 err.emit();
607 }
608
609 /// Emit a lint and help at the appropriate level, for a particular span.
610 fn span_lint_help(&self, lint: &'static Lint, span: Span, msg: &str, help: &str) {
611 let mut err = self.lookup(lint, Some(span), msg);
612 self.span_lint(lint, span, msg);
613 err.span_help(span, help);
614 err.emit();
615 }
616
617 /// Emit a lint at the appropriate level, with no associated span.
618 fn lint(&self, lint: &'static Lint, msg: &str) {
619 self.lookup_and_emit(lint, None as Option<Span>, msg);
620 }
621 }
622
623 impl<'a> EarlyContext<'a> {
624 pub fn new(
625 sess: &'a Session,
626 lint_store: &'a LintStore,
627 krate: &'a ast::Crate,
628 buffered: LintBuffer,
629 warn_about_weird_lints: bool,
630 ) -> EarlyContext<'a> {
631 EarlyContext {
632 sess,
633 krate,
634 lint_store,
635 builder: LintLevelsBuilder::new(sess, warn_about_weird_lints, lint_store),
636 buffered,
637 }
638 }
639 }
640
641 impl LintContext for LateContext<'_, '_> {
642 type PassObject = LateLintPassObject;
643
644 /// Gets the overall compiler `Session` object.
645 fn sess(&self) -> &Session {
646 &self.tcx.sess
647 }
648
649 fn lints(&self) -> &LintStore {
650 &*self.lint_store
651 }
652
653 fn lookup<S: Into<MultiSpan>>(
654 &self,
655 lint: &'static Lint,
656 span: Option<S>,
657 msg: &str,
658 ) -> DiagnosticBuilder<'_> {
659 let hir_id = self.last_node_with_lint_attrs;
660
661 match span {
662 Some(s) => self.tcx.struct_span_lint_hir(lint, hir_id, s, msg),
663 None => self.tcx.struct_lint_node(lint, hir_id, msg),
664 }
665 }
666 }
667
668 impl LintContext for EarlyContext<'_> {
669 type PassObject = EarlyLintPassObject;
670
671 /// Gets the overall compiler `Session` object.
672 fn sess(&self) -> &Session {
673 &self.sess
674 }
675
676 fn lints(&self) -> &LintStore {
677 &*self.lint_store
678 }
679
680 fn lookup<S: Into<MultiSpan>>(
681 &self,
682 lint: &'static Lint,
683 span: Option<S>,
684 msg: &str,
685 ) -> DiagnosticBuilder<'_> {
686 self.builder.struct_lint(lint, span.map(|s| s.into()), msg)
687 }
688 }
689
690 impl<'a, 'tcx> LateContext<'a, 'tcx> {
691 pub fn current_lint_root(&self) -> hir::HirId {
692 self.last_node_with_lint_attrs
693 }
694
695 /// Check if a `DefId`'s path matches the given absolute type path usage.
696 ///
697 /// Anonymous scopes such as `extern` imports are matched with `kw::Invalid`;
698 /// inherent `impl` blocks are matched with the name of the type.
699 ///
700 /// # Examples
701 ///
702 /// ```rust,ignore (no context or def id available)
703 /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) {
704 /// // The given `def_id` is that of an `Option` type
705 /// }
706 /// ```
707 pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool {
708 let names = self.get_def_path(def_id);
709
710 names.len() == path.len() && names.into_iter().zip(path.iter()).all(|(a, &b)| a == b)
711 }
712
713 /// Gets the absolute path of `def_id` as a vector of `Symbol`.
714 ///
715 /// # Examples
716 ///
717 /// ```rust,ignore (no context or def id available)
718 /// let def_path = cx.get_def_path(def_id);
719 /// if let &[sym::core, sym::option, sym::Option] = &def_path[..] {
720 /// // The given `def_id` is that of an `Option` type
721 /// }
722 /// ```
723 pub fn get_def_path(&self, def_id: DefId) -> Vec<Symbol> {
724 pub struct AbsolutePathPrinter<'tcx> {
725 pub tcx: TyCtxt<'tcx>,
726 }
727
728 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
729 type Error = !;
730
731 type Path = Vec<Symbol>;
732 type Region = ();
733 type Type = ();
734 type DynExistential = ();
735 type Const = ();
736
737 fn tcx(&self) -> TyCtxt<'tcx> {
738 self.tcx
739 }
740
741 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
742 Ok(())
743 }
744
745 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
746 Ok(())
747 }
748
749 fn print_dyn_existential(
750 self,
751 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
752 ) -> Result<Self::DynExistential, Self::Error> {
753 Ok(())
754 }
755
756 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
757 Ok(())
758 }
759
760 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
761 Ok(vec![self.tcx.original_crate_name(cnum)])
762 }
763
764 fn path_qualified(
765 self,
766 self_ty: Ty<'tcx>,
767 trait_ref: Option<ty::TraitRef<'tcx>>,
768 ) -> Result<Self::Path, Self::Error> {
769 if trait_ref.is_none() {
770 if let ty::Adt(def, substs) = self_ty.kind {
771 return self.print_def_path(def.did, substs);
772 }
773 }
774
775 // This shouldn't ever be needed, but just in case:
776 Ok(vec![match trait_ref {
777 Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
778 None => Symbol::intern(&format!("<{}>", self_ty)),
779 }])
780 }
781
782 fn path_append_impl(
783 self,
784 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
785 _disambiguated_data: &DisambiguatedDefPathData,
786 self_ty: Ty<'tcx>,
787 trait_ref: Option<ty::TraitRef<'tcx>>,
788 ) -> Result<Self::Path, Self::Error> {
789 let mut path = print_prefix(self)?;
790
791 // This shouldn't ever be needed, but just in case:
792 path.push(match trait_ref {
793 Some(trait_ref) => Symbol::intern(&format!(
794 "<impl {} for {}>",
795 trait_ref.print_only_trait_path(),
796 self_ty
797 )),
798 None => Symbol::intern(&format!("<impl {}>", self_ty)),
799 });
800
801 Ok(path)
802 }
803
804 fn path_append(
805 self,
806 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
807 disambiguated_data: &DisambiguatedDefPathData,
808 ) -> Result<Self::Path, Self::Error> {
809 let mut path = print_prefix(self)?;
810
811 // Skip `::{{constructor}}` on tuple/unit structs.
812 match disambiguated_data.data {
813 DefPathData::Ctor => return Ok(path),
814 _ => {}
815 }
816
817 path.push(disambiguated_data.data.as_symbol());
818 Ok(path)
819 }
820
821 fn path_generic_args(
822 self,
823 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
824 _args: &[GenericArg<'tcx>],
825 ) -> Result<Self::Path, Self::Error> {
826 print_prefix(self)
827 }
828 }
829
830 AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]).unwrap()
831 }
832 }
833
834 impl<'a, 'tcx> LayoutOf for LateContext<'a, 'tcx> {
835 type Ty = Ty<'tcx>;
836 type TyLayout = Result<TyLayout<'tcx>, LayoutError<'tcx>>;
837
838 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
839 self.tcx.layout_of(self.param_env.and(ty))
840 }
841 }