rustc_lint/builtin.rs
1//! Lints in the Rust compiler.
2//!
3//! This contains lints which can feasibly be implemented as their own
4//! AST visitor. Also see `rustc_session::lint::builtin`, which contains the
5//! definitions of lints that are emitted directly inside the main compiler.
6//!
7//! To add a new lint to rustc, declare it here using [`declare_lint!`].
8//! Then add code to emit the new lint in the appropriate circumstances.
9//!
10//! If you define a new [`EarlyLintPass`], you will also need to add it to the
11//! [`crate::early_lint_methods!`] invocation in `lib.rs`.
12//!
13//! If you define a new [`LateLintPass`], you will also need to add it to the
14//! [`crate::late_lint_methods!`] invocation in `lib.rs`.
15
16use std::fmt::Write;
17
18use ast::token::TokenKind;
19use rustc_abi::BackendRepr;
20use rustc_ast::tokenstream::{TokenStream, TokenTree};
21use rustc_ast::visit::{FnCtxt, FnKind};
22use rustc_ast::{self as ast, *};
23use rustc_ast_pretty::pprust::expr_to_string;
24use rustc_attr_parsing::AttributeParser;
25use rustc_errors::{Applicability, LintDiagnostic};
26use rustc_feature::GateIssue;
27use rustc_hir as hir;
28use rustc_hir::attrs::AttributeKind;
29use rustc_hir::def::{DefKind, Res};
30use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
31use rustc_hir::intravisit::FnKind as HirFnKind;
32use rustc_hir::{Body, FnDecl, ImplItemImplKind, PatKind, PredicateOrigin, find_attr};
33use rustc_middle::bug;
34use rustc_middle::lint::LevelAndSource;
35use rustc_middle::ty::layout::LayoutOf;
36use rustc_middle::ty::print::with_no_trimmed_paths;
37use rustc_middle::ty::{self, AssocContainer, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef};
38use rustc_session::lint::FutureIncompatibilityReason;
39// hardwired lints from rustc_lint_defs
40pub use rustc_session::lint::builtin::*;
41use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
42use rustc_span::edition::Edition;
43use rustc_span::source_map::Spanned;
44use rustc_span::{BytePos, DUMMY_SP, Ident, InnerSpan, Span, Symbol, kw, sym};
45use rustc_target::asm::InlineAsmArch;
46use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
47use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy;
48use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
49use rustc_trait_selection::traits::{self};
50
51use crate::errors::BuiltinEllipsisInclusiveRangePatterns;
52use crate::lints::{
53 BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations,
54 BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatternsLint,
55 BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote,
56 BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures,
57 BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
58 BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
59 BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
60 BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
61 BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
62 BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
63};
64use crate::{
65 EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext,
66 fluent_generated as fluent,
67};
68declare_lint! {
69 /// The `while_true` lint detects `while true { }`.
70 ///
71 /// ### Example
72 ///
73 /// ```rust,no_run
74 /// while true {
75 ///
76 /// }
77 /// ```
78 ///
79 /// {{produces}}
80 ///
81 /// ### Explanation
82 ///
83 /// `while true` should be replaced with `loop`. A `loop` expression is
84 /// the preferred way to write an infinite loop because it more directly
85 /// expresses the intent of the loop.
86 WHILE_TRUE,
87 Warn,
88 "suggest using `loop { }` instead of `while true { }`"
89}
90
91declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
92
93impl EarlyLintPass for WhileTrue {
94 #[inline]
95 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
96 if let ast::ExprKind::While(cond, _, label) = &e.kind
97 && let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
98 && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
99 && !cond.span.from_expansion()
100 {
101 let condition_span = e.span.with_hi(cond.span.hi());
102 let replace = format!(
103 "{}loop",
104 label.map_or_else(String::new, |label| format!("{}: ", label.ident,))
105 );
106 cx.emit_span_lint(
107 WHILE_TRUE,
108 condition_span,
109 BuiltinWhileTrue { suggestion: condition_span, replace },
110 );
111 }
112 }
113}
114
115declare_lint! {
116 /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`
117 /// instead of `Struct { x }` in a pattern.
118 ///
119 /// ### Example
120 ///
121 /// ```rust
122 /// struct Point {
123 /// x: i32,
124 /// y: i32,
125 /// }
126 ///
127 ///
128 /// fn main() {
129 /// let p = Point {
130 /// x: 5,
131 /// y: 5,
132 /// };
133 ///
134 /// match p {
135 /// Point { x: x, y: y } => (),
136 /// }
137 /// }
138 /// ```
139 ///
140 /// {{produces}}
141 ///
142 /// ### Explanation
143 ///
144 /// The preferred style is to avoid the repetition of specifying both the
145 /// field name and the binding name if both identifiers are the same.
146 NON_SHORTHAND_FIELD_PATTERNS,
147 Warn,
148 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
149}
150
151declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
152
153impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
154 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
155 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
156 let variant = cx
157 .typeck_results()
158 .pat_ty(pat)
159 .ty_adt_def()
160 .expect("struct pattern type is not an ADT")
161 .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
162 for fieldpat in field_pats {
163 if fieldpat.is_shorthand {
164 continue;
165 }
166 if fieldpat.span.from_expansion() {
167 // Don't lint if this is a macro expansion: macro authors
168 // shouldn't have to worry about this kind of style issue
169 // (Issue #49588)
170 continue;
171 }
172 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
173 if cx.tcx.find_field_index(ident, variant)
174 == Some(cx.typeck_results().field_index(fieldpat.hir_id))
175 {
176 cx.emit_span_lint(
177 NON_SHORTHAND_FIELD_PATTERNS,
178 fieldpat.span,
179 BuiltinNonShorthandFieldPatterns {
180 ident,
181 suggestion: fieldpat.span,
182 prefix: binding_annot.prefix_str(),
183 },
184 );
185 }
186 }
187 }
188 }
189 }
190}
191
192declare_lint! {
193 /// The `unsafe_code` lint catches usage of `unsafe` code and other
194 /// potentially unsound constructs like `no_mangle`, `export_name`,
195 /// and `link_section`.
196 ///
197 /// ### Example
198 ///
199 /// ```rust,compile_fail
200 /// #![deny(unsafe_code)]
201 /// fn main() {
202 /// unsafe {
203 ///
204 /// }
205 /// }
206 ///
207 /// #[no_mangle]
208 /// fn func_0() { }
209 ///
210 /// #[export_name = "exported_symbol_name"]
211 /// pub fn name_in_rust() { }
212 ///
213 /// #[no_mangle]
214 /// #[link_section = ".example_section"]
215 /// pub static VAR1: u32 = 1;
216 /// ```
217 ///
218 /// {{produces}}
219 ///
220 /// ### Explanation
221 ///
222 /// This lint is intended to restrict the usage of `unsafe` blocks and other
223 /// constructs (including, but not limited to `no_mangle`, `link_section`
224 /// and `export_name` attributes) wrong usage of which causes undefined
225 /// behavior.
226 UNSAFE_CODE,
227 Allow,
228 "usage of `unsafe` code and other potentially unsound constructs",
229 @eval_always = true
230}
231
232declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
233
234impl UnsafeCode {
235 fn report_unsafe(
236 &self,
237 cx: &EarlyContext<'_>,
238 span: Span,
239 decorate: impl for<'a> LintDiagnostic<'a, ()>,
240 ) {
241 // This comes from a macro that has `#[allow_internal_unsafe]`.
242 if span.allows_unsafe() {
243 return;
244 }
245
246 cx.emit_span_lint(UNSAFE_CODE, span, decorate);
247 }
248}
249
250impl EarlyLintPass for UnsafeCode {
251 #[inline]
252 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
253 if let ast::ExprKind::Block(ref blk, _) = e.kind {
254 // Don't warn about generated blocks; that'll just pollute the output.
255 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
256 self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
257 }
258 }
259 }
260
261 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
262 match it.kind {
263 ast::ItemKind::Trait(box ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
264 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
265 }
266
267 ast::ItemKind::Impl(ast::Impl {
268 of_trait: Some(box ast::TraitImplHeader { safety: ast::Safety::Unsafe(_), .. }),
269 ..
270 }) => {
271 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
272 }
273
274 ast::ItemKind::Fn(..) => {
275 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
276 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleFn);
277 }
278
279 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
280 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameFn);
281 }
282
283 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
284 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionFn);
285 }
286 }
287
288 ast::ItemKind::Static(..) => {
289 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
290 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleStatic);
291 }
292
293 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
294 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameStatic);
295 }
296
297 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
298 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionStatic);
299 }
300 }
301
302 ast::ItemKind::GlobalAsm(..) => {
303 self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
304 }
305
306 ast::ItemKind::ForeignMod(ForeignMod { safety, .. }) => {
307 if let Safety::Unsafe(_) = safety {
308 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeExternBlock);
309 }
310 }
311
312 ast::ItemKind::MacroDef(..) => {
313 if let Some(hir::Attribute::Parsed(AttributeKind::AllowInternalUnsafe(span))) =
314 AttributeParser::parse_limited(
315 cx.builder.sess(),
316 &it.attrs,
317 sym::allow_internal_unsafe,
318 it.span,
319 DUMMY_NODE_ID,
320 Some(cx.builder.features()),
321 )
322 {
323 self.report_unsafe(cx, span, BuiltinUnsafe::AllowInternalUnsafe);
324 }
325 }
326
327 _ => {}
328 }
329 }
330
331 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
332 if let ast::AssocItemKind::Fn(..) = it.kind {
333 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
334 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleMethod);
335 }
336 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
337 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameMethod);
338 }
339 }
340 }
341
342 fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
343 if let FnKind::Fn(
344 ctxt,
345 _,
346 ast::Fn {
347 sig: ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
348 body,
349 ..
350 },
351 ) = fk
352 {
353 let decorator = match ctxt {
354 FnCtxt::Foreign => return,
355 FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
356 FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
357 FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
358 };
359 self.report_unsafe(cx, span, decorator);
360 }
361 }
362}
363
364declare_lint! {
365 /// The `missing_docs` lint detects missing documentation for public items.
366 ///
367 /// ### Example
368 ///
369 /// ```rust,compile_fail
370 /// #![deny(missing_docs)]
371 /// pub fn foo() {}
372 /// ```
373 ///
374 /// {{produces}}
375 ///
376 /// ### Explanation
377 ///
378 /// This lint is intended to ensure that a library is well-documented.
379 /// Items without documentation can be difficult for users to understand
380 /// how to use properly.
381 ///
382 /// This lint is "allow" by default because it can be noisy, and not all
383 /// projects may want to enforce everything to be documented.
384 pub MISSING_DOCS,
385 Allow,
386 "detects missing documentation for public members",
387 report_in_external_macro
388}
389
390#[derive(Default)]
391pub struct MissingDoc;
392
393impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
394
395fn has_doc(attr: &hir::Attribute) -> bool {
396 if attr.is_doc_comment() {
397 return true;
398 }
399
400 if !attr.has_name(sym::doc) {
401 return false;
402 }
403
404 if attr.value_str().is_some() {
405 return true;
406 }
407
408 if let Some(list) = attr.meta_item_list() {
409 for meta in list {
410 if meta.has_name(sym::hidden) {
411 return true;
412 }
413 }
414 }
415
416 false
417}
418
419impl MissingDoc {
420 fn check_missing_docs_attrs(
421 &self,
422 cx: &LateContext<'_>,
423 def_id: LocalDefId,
424 article: &'static str,
425 desc: &'static str,
426 ) {
427 // Only check publicly-visible items, using the result from the privacy pass.
428 // It's an option so the crate root can also use this function (it doesn't
429 // have a `NodeId`).
430 if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
431 return;
432 }
433
434 let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
435 let has_doc = attrs.iter().any(has_doc);
436 if !has_doc {
437 cx.emit_span_lint(
438 MISSING_DOCS,
439 cx.tcx.def_span(def_id),
440 BuiltinMissingDoc { article, desc },
441 );
442 }
443 }
444}
445
446impl<'tcx> LateLintPass<'tcx> for MissingDoc {
447 fn check_crate(&mut self, cx: &LateContext<'_>) {
448 self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
449 }
450
451 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
452 // Previously the Impl and Use types have been excluded from missing docs,
453 // so we will continue to exclude them for compatibility.
454 //
455 // The documentation on `ExternCrate` is not used at the moment so no need to warn for it.
456 if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(..) =
457 it.kind
458 {
459 return;
460 }
461
462 let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
463 self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
464 }
465
466 fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
467 let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
468
469 self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
470 }
471
472 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
473 let container = cx.tcx.associated_item(impl_item.owner_id.def_id).container;
474
475 match container {
476 // If the method is an impl for a trait, don't doc.
477 AssocContainer::TraitImpl(_) => return,
478 AssocContainer::Trait => {}
479 // If the method is an impl for an item with docs_hidden, don't doc.
480 AssocContainer::InherentImpl => {
481 let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id());
482 let impl_ty = cx.tcx.type_of(parent).instantiate_identity();
483 let outerdef = match impl_ty.kind() {
484 ty::Adt(def, _) => Some(def.did()),
485 ty::Foreign(def_id) => Some(*def_id),
486 _ => None,
487 };
488 let is_hidden = match outerdef {
489 Some(id) => cx.tcx.is_doc_hidden(id),
490 None => false,
491 };
492 if is_hidden {
493 return;
494 }
495 }
496 }
497
498 let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
499 self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
500 }
501
502 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
503 let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
504 self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
505 }
506
507 fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
508 if !sf.is_positional() {
509 self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
510 }
511 }
512
513 fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
514 self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
515 }
516}
517
518declare_lint! {
519 /// The `missing_copy_implementations` lint detects potentially-forgotten
520 /// implementations of [`Copy`] for public types.
521 ///
522 /// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
523 ///
524 /// ### Example
525 ///
526 /// ```rust,compile_fail
527 /// #![deny(missing_copy_implementations)]
528 /// pub struct Foo {
529 /// pub field: i32
530 /// }
531 /// # fn main() {}
532 /// ```
533 ///
534 /// {{produces}}
535 ///
536 /// ### Explanation
537 ///
538 /// Historically (before 1.0), types were automatically marked as `Copy`
539 /// if possible. This was changed so that it required an explicit opt-in
540 /// by implementing the `Copy` trait. As part of this change, a lint was
541 /// added to alert if a copyable type was not marked `Copy`.
542 ///
543 /// This lint is "allow" by default because this code isn't bad; it is
544 /// common to write newtypes like this specifically so that a `Copy` type
545 /// is no longer `Copy`. `Copy` types can result in unintended copies of
546 /// large data which can impact performance.
547 pub MISSING_COPY_IMPLEMENTATIONS,
548 Allow,
549 "detects potentially-forgotten implementations of `Copy`"
550}
551
552declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
553
554impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
555 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
556 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
557 return;
558 }
559 let (def, ty) = match item.kind {
560 hir::ItemKind::Struct(_, generics, _) => {
561 if !generics.params.is_empty() {
562 return;
563 }
564 let def = cx.tcx.adt_def(item.owner_id);
565 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
566 }
567 hir::ItemKind::Union(_, generics, _) => {
568 if !generics.params.is_empty() {
569 return;
570 }
571 let def = cx.tcx.adt_def(item.owner_id);
572 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
573 }
574 hir::ItemKind::Enum(_, generics, _) => {
575 if !generics.params.is_empty() {
576 return;
577 }
578 let def = cx.tcx.adt_def(item.owner_id);
579 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
580 }
581 _ => return,
582 };
583 if def.has_dtor(cx.tcx) {
584 return;
585 }
586
587 // If the type contains a raw pointer, it may represent something like a handle,
588 // and recommending Copy might be a bad idea.
589 for field in def.all_fields() {
590 let did = field.did;
591 if cx.tcx.type_of(did).instantiate_identity().is_raw_ptr() {
592 return;
593 }
594 }
595 if cx.type_is_copy_modulo_regions(ty) {
596 return;
597 }
598 if type_implements_negative_copy_modulo_regions(cx.tcx, ty, cx.typing_env()) {
599 return;
600 }
601 if def.is_variant_list_non_exhaustive()
602 || def.variants().iter().any(|variant| variant.is_field_list_non_exhaustive())
603 {
604 return;
605 }
606
607 // We shouldn't recommend implementing `Copy` on stateful things,
608 // such as iterators.
609 if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
610 && cx
611 .tcx
612 .infer_ctxt()
613 .build(cx.typing_mode())
614 .type_implements_trait(iter_trait, [ty], cx.param_env)
615 .must_apply_modulo_regions()
616 {
617 return;
618 }
619
620 // Default value of clippy::trivially_copy_pass_by_ref
621 const MAX_SIZE: u64 = 256;
622
623 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
624 if size > MAX_SIZE {
625 return;
626 }
627 }
628
629 if type_allowed_to_implement_copy(
630 cx.tcx,
631 cx.param_env,
632 ty,
633 traits::ObligationCause::misc(item.span, item.owner_id.def_id),
634 hir::Safety::Safe,
635 )
636 .is_ok()
637 {
638 cx.emit_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
639 }
640 }
641}
642
643/// Check whether a `ty` has a negative `Copy` implementation, ignoring outlives constraints.
644fn type_implements_negative_copy_modulo_regions<'tcx>(
645 tcx: TyCtxt<'tcx>,
646 ty: Ty<'tcx>,
647 typing_env: ty::TypingEnv<'tcx>,
648) -> bool {
649 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
650 let trait_ref =
651 ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, DUMMY_SP), [ty]);
652 let pred = ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Negative };
653 let obligation = traits::Obligation {
654 cause: traits::ObligationCause::dummy(),
655 param_env,
656 recursion_depth: 0,
657 predicate: pred.upcast(tcx),
658 };
659 infcx.predicate_must_hold_modulo_regions(&obligation)
660}
661
662declare_lint! {
663 /// The `missing_debug_implementations` lint detects missing
664 /// implementations of [`fmt::Debug`] for public types.
665 ///
666 /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
667 ///
668 /// ### Example
669 ///
670 /// ```rust,compile_fail
671 /// #![deny(missing_debug_implementations)]
672 /// pub struct Foo;
673 /// # fn main() {}
674 /// ```
675 ///
676 /// {{produces}}
677 ///
678 /// ### Explanation
679 ///
680 /// Having a `Debug` implementation on all types can assist with
681 /// debugging, as it provides a convenient way to format and display a
682 /// value. Using the `#[derive(Debug)]` attribute will automatically
683 /// generate a typical implementation, or a custom implementation can be
684 /// added by manually implementing the `Debug` trait.
685 ///
686 /// This lint is "allow" by default because adding `Debug` to all types can
687 /// have a negative impact on compile time and code size. It also requires
688 /// boilerplate to be added to every type, which can be an impediment.
689 MISSING_DEBUG_IMPLEMENTATIONS,
690 Allow,
691 "detects missing implementations of Debug"
692}
693
694#[derive(Default)]
695pub(crate) struct MissingDebugImplementations;
696
697impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
698
699impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
700 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
701 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
702 return;
703 }
704
705 match item.kind {
706 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
707 _ => return,
708 }
709
710 // Avoid listing trait impls if the trait is allowed.
711 let LevelAndSource { level, .. } =
712 cx.tcx.lint_level_at_node(MISSING_DEBUG_IMPLEMENTATIONS, item.hir_id());
713 if level == Level::Allow {
714 return;
715 }
716
717 let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return };
718
719 let has_impl = cx
720 .tcx
721 .non_blanket_impls_for_ty(debug, cx.tcx.type_of(item.owner_id).instantiate_identity())
722 .next()
723 .is_some();
724 if !has_impl {
725 cx.emit_span_lint(
726 MISSING_DEBUG_IMPLEMENTATIONS,
727 item.span,
728 BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
729 );
730 }
731 }
732}
733
734declare_lint! {
735 /// The `anonymous_parameters` lint detects anonymous parameters in trait
736 /// definitions.
737 ///
738 /// ### Example
739 ///
740 /// ```rust,edition2015,compile_fail
741 /// #![deny(anonymous_parameters)]
742 /// // edition 2015
743 /// pub trait Foo {
744 /// fn foo(usize);
745 /// }
746 /// fn main() {}
747 /// ```
748 ///
749 /// {{produces}}
750 ///
751 /// ### Explanation
752 ///
753 /// This syntax is mostly a historical accident, and can be worked around
754 /// quite easily by adding an `_` pattern or a descriptive identifier:
755 ///
756 /// ```rust
757 /// trait Foo {
758 /// fn foo(_: usize);
759 /// }
760 /// ```
761 ///
762 /// This syntax is now a hard error in the 2018 edition. In the 2015
763 /// edition, this lint is "warn" by default. This lint
764 /// enables the [`cargo fix`] tool with the `--edition` flag to
765 /// automatically transition old code from the 2015 edition to 2018. The
766 /// tool will run this lint and automatically apply the
767 /// suggested fix from the compiler (which is to add `_` to each
768 /// parameter). This provides a completely automated way to update old
769 /// code for a new edition. See [issue #41686] for more details.
770 ///
771 /// [issue #41686]: https://github.com/rust-lang/rust/issues/41686
772 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
773 pub ANONYMOUS_PARAMETERS,
774 Warn,
775 "detects anonymous parameters",
776 @future_incompatible = FutureIncompatibleInfo {
777 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
778 reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
779 };
780}
781
782declare_lint_pass!(
783 /// Checks for use of anonymous parameters (RFC 1685).
784 AnonymousParameters => [ANONYMOUS_PARAMETERS]
785);
786
787impl EarlyLintPass for AnonymousParameters {
788 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
789 if cx.sess().edition() != Edition::Edition2015 {
790 // This is a hard error in future editions; avoid linting and erroring
791 return;
792 }
793 if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
794 for arg in sig.decl.inputs.iter() {
795 if let ast::PatKind::Missing = arg.pat.kind {
796 let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
797
798 let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
799 (snip.as_str(), Applicability::MachineApplicable)
800 } else {
801 ("<type>", Applicability::HasPlaceholders)
802 };
803 cx.emit_span_lint(
804 ANONYMOUS_PARAMETERS,
805 arg.pat.span,
806 BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
807 );
808 }
809 }
810 }
811 }
812}
813
814fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
815 use rustc_ast::token::CommentKind;
816
817 let mut attrs = attrs.iter().peekable();
818
819 // Accumulate a single span for sugared doc comments.
820 let mut sugared_span: Option<Span> = None;
821
822 while let Some(attr) = attrs.next() {
823 let is_doc_comment = attr.is_doc_comment();
824 if is_doc_comment {
825 sugared_span =
826 Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
827 }
828
829 if attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
830 continue;
831 }
832
833 let span = sugared_span.take().unwrap_or(attr.span);
834
835 if is_doc_comment || attr.has_name(sym::doc) {
836 let sub = match attr.kind {
837 AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
838 BuiltinUnusedDocCommentSub::PlainHelp
839 }
840 AttrKind::DocComment(CommentKind::Block, _) => {
841 BuiltinUnusedDocCommentSub::BlockHelp
842 }
843 };
844 cx.emit_span_lint(
845 UNUSED_DOC_COMMENTS,
846 span,
847 BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
848 );
849 }
850 }
851}
852
853impl EarlyLintPass for UnusedDocComment {
854 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
855 let kind = match stmt.kind {
856 ast::StmtKind::Let(..) => "statements",
857 // Disabled pending discussion in #78306
858 ast::StmtKind::Item(..) => return,
859 // expressions will be reported by `check_expr`.
860 ast::StmtKind::Empty
861 | ast::StmtKind::Semi(_)
862 | ast::StmtKind::Expr(_)
863 | ast::StmtKind::MacCall(_) => return,
864 };
865
866 warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
867 }
868
869 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
870 if let Some(body) = &arm.body {
871 let arm_span = arm.pat.span.with_hi(body.span.hi());
872 warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
873 }
874 }
875
876 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
877 if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind {
878 for field in fields {
879 warn_if_doc(cx, field.span, "pattern fields", &field.attrs);
880 }
881 }
882 }
883
884 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
885 warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
886
887 if let ExprKind::Struct(s) = &expr.kind {
888 for field in &s.fields {
889 warn_if_doc(cx, field.span, "expression fields", &field.attrs);
890 }
891 }
892 }
893
894 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
895 warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs);
896 }
897
898 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
899 warn_if_doc(cx, block.span, "blocks", block.attrs());
900 }
901
902 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
903 if let ast::ItemKind::ForeignMod(_) = item.kind {
904 warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
905 }
906 }
907}
908
909declare_lint! {
910 /// The `no_mangle_const_items` lint detects any `const` items with the
911 /// [`no_mangle` attribute].
912 ///
913 /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
914 ///
915 /// ### Example
916 ///
917 /// ```rust,compile_fail,edition2021
918 /// #[no_mangle]
919 /// const FOO: i32 = 5;
920 /// ```
921 ///
922 /// {{produces}}
923 ///
924 /// ### Explanation
925 ///
926 /// Constants do not have their symbols exported, and therefore, this
927 /// probably means you meant to use a [`static`], not a [`const`].
928 ///
929 /// [`static`]: https://doc.rust-lang.org/reference/items/static-items.html
930 /// [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html
931 NO_MANGLE_CONST_ITEMS,
932 Deny,
933 "const items will not have their symbols exported"
934}
935
936declare_lint! {
937 /// The `no_mangle_generic_items` lint detects generic items that must be
938 /// mangled.
939 ///
940 /// ### Example
941 ///
942 /// ```rust
943 /// #[unsafe(no_mangle)]
944 /// fn foo<T>(t: T) {}
945 ///
946 /// #[unsafe(export_name = "bar")]
947 /// fn bar<T>(t: T) {}
948 /// ```
949 ///
950 /// {{produces}}
951 ///
952 /// ### Explanation
953 ///
954 /// A function with generics must have its symbol mangled to accommodate
955 /// the generic parameter. The [`no_mangle`] and [`export_name`] attributes
956 /// have no effect in this situation, and should be removed.
957 ///
958 /// [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
959 /// [`export_name`]: https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute
960 NO_MANGLE_GENERIC_ITEMS,
961 Warn,
962 "generic items must be mangled"
963}
964
965declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
966
967impl InvalidNoMangleItems {
968 fn check_no_mangle_on_generic_fn(
969 &self,
970 cx: &LateContext<'_>,
971 attr_span: Span,
972 def_id: LocalDefId,
973 ) {
974 let generics = cx.tcx.generics_of(def_id);
975 if generics.requires_monomorphization(cx.tcx) {
976 cx.emit_span_lint(
977 NO_MANGLE_GENERIC_ITEMS,
978 cx.tcx.def_span(def_id),
979 BuiltinNoMangleGeneric { suggestion: attr_span },
980 );
981 }
982 }
983}
984
985impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
986 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
987 let attrs = cx.tcx.hir_attrs(it.hir_id());
988 match it.kind {
989 hir::ItemKind::Fn { .. } => {
990 if let Some(attr_span) =
991 find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
992 .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
993 {
994 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
995 }
996 }
997 hir::ItemKind::Const(..) => {
998 if find_attr!(attrs, AttributeKind::NoMangle(..)) {
999 // account for "pub const" (#45562)
1000 let start = cx
1001 .tcx
1002 .sess
1003 .source_map()
1004 .span_to_snippet(it.span)
1005 .map(|snippet| snippet.find("const").unwrap_or(0))
1006 .unwrap_or(0) as u32;
1007 // `const` is 5 chars
1008 let suggestion = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1009
1010 // Const items do not refer to a particular location in memory, and therefore
1011 // don't have anything to attach a symbol to
1012 cx.emit_span_lint(
1013 NO_MANGLE_CONST_ITEMS,
1014 it.span,
1015 BuiltinConstNoMangle { suggestion },
1016 );
1017 }
1018 }
1019 _ => {}
1020 }
1021 }
1022
1023 fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) {
1024 let attrs = cx.tcx.hir_attrs(it.hir_id());
1025 match it.kind {
1026 hir::ImplItemKind::Fn { .. } => {
1027 if let Some(attr_span) =
1028 find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
1029 .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
1030 {
1031 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
1032 }
1033 }
1034 _ => {}
1035 }
1036 }
1037}
1038
1039declare_lint! {
1040 /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1041 /// T` because it is [undefined behavior].
1042 ///
1043 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1044 ///
1045 /// ### Example
1046 ///
1047 /// ```rust,compile_fail
1048 /// unsafe {
1049 /// let y = std::mem::transmute::<&i32, &mut i32>(&5);
1050 /// }
1051 /// ```
1052 ///
1053 /// {{produces}}
1054 ///
1055 /// ### Explanation
1056 ///
1057 /// Certain assumptions are made about aliasing of data, and this transmute
1058 /// violates those assumptions. Consider using [`UnsafeCell`] instead.
1059 ///
1060 /// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1061 MUTABLE_TRANSMUTES,
1062 Deny,
1063 "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1064}
1065
1066declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1067
1068impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1069 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1070 if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1071 get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1072 {
1073 if from_mutbl < to_mutbl {
1074 cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1075 }
1076 }
1077
1078 fn get_transmute_from_to<'tcx>(
1079 cx: &LateContext<'tcx>,
1080 expr: &hir::Expr<'_>,
1081 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1082 let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
1083 cx.qpath_res(qpath, expr.hir_id)
1084 } else {
1085 return None;
1086 };
1087 if let Res::Def(DefKind::Fn, did) = def {
1088 if !def_id_is_transmute(cx, did) {
1089 return None;
1090 }
1091 let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1092 let from = sig.inputs().skip_binder()[0];
1093 let to = sig.output().skip_binder();
1094 return Some((from, to));
1095 }
1096 None
1097 }
1098
1099 fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1100 cx.tcx.is_intrinsic(def_id, sym::transmute)
1101 }
1102 }
1103}
1104
1105declare_lint! {
1106 /// The `unstable_features` lint detects uses of `#![feature]`.
1107 ///
1108 /// ### Example
1109 ///
1110 /// ```rust,compile_fail
1111 /// #![deny(unstable_features)]
1112 /// #![feature(test)]
1113 /// ```
1114 ///
1115 /// {{produces}}
1116 ///
1117 /// ### Explanation
1118 ///
1119 /// In larger nightly-based projects which
1120 ///
1121 /// * consist of a multitude of crates where a subset of crates has to compile on
1122 /// stable either unconditionally or depending on a `cfg` flag to for example
1123 /// allow stable users to depend on them,
1124 /// * don't use nightly for experimental features but for, e.g., unstable options only,
1125 ///
1126 /// this lint may come in handy to enforce policies of these kinds.
1127 UNSTABLE_FEATURES,
1128 Allow,
1129 "enabling unstable features"
1130}
1131
1132declare_lint_pass!(
1133 /// Forbids using the `#[feature(...)]` attribute
1134 UnstableFeatures => [UNSTABLE_FEATURES]
1135);
1136
1137impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
1138 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &hir::Attribute) {
1139 if attr.has_name(sym::feature)
1140 && let Some(items) = attr.meta_item_list()
1141 {
1142 for item in items {
1143 cx.emit_span_lint(UNSTABLE_FEATURES, item.span(), BuiltinUnstableFeatures);
1144 }
1145 }
1146 }
1147}
1148
1149declare_lint! {
1150 /// The `ungated_async_fn_track_caller` lint warns when the
1151 /// `#[track_caller]` attribute is used on an async function
1152 /// without enabling the corresponding unstable feature flag.
1153 ///
1154 /// ### Example
1155 ///
1156 /// ```rust
1157 /// #[track_caller]
1158 /// async fn foo() {}
1159 /// ```
1160 ///
1161 /// {{produces}}
1162 ///
1163 /// ### Explanation
1164 ///
1165 /// The attribute must be used in conjunction with the
1166 /// [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`
1167 /// annotation will function as a no-op.
1168 ///
1169 /// [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html
1170 UNGATED_ASYNC_FN_TRACK_CALLER,
1171 Warn,
1172 "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled"
1173}
1174
1175declare_lint_pass!(
1176 /// Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to
1177 /// do anything
1178 UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1179);
1180
1181impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
1182 fn check_fn(
1183 &mut self,
1184 cx: &LateContext<'_>,
1185 fn_kind: HirFnKind<'_>,
1186 _: &'tcx FnDecl<'_>,
1187 _: &'tcx Body<'_>,
1188 span: Span,
1189 def_id: LocalDefId,
1190 ) {
1191 if fn_kind.asyncness().is_async()
1192 && !cx.tcx.features().async_fn_track_caller()
1193 // Now, check if the function has the `#[track_caller]` attribute
1194 && let Some(attr_span) = find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::TrackCaller(span) => *span)
1195 {
1196 cx.emit_span_lint(
1197 UNGATED_ASYNC_FN_TRACK_CALLER,
1198 attr_span,
1199 BuiltinUngatedAsyncFnTrackCaller { label: span, session: &cx.tcx.sess },
1200 );
1201 }
1202 }
1203}
1204
1205declare_lint! {
1206 /// The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that
1207 /// means neither directly accessible, nor reexported (with `pub use`), nor leaked through
1208 /// things like return types (which the [`unnameable_types`] lint can detect if desired).
1209 ///
1210 /// ### Example
1211 ///
1212 /// ```rust,compile_fail
1213 /// #![deny(unreachable_pub)]
1214 /// mod foo {
1215 /// pub mod bar {
1216 ///
1217 /// }
1218 /// }
1219 /// ```
1220 ///
1221 /// {{produces}}
1222 ///
1223 /// ### Explanation
1224 ///
1225 /// The `pub` keyword both expresses an intent for an item to be publicly available, and also
1226 /// signals to the compiler to make the item publicly accessible. The intent can only be
1227 /// satisfied, however, if all items which contain this item are *also* publicly accessible.
1228 /// Thus, this lint serves to identify situations where the intent does not match the reality.
1229 ///
1230 /// If you wish the item to be accessible elsewhere within the crate, but not outside it, the
1231 /// `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the
1232 /// intent that the item is only visible within its own crate.
1233 ///
1234 /// This lint is "allow" by default because it will trigger for a large amount of existing Rust code.
1235 /// Eventually it is desired for this to become warn-by-default.
1236 ///
1237 /// [`unnameable_types`]: #unnameable-types
1238 pub UNREACHABLE_PUB,
1239 Allow,
1240 "`pub` items not reachable from crate root"
1241}
1242
1243declare_lint_pass!(
1244 /// Lint for items marked `pub` that aren't reachable from other crates.
1245 UnreachablePub => [UNREACHABLE_PUB]
1246);
1247
1248impl UnreachablePub {
1249 fn perform_lint(
1250 &self,
1251 cx: &LateContext<'_>,
1252 what: &str,
1253 def_id: LocalDefId,
1254 vis_span: Span,
1255 exportable: bool,
1256 ) {
1257 let mut applicability = Applicability::MachineApplicable;
1258 if cx.tcx.visibility(def_id).is_public() && !cx.effective_visibilities.is_reachable(def_id)
1259 {
1260 // prefer suggesting `pub(super)` instead of `pub(crate)` when possible,
1261 // except when `pub(super) == pub(crate)`
1262 let new_vis = if let Some(ty::Visibility::Restricted(restricted_did)) =
1263 cx.effective_visibilities.effective_vis(def_id).map(|effective_vis| {
1264 effective_vis.at_level(rustc_middle::middle::privacy::Level::Reachable)
1265 })
1266 && let parent_parent = cx
1267 .tcx
1268 .parent_module_from_def_id(cx.tcx.parent_module_from_def_id(def_id).into())
1269 && *restricted_did == parent_parent.to_local_def_id()
1270 && !restricted_did.to_def_id().is_crate_root()
1271 {
1272 "pub(super)"
1273 } else {
1274 "pub(crate)"
1275 };
1276
1277 if vis_span.from_expansion() {
1278 applicability = Applicability::MaybeIncorrect;
1279 }
1280 let def_span = cx.tcx.def_span(def_id);
1281 cx.emit_span_lint(
1282 UNREACHABLE_PUB,
1283 def_span,
1284 BuiltinUnreachablePub {
1285 what,
1286 new_vis,
1287 suggestion: (vis_span, applicability),
1288 help: exportable,
1289 },
1290 );
1291 }
1292 }
1293}
1294
1295impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
1296 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1297 // Do not warn for fake `use` statements.
1298 if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind {
1299 return;
1300 }
1301 self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1302 }
1303
1304 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1305 self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1306 }
1307
1308 fn check_field_def(&mut self, _cx: &LateContext<'_>, _field: &hir::FieldDef<'_>) {
1309 // - If an ADT definition is reported then we don't need to check fields
1310 // (as it would add unnecessary complexity to the source code, the struct
1311 // definition is in the immediate proximity to give the "real" visibility).
1312 // - If an ADT is not reported because it's not `pub` - we don't need to
1313 // check fields.
1314 // - If an ADT is not reported because it's reachable - we also don't need
1315 // to check fields because then they are reachable by construction if they
1316 // are pub.
1317 //
1318 // Therefore in no case we check the fields.
1319 //
1320 // cf. https://github.com/rust-lang/rust/pull/126013#issuecomment-2152839205
1321 // cf. https://github.com/rust-lang/rust/pull/126040#issuecomment-2152944506
1322 }
1323
1324 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1325 if let ImplItemImplKind::Inherent { vis_span } = impl_item.impl_kind {
1326 self.perform_lint(cx, "item", impl_item.owner_id.def_id, vis_span, false);
1327 }
1328 }
1329}
1330
1331declare_lint! {
1332 /// The `type_alias_bounds` lint detects bounds in type aliases.
1333 ///
1334 /// ### Example
1335 ///
1336 /// ```rust
1337 /// type SendVec<T: Send> = Vec<T>;
1338 /// ```
1339 ///
1340 /// {{produces}}
1341 ///
1342 /// ### Explanation
1343 ///
1344 /// Trait and lifetime bounds on generic parameters and in where clauses of
1345 /// type aliases are not checked at usage sites of the type alias. Moreover,
1346 /// they are not thoroughly checked for correctness at their definition site
1347 /// either similar to the aliased type.
1348 ///
1349 /// This is a known limitation of the type checker that may be lifted in a
1350 /// future edition. Permitting such bounds in light of this was unintentional.
1351 ///
1352 /// While these bounds may have secondary effects such as enabling the use of
1353 /// "shorthand" associated type paths[^1] and affecting the default trait
1354 /// object lifetime[^2] of trait object types passed to the type alias, this
1355 /// should not have been allowed until the aforementioned restrictions of the
1356 /// type checker have been lifted.
1357 ///
1358 /// Using such bounds is highly discouraged as they are actively misleading.
1359 ///
1360 /// [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter
1361 /// bounded by trait `Trait` which defines an associated type called `Assoc`
1362 /// as opposed to a fully qualified path of the form `<T as Trait>::Assoc`.
1363 /// [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>
1364 TYPE_ALIAS_BOUNDS,
1365 Warn,
1366 "bounds in type aliases are not enforced"
1367}
1368
1369declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]);
1370
1371impl TypeAliasBounds {
1372 pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool {
1373 // Bounds of the form `T: 'a` with `T` type param affect object lifetime defaults.
1374 if let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind
1375 && pred.bounds.iter().any(|bound| matches!(bound, hir::GenericBound::Outlives(_)))
1376 && pred.bound_generic_params.is_empty() // indeed, even if absent from the RHS
1377 && pred.bounded_ty.as_generic_param().is_some()
1378 {
1379 return true;
1380 }
1381 false
1382 }
1383}
1384
1385impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
1386 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1387 let hir::ItemKind::TyAlias(_, generics, hir_ty) = item.kind else { return };
1388
1389 // There must not be a where clause.
1390 if generics.predicates.is_empty() {
1391 return;
1392 }
1393
1394 // Bounds of lazy type aliases and TAITs are respected.
1395 if cx.tcx.type_alias_is_lazy(item.owner_id) {
1396 return;
1397 }
1398
1399 // FIXME(generic_const_exprs): Revisit this before stabilization.
1400 // See also `tests/ui/const-generics/generic_const_exprs/type-alias-bounds.rs`.
1401 let ty = cx.tcx.type_of(item.owner_id).instantiate_identity();
1402 if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION)
1403 && cx.tcx.features().generic_const_exprs()
1404 {
1405 return;
1406 }
1407
1408 // NOTE(inherent_associated_types): While we currently do take some bounds in type
1409 // aliases into consideration during IAT *selection*, we don't perform full use+def
1410 // site wfchecking for such type aliases. Therefore TAB should still trigger.
1411 // See also `tests/ui/associated-inherent-types/type-alias-bounds.rs`.
1412
1413 let mut where_spans = Vec::new();
1414 let mut inline_spans = Vec::new();
1415 let mut inline_sugg = Vec::new();
1416
1417 for p in generics.predicates {
1418 let span = p.span;
1419 if p.kind.in_where_clause() {
1420 where_spans.push(span);
1421 } else {
1422 for b in p.kind.bounds() {
1423 inline_spans.push(b.span());
1424 }
1425 inline_sugg.push((span, String::new()));
1426 }
1427 }
1428
1429 let mut ty = Some(hir_ty);
1430 let enable_feat_help = cx.tcx.sess.is_nightly_build();
1431
1432 if let [.., label_sp] = *where_spans {
1433 cx.emit_span_lint(
1434 TYPE_ALIAS_BOUNDS,
1435 where_spans,
1436 BuiltinTypeAliasBounds {
1437 in_where_clause: true,
1438 label: label_sp,
1439 enable_feat_help,
1440 suggestions: vec![(generics.where_clause_span, String::new())],
1441 preds: generics.predicates,
1442 ty: ty.take(),
1443 },
1444 );
1445 }
1446 if let [.., label_sp] = *inline_spans {
1447 cx.emit_span_lint(
1448 TYPE_ALIAS_BOUNDS,
1449 inline_spans,
1450 BuiltinTypeAliasBounds {
1451 in_where_clause: false,
1452 label: label_sp,
1453 enable_feat_help,
1454 suggestions: inline_sugg,
1455 preds: generics.predicates,
1456 ty,
1457 },
1458 );
1459 }
1460 }
1461}
1462
1463pub(crate) struct ShorthandAssocTyCollector {
1464 pub(crate) qselves: Vec<Span>,
1465}
1466
1467impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector {
1468 fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) {
1469 // Look for "type-parameter shorthand-associated-types". I.e., paths of the
1470 // form `T::Assoc` with `T` type param. These are reliant on trait bounds.
1471 if let hir::QPath::TypeRelative(qself, _) = qpath
1472 && qself.as_generic_param().is_some()
1473 {
1474 self.qselves.push(qself.span);
1475 }
1476 hir::intravisit::walk_qpath(self, qpath, id)
1477 }
1478}
1479
1480declare_lint! {
1481 /// The `trivial_bounds` lint detects trait bounds that don't depend on
1482 /// any type parameters.
1483 ///
1484 /// ### Example
1485 ///
1486 /// ```rust
1487 /// #![feature(trivial_bounds)]
1488 /// pub struct A where i32: Copy;
1489 /// ```
1490 ///
1491 /// {{produces}}
1492 ///
1493 /// ### Explanation
1494 ///
1495 /// Usually you would not write a trait bound that you know is always
1496 /// true, or never true. However, when using macros, the macro may not
1497 /// know whether or not the constraint would hold or not at the time when
1498 /// generating the code. Currently, the compiler does not alert you if the
1499 /// constraint is always true, and generates an error if it is never true.
1500 /// The `trivial_bounds` feature changes this to be a warning in both
1501 /// cases, giving macros more freedom and flexibility to generate code,
1502 /// while still providing a signal when writing non-macro code that
1503 /// something is amiss.
1504 ///
1505 /// See [RFC 2056] for more details. This feature is currently only
1506 /// available on the nightly channel, see [tracking issue #48214].
1507 ///
1508 /// [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md
1509 /// [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214
1510 TRIVIAL_BOUNDS,
1511 Warn,
1512 "these bounds don't depend on an type parameters"
1513}
1514
1515declare_lint_pass!(
1516 /// Lint for trait and lifetime bounds that don't depend on type parameters
1517 /// which either do nothing, or stop the item from being used.
1518 TrivialConstraints => [TRIVIAL_BOUNDS]
1519);
1520
1521impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
1522 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1523 use rustc_middle::ty::ClauseKind;
1524
1525 if cx.tcx.features().trivial_bounds() {
1526 let predicates = cx.tcx.predicates_of(item.owner_id);
1527 for &(predicate, span) in predicates.predicates {
1528 let predicate_kind_name = match predicate.kind().skip_binder() {
1529 ClauseKind::Trait(..) => "trait",
1530 ClauseKind::TypeOutlives(..) |
1531 ClauseKind::RegionOutlives(..) => "lifetime",
1532
1533 ClauseKind::UnstableFeature(_)
1534 // `ConstArgHasType` is never global as `ct` is always a param
1535 | ClauseKind::ConstArgHasType(..)
1536 // Ignore projections, as they can only be global
1537 // if the trait bound is global
1538 | ClauseKind::Projection(..)
1539 // Ignore bounds that a user can't type
1540 | ClauseKind::WellFormed(..)
1541 // FIXME(generic_const_exprs): `ConstEvaluatable` can be written
1542 | ClauseKind::ConstEvaluatable(..)
1543 // Users don't write this directly, only via another trait ref.
1544 | ty::ClauseKind::HostEffect(..) => continue,
1545 };
1546 if predicate.is_global() {
1547 cx.emit_span_lint(
1548 TRIVIAL_BOUNDS,
1549 span,
1550 BuiltinTrivialBounds { predicate_kind_name, predicate },
1551 );
1552 }
1553 }
1554 }
1555 }
1556}
1557
1558declare_lint! {
1559 /// The `double_negations` lint detects expressions of the form `--x`.
1560 ///
1561 /// ### Example
1562 ///
1563 /// ```rust
1564 /// fn main() {
1565 /// let x = 1;
1566 /// let _b = --x;
1567 /// }
1568 /// ```
1569 ///
1570 /// {{produces}}
1571 ///
1572 /// ### Explanation
1573 ///
1574 /// Negating something twice is usually the same as not negating it at all.
1575 /// However, a double negation in Rust can easily be confused with the
1576 /// prefix decrement operator that exists in many languages derived from C.
1577 /// Use `-(-x)` if you really wanted to negate the value twice.
1578 ///
1579 /// To decrement a value, use `x -= 1` instead.
1580 pub DOUBLE_NEGATIONS,
1581 Warn,
1582 "detects expressions of the form `--x`"
1583}
1584
1585declare_lint_pass!(
1586 /// Lint for expressions of the form `--x` that can be confused with C's
1587 /// prefix decrement operator.
1588 DoubleNegations => [DOUBLE_NEGATIONS]
1589);
1590
1591impl EarlyLintPass for DoubleNegations {
1592 #[inline]
1593 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1594 // only lint on the innermost `--` in a chain of `-` operators,
1595 // even if there are 3 or more negations
1596 if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1597 && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1598 && !matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1599 // Don't lint if this jumps macro expansion boundary (Issue #143980)
1600 && expr.span.eq_ctxt(inner.span)
1601 {
1602 cx.emit_span_lint(
1603 DOUBLE_NEGATIONS,
1604 expr.span,
1605 BuiltinDoubleNegations {
1606 add_parens: BuiltinDoubleNegationsAddParens {
1607 start_span: inner.span.shrink_to_lo(),
1608 end_span: inner.span.shrink_to_hi(),
1609 },
1610 },
1611 );
1612 }
1613 }
1614}
1615
1616declare_lint_pass!(
1617 /// Does nothing as a lint pass, but registers some `Lint`s
1618 /// which are used by other parts of the compiler.
1619 SoftLints => [
1620 WHILE_TRUE,
1621 NON_SHORTHAND_FIELD_PATTERNS,
1622 UNSAFE_CODE,
1623 MISSING_DOCS,
1624 MISSING_COPY_IMPLEMENTATIONS,
1625 MISSING_DEBUG_IMPLEMENTATIONS,
1626 ANONYMOUS_PARAMETERS,
1627 UNUSED_DOC_COMMENTS,
1628 NO_MANGLE_CONST_ITEMS,
1629 NO_MANGLE_GENERIC_ITEMS,
1630 MUTABLE_TRANSMUTES,
1631 UNSTABLE_FEATURES,
1632 UNREACHABLE_PUB,
1633 TYPE_ALIAS_BOUNDS,
1634 TRIVIAL_BOUNDS,
1635 DOUBLE_NEGATIONS
1636 ]
1637);
1638
1639declare_lint! {
1640 /// The `ellipsis_inclusive_range_patterns` lint detects the [`...` range
1641 /// pattern], which is deprecated.
1642 ///
1643 /// [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns
1644 ///
1645 /// ### Example
1646 ///
1647 /// ```rust,edition2018
1648 /// let x = 123;
1649 /// match x {
1650 /// 0...100 => {}
1651 /// _ => {}
1652 /// }
1653 /// ```
1654 ///
1655 /// {{produces}}
1656 ///
1657 /// ### Explanation
1658 ///
1659 /// The `...` range pattern syntax was changed to `..=` to avoid potential
1660 /// confusion with the [`..` range expression]. Use the new form instead.
1661 ///
1662 /// [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html
1663 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1664 Warn,
1665 "`...` range patterns are deprecated",
1666 @future_incompatible = FutureIncompatibleInfo {
1667 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2021),
1668 reference: "<https://doc.rust-lang.org/edition-guide/rust-2021/warnings-promoted-to-error.html>",
1669 };
1670}
1671
1672#[derive(Default)]
1673pub struct EllipsisInclusiveRangePatterns {
1674 /// If `Some(_)`, suppress all subsequent pattern
1675 /// warnings for better diagnostics.
1676 node_id: Option<ast::NodeId>,
1677}
1678
1679impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1680
1681impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1682 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1683 if self.node_id.is_some() {
1684 // Don't recursively warn about patterns inside range endpoints.
1685 return;
1686 }
1687
1688 use self::ast::PatKind;
1689 use self::ast::RangeSyntax::DotDotDot;
1690
1691 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1692 /// corresponding to the ellipsis.
1693 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1694 match &pat.kind {
1695 PatKind::Range(
1696 a,
1697 Some(b),
1698 Spanned { span, node: RangeEnd::Included(DotDotDot) },
1699 ) => Some((a.as_deref(), b, *span)),
1700 _ => None,
1701 }
1702 }
1703
1704 let (parentheses, endpoints) = match &pat.kind {
1705 PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(subpat)),
1706 _ => (false, matches_ellipsis_pat(pat)),
1707 };
1708
1709 if let Some((start, end, join)) = endpoints {
1710 if parentheses {
1711 self.node_id = Some(pat.id);
1712 let end = expr_to_string(end);
1713 let replace = match start {
1714 Some(start) => format!("&({}..={})", expr_to_string(start), end),
1715 None => format!("&(..={end})"),
1716 };
1717 if join.edition() >= Edition::Edition2021 {
1718 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1719 span: pat.span,
1720 suggestion: pat.span,
1721 replace,
1722 });
1723 } else {
1724 cx.emit_span_lint(
1725 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1726 pat.span,
1727 BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1728 suggestion: pat.span,
1729 replace,
1730 },
1731 );
1732 }
1733 } else {
1734 let replace = "..=";
1735 if join.edition() >= Edition::Edition2021 {
1736 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1737 span: pat.span,
1738 suggestion: join,
1739 replace: replace.to_string(),
1740 });
1741 } else {
1742 cx.emit_span_lint(
1743 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1744 join,
1745 BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1746 suggestion: join,
1747 },
1748 );
1749 }
1750 };
1751 }
1752 }
1753
1754 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1755 if let Some(node_id) = self.node_id {
1756 if pat.id == node_id {
1757 self.node_id = None
1758 }
1759 }
1760 }
1761}
1762
1763declare_lint! {
1764 /// The `keyword_idents_2018` lint detects edition keywords being used as an
1765 /// identifier.
1766 ///
1767 /// ### Example
1768 ///
1769 /// ```rust,edition2015,compile_fail
1770 /// #![deny(keyword_idents_2018)]
1771 /// // edition 2015
1772 /// fn dyn() {}
1773 /// ```
1774 ///
1775 /// {{produces}}
1776 ///
1777 /// ### Explanation
1778 ///
1779 /// Rust [editions] allow the language to evolve without breaking
1780 /// backwards compatibility. This lint catches code that uses new keywords
1781 /// that are added to the language that are used as identifiers (such as a
1782 /// variable name, function name, etc.). If you switch the compiler to a
1783 /// new edition without updating the code, then it will fail to compile if
1784 /// you are using a new keyword as an identifier.
1785 ///
1786 /// You can manually change the identifiers to a non-keyword, or use a
1787 /// [raw identifier], for example `r#dyn`, to transition to a new edition.
1788 ///
1789 /// This lint solves the problem automatically. It is "allow" by default
1790 /// because the code is perfectly valid in older editions. The [`cargo
1791 /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1792 /// and automatically apply the suggested fix from the compiler (which is
1793 /// to use a raw identifier). This provides a completely automated way to
1794 /// update old code for a new edition.
1795 ///
1796 /// [editions]: https://doc.rust-lang.org/edition-guide/
1797 /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1798 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1799 pub KEYWORD_IDENTS_2018,
1800 Allow,
1801 "detects edition keywords being used as an identifier",
1802 @future_incompatible = FutureIncompatibleInfo {
1803 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
1804 reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1805 };
1806}
1807
1808declare_lint! {
1809 /// The `keyword_idents_2024` lint detects edition keywords being used as an
1810 /// identifier.
1811 ///
1812 /// ### Example
1813 ///
1814 /// ```rust,edition2015,compile_fail
1815 /// #![deny(keyword_idents_2024)]
1816 /// // edition 2015
1817 /// fn gen() {}
1818 /// ```
1819 ///
1820 /// {{produces}}
1821 ///
1822 /// ### Explanation
1823 ///
1824 /// Rust [editions] allow the language to evolve without breaking
1825 /// backwards compatibility. This lint catches code that uses new keywords
1826 /// that are added to the language that are used as identifiers (such as a
1827 /// variable name, function name, etc.). If you switch the compiler to a
1828 /// new edition without updating the code, then it will fail to compile if
1829 /// you are using a new keyword as an identifier.
1830 ///
1831 /// You can manually change the identifiers to a non-keyword, or use a
1832 /// [raw identifier], for example `r#gen`, to transition to a new edition.
1833 ///
1834 /// This lint solves the problem automatically. It is "allow" by default
1835 /// because the code is perfectly valid in older editions. The [`cargo
1836 /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1837 /// and automatically apply the suggested fix from the compiler (which is
1838 /// to use a raw identifier). This provides a completely automated way to
1839 /// update old code for a new edition.
1840 ///
1841 /// [editions]: https://doc.rust-lang.org/edition-guide/
1842 /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1843 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1844 pub KEYWORD_IDENTS_2024,
1845 Allow,
1846 "detects edition keywords being used as an identifier",
1847 @future_incompatible = FutureIncompatibleInfo {
1848 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2024),
1849 reference: "<https://doc.rust-lang.org/edition-guide/rust-2024/gen-keyword.html>",
1850 };
1851}
1852
1853declare_lint_pass!(
1854 /// Check for uses of edition keywords used as an identifier.
1855 KeywordIdents => [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]
1856);
1857
1858struct UnderMacro(bool);
1859
1860impl KeywordIdents {
1861 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1862 // Check if the preceding token is `$`, because we want to allow `$async`, etc.
1863 let mut prev_dollar = false;
1864 for tt in tokens.iter() {
1865 match tt {
1866 // Only report non-raw idents.
1867 TokenTree::Token(token, _) => {
1868 if let Some((ident, token::IdentIsRaw::No)) = token.ident() {
1869 if !prev_dollar {
1870 self.check_ident_token(cx, UnderMacro(true), ident, "");
1871 }
1872 } else if let Some((ident, token::IdentIsRaw::No)) = token.lifetime() {
1873 self.check_ident_token(
1874 cx,
1875 UnderMacro(true),
1876 ident.without_first_quote(),
1877 "'",
1878 );
1879 } else if token.kind == TokenKind::Dollar {
1880 prev_dollar = true;
1881 continue;
1882 }
1883 }
1884 TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts),
1885 }
1886 prev_dollar = false;
1887 }
1888 }
1889
1890 fn check_ident_token(
1891 &mut self,
1892 cx: &EarlyContext<'_>,
1893 UnderMacro(under_macro): UnderMacro,
1894 ident: Ident,
1895 prefix: &'static str,
1896 ) {
1897 let (lint, edition) = match ident.name {
1898 kw::Async | kw::Await | kw::Try => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1899
1900 // rust-lang/rust#56327: Conservatively do not
1901 // attempt to report occurrences of `dyn` within
1902 // macro definitions or invocations, because `dyn`
1903 // can legitimately occur as a contextual keyword
1904 // in 2015 code denoting its 2018 meaning, and we
1905 // do not want rustfix to inject bugs into working
1906 // code by rewriting such occurrences.
1907 //
1908 // But if we see `dyn` outside of a macro, we know
1909 // its precise role in the parsed AST and thus are
1910 // assured this is truly an attempt to use it as
1911 // an identifier.
1912 kw::Dyn if !under_macro => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1913
1914 kw::Gen => (KEYWORD_IDENTS_2024, Edition::Edition2024),
1915
1916 _ => return,
1917 };
1918
1919 // Don't lint `r#foo`.
1920 if ident.span.edition() >= edition
1921 || cx.sess().psess.raw_identifier_spans.contains(ident.span)
1922 {
1923 return;
1924 }
1925
1926 cx.emit_span_lint(
1927 lint,
1928 ident.span,
1929 BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix },
1930 );
1931 }
1932}
1933
1934impl EarlyLintPass for KeywordIdents {
1935 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1936 self.check_tokens(cx, &mac_def.body.tokens);
1937 }
1938 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1939 self.check_tokens(cx, &mac.args.tokens);
1940 }
1941 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) {
1942 if ident.name.as_str().starts_with('\'') {
1943 self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'");
1944 } else {
1945 self.check_ident_token(cx, UnderMacro(false), *ident, "");
1946 }
1947 }
1948}
1949
1950declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1951
1952impl ExplicitOutlivesRequirements {
1953 fn lifetimes_outliving_lifetime<'tcx>(
1954 tcx: TyCtxt<'tcx>,
1955 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1956 item: LocalDefId,
1957 lifetime: LocalDefId,
1958 ) -> Vec<ty::Region<'tcx>> {
1959 let item_generics = tcx.generics_of(item);
1960
1961 inferred_outlives
1962 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1963 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a.kind() {
1964 ty::ReEarlyParam(ebr)
1965 if item_generics.region_param(ebr, tcx).def_id == lifetime.to_def_id() =>
1966 {
1967 Some(b)
1968 }
1969 _ => None,
1970 },
1971 _ => None,
1972 })
1973 .collect()
1974 }
1975
1976 fn lifetimes_outliving_type<'tcx>(
1977 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1978 index: u32,
1979 ) -> Vec<ty::Region<'tcx>> {
1980 inferred_outlives
1981 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1982 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
1983 a.is_param(index).then_some(b)
1984 }
1985 _ => None,
1986 })
1987 .collect()
1988 }
1989
1990 fn collect_outlives_bound_spans<'tcx>(
1991 &self,
1992 tcx: TyCtxt<'tcx>,
1993 bounds: &hir::GenericBounds<'_>,
1994 inferred_outlives: &[ty::Region<'tcx>],
1995 predicate_span: Span,
1996 item: DefId,
1997 ) -> Vec<(usize, Span)> {
1998 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1999
2000 let item_generics = tcx.generics_of(item);
2001
2002 bounds
2003 .iter()
2004 .enumerate()
2005 .filter_map(|(i, bound)| {
2006 let hir::GenericBound::Outlives(lifetime) = bound else {
2007 return None;
2008 };
2009
2010 let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
2011 Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
2012 .iter()
2013 .any(|r| matches!(r.kind(), ty::ReEarlyParam(ebr) if { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() })),
2014 _ => false,
2015 };
2016
2017 if !is_inferred {
2018 return None;
2019 }
2020
2021 let span = bound.span().find_ancestor_inside(predicate_span)?;
2022 if span.in_external_macro(tcx.sess.source_map()) {
2023 return None;
2024 }
2025
2026 Some((i, span))
2027 })
2028 .collect()
2029 }
2030
2031 fn consolidate_outlives_bound_spans(
2032 &self,
2033 lo: Span,
2034 bounds: &hir::GenericBounds<'_>,
2035 bound_spans: Vec<(usize, Span)>,
2036 ) -> Vec<Span> {
2037 if bounds.is_empty() {
2038 return Vec::new();
2039 }
2040 if bound_spans.len() == bounds.len() {
2041 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
2042 // If all bounds are inferable, we want to delete the colon, so
2043 // start from just after the parameter (span passed as argument)
2044 vec![lo.to(last_bound_span)]
2045 } else {
2046 let mut merged = Vec::new();
2047 let mut last_merged_i = None;
2048
2049 let mut from_start = true;
2050 for (i, bound_span) in bound_spans {
2051 match last_merged_i {
2052 // If the first bound is inferable, our span should also eat the leading `+`.
2053 None if i == 0 => {
2054 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
2055 last_merged_i = Some(0);
2056 }
2057 // If consecutive bounds are inferable, merge their spans
2058 Some(h) if i == h + 1 => {
2059 if let Some(tail) = merged.last_mut() {
2060 // Also eat the trailing `+` if the first
2061 // more-than-one bound is inferable
2062 let to_span = if from_start && i < bounds.len() {
2063 bounds[i + 1].span().shrink_to_lo()
2064 } else {
2065 bound_span
2066 };
2067 *tail = tail.to(to_span);
2068 last_merged_i = Some(i);
2069 } else {
2070 bug!("another bound-span visited earlier");
2071 }
2072 }
2073 _ => {
2074 // When we find a non-inferable bound, subsequent inferable bounds
2075 // won't be consecutive from the start (and we'll eat the leading
2076 // `+` rather than the trailing one)
2077 from_start = false;
2078 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
2079 last_merged_i = Some(i);
2080 }
2081 }
2082 }
2083 merged
2084 }
2085 }
2086}
2087
2088impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
2089 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
2090 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2091
2092 let def_id = item.owner_id.def_id;
2093 if let hir::ItemKind::Struct(_, generics, _)
2094 | hir::ItemKind::Enum(_, generics, _)
2095 | hir::ItemKind::Union(_, generics, _) = item.kind
2096 {
2097 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
2098 if inferred_outlives.is_empty() {
2099 return;
2100 }
2101
2102 let ty_generics = cx.tcx.generics_of(def_id);
2103 let num_where_predicates = generics
2104 .predicates
2105 .iter()
2106 .filter(|predicate| predicate.kind.in_where_clause())
2107 .count();
2108
2109 let mut bound_count = 0;
2110 let mut lint_spans = Vec::new();
2111 let mut where_lint_spans = Vec::new();
2112 let mut dropped_where_predicate_count = 0;
2113 for (i, where_predicate) in generics.predicates.iter().enumerate() {
2114 let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2115 match where_predicate.kind {
2116 hir::WherePredicateKind::RegionPredicate(predicate) => {
2117 if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2118 cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2119 {
2120 (
2121 Self::lifetimes_outliving_lifetime(
2122 cx.tcx,
2123 // don't warn if the inferred span actually came from the predicate we're looking at
2124 // this happens if the type is recursively defined
2125 inferred_outlives.iter().filter(|(_, span)| {
2126 !where_predicate.span.contains(*span)
2127 }),
2128 item.owner_id.def_id,
2129 region_def_id,
2130 ),
2131 &predicate.bounds,
2132 where_predicate.span,
2133 predicate.in_where_clause,
2134 )
2135 } else {
2136 continue;
2137 }
2138 }
2139 hir::WherePredicateKind::BoundPredicate(predicate) => {
2140 // FIXME we can also infer bounds on associated types,
2141 // and should check for them here.
2142 match predicate.bounded_ty.kind {
2143 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2144 let Res::Def(DefKind::TyParam, def_id) = path.res else {
2145 continue;
2146 };
2147 let index = ty_generics.param_def_id_to_index[&def_id];
2148 (
2149 Self::lifetimes_outliving_type(
2150 // don't warn if the inferred span actually came from the predicate we're looking at
2151 // this happens if the type is recursively defined
2152 inferred_outlives.iter().filter(|(_, span)| {
2153 !where_predicate.span.contains(*span)
2154 }),
2155 index,
2156 ),
2157 &predicate.bounds,
2158 where_predicate.span,
2159 predicate.origin == PredicateOrigin::WhereClause,
2160 )
2161 }
2162 _ => {
2163 continue;
2164 }
2165 }
2166 }
2167 _ => continue,
2168 };
2169 if relevant_lifetimes.is_empty() {
2170 continue;
2171 }
2172
2173 let bound_spans = self.collect_outlives_bound_spans(
2174 cx.tcx,
2175 bounds,
2176 &relevant_lifetimes,
2177 predicate_span,
2178 item.owner_id.to_def_id(),
2179 );
2180 bound_count += bound_spans.len();
2181
2182 let drop_predicate = bound_spans.len() == bounds.len();
2183 if drop_predicate && in_where_clause {
2184 dropped_where_predicate_count += 1;
2185 }
2186
2187 if drop_predicate {
2188 if !in_where_clause {
2189 lint_spans.push(predicate_span);
2190 } else if predicate_span.from_expansion() {
2191 // Don't try to extend the span if it comes from a macro expansion.
2192 where_lint_spans.push(predicate_span);
2193 } else if i + 1 < num_where_predicates {
2194 // If all the bounds on a predicate were inferable and there are
2195 // further predicates, we want to eat the trailing comma.
2196 let next_predicate_span = generics.predicates[i + 1].span;
2197 if next_predicate_span.from_expansion() {
2198 where_lint_spans.push(predicate_span);
2199 } else {
2200 where_lint_spans
2201 .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2202 }
2203 } else {
2204 // Eat the optional trailing comma after the last predicate.
2205 let where_span = generics.where_clause_span;
2206 if where_span.from_expansion() {
2207 where_lint_spans.push(predicate_span);
2208 } else {
2209 where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2210 }
2211 }
2212 } else {
2213 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2214 predicate_span.shrink_to_lo(),
2215 bounds,
2216 bound_spans,
2217 ));
2218 }
2219 }
2220
2221 // If all predicates in where clause are inferable, drop the entire clause
2222 // (including the `where`)
2223 if generics.has_where_clause_predicates
2224 && dropped_where_predicate_count == num_where_predicates
2225 {
2226 let where_span = generics.where_clause_span;
2227 // Extend the where clause back to the closing `>` of the
2228 // generics, except for tuple struct, which have the `where`
2229 // after the fields of the struct.
2230 let full_where_span =
2231 if let hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(..)) = item.kind {
2232 where_span
2233 } else {
2234 generics.span.shrink_to_hi().to(where_span)
2235 };
2236
2237 // Due to macro expansions, the `full_where_span` might not actually contain all
2238 // predicates.
2239 if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2240 lint_spans.push(full_where_span);
2241 } else {
2242 lint_spans.extend(where_lint_spans);
2243 }
2244 } else {
2245 lint_spans.extend(where_lint_spans);
2246 }
2247
2248 if !lint_spans.is_empty() {
2249 // Do not automatically delete outlives requirements from macros.
2250 let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2251 {
2252 Applicability::MachineApplicable
2253 } else {
2254 Applicability::MaybeIncorrect
2255 };
2256
2257 // Due to macros, there might be several predicates with the same span
2258 // and we only want to suggest removing them once.
2259 lint_spans.sort_unstable();
2260 lint_spans.dedup();
2261
2262 cx.emit_span_lint(
2263 EXPLICIT_OUTLIVES_REQUIREMENTS,
2264 lint_spans.clone(),
2265 BuiltinExplicitOutlives {
2266 count: bound_count,
2267 suggestion: BuiltinExplicitOutlivesSuggestion {
2268 spans: lint_spans,
2269 applicability,
2270 },
2271 },
2272 );
2273 }
2274 }
2275 }
2276}
2277
2278declare_lint! {
2279 /// The `incomplete_features` lint detects unstable features enabled with
2280 /// the [`feature` attribute] that may function improperly in some or all
2281 /// cases.
2282 ///
2283 /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2284 ///
2285 /// ### Example
2286 ///
2287 /// ```rust
2288 /// #![feature(generic_const_exprs)]
2289 /// ```
2290 ///
2291 /// {{produces}}
2292 ///
2293 /// ### Explanation
2294 ///
2295 /// Although it is encouraged for people to experiment with unstable
2296 /// features, some of them are known to be incomplete or faulty. This lint
2297 /// is a signal that the feature has not yet been finished, and you may
2298 /// experience problems with it.
2299 pub INCOMPLETE_FEATURES,
2300 Warn,
2301 "incomplete features that may function improperly in some or all cases"
2302}
2303
2304declare_lint! {
2305 /// The `internal_features` lint detects unstable features enabled with
2306 /// the [`feature` attribute] that are internal to the compiler or standard
2307 /// library.
2308 ///
2309 /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2310 ///
2311 /// ### Example
2312 ///
2313 /// ```rust
2314 /// #![feature(rustc_attrs)]
2315 /// ```
2316 ///
2317 /// {{produces}}
2318 ///
2319 /// ### Explanation
2320 ///
2321 /// These features are an implementation detail of the compiler and standard
2322 /// library and are not supposed to be used in user code.
2323 pub INTERNAL_FEATURES,
2324 Warn,
2325 "internal features are not supposed to be used"
2326}
2327
2328declare_lint_pass!(
2329 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`.
2330 IncompleteInternalFeatures => [INCOMPLETE_FEATURES, INTERNAL_FEATURES]
2331);
2332
2333impl EarlyLintPass for IncompleteInternalFeatures {
2334 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2335 let features = cx.builder.features();
2336
2337 features
2338 .enabled_features_iter_stable_order()
2339 .filter(|(name, _)| features.incomplete(*name) || features.internal(*name))
2340 .for_each(|(name, span)| {
2341 if features.incomplete(name) {
2342 let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2343 .map(|n| BuiltinFeatureIssueNote { n });
2344 let help =
2345 HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp);
2346
2347 cx.emit_span_lint(
2348 INCOMPLETE_FEATURES,
2349 span,
2350 BuiltinIncompleteFeatures { name, note, help },
2351 );
2352 } else {
2353 cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name });
2354 }
2355 });
2356 }
2357}
2358
2359const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2360
2361declare_lint! {
2362 /// The `invalid_value` lint detects creating a value that is not valid,
2363 /// such as a null reference.
2364 ///
2365 /// ### Example
2366 ///
2367 /// ```rust,no_run
2368 /// # #![allow(unused)]
2369 /// unsafe {
2370 /// let x: &'static i32 = std::mem::zeroed();
2371 /// }
2372 /// ```
2373 ///
2374 /// {{produces}}
2375 ///
2376 /// ### Explanation
2377 ///
2378 /// In some situations the compiler can detect that the code is creating
2379 /// an invalid value, which should be avoided.
2380 ///
2381 /// In particular, this lint will check for improper use of
2382 /// [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and
2383 /// [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The
2384 /// lint should provide extra information to indicate what the problem is
2385 /// and a possible solution.
2386 ///
2387 /// [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html
2388 /// [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html
2389 /// [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html
2390 /// [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init
2391 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2392 pub INVALID_VALUE,
2393 Warn,
2394 "an invalid value is being created (such as a null reference)"
2395}
2396
2397declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2398
2399/// Information about why a type cannot be initialized this way.
2400pub struct InitError {
2401 pub(crate) message: String,
2402 /// Spans from struct fields and similar that can be obtained from just the type.
2403 pub(crate) span: Option<Span>,
2404 /// Used to report a trace through adts.
2405 pub(crate) nested: Option<Box<InitError>>,
2406}
2407impl InitError {
2408 fn spanned(self, span: Span) -> InitError {
2409 Self { span: Some(span), ..self }
2410 }
2411
2412 fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2413 assert!(self.nested.is_none());
2414 Self { nested: nested.into().map(Box::new), ..self }
2415 }
2416}
2417
2418impl<'a> From<&'a str> for InitError {
2419 fn from(s: &'a str) -> Self {
2420 s.to_owned().into()
2421 }
2422}
2423impl From<String> for InitError {
2424 fn from(message: String) -> Self {
2425 Self { message, span: None, nested: None }
2426 }
2427}
2428
2429impl<'tcx> LateLintPass<'tcx> for InvalidValue {
2430 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2431 #[derive(Debug, Copy, Clone, PartialEq)]
2432 enum InitKind {
2433 Zeroed,
2434 Uninit,
2435 }
2436
2437 /// Test if this constant is all-0.
2438 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2439 use hir::ExprKind::*;
2440 use rustc_ast::LitKind::*;
2441 match &expr.kind {
2442 Lit(lit) => {
2443 if let Int(i, _) = lit.node {
2444 i == 0
2445 } else {
2446 false
2447 }
2448 }
2449 Tup(tup) => tup.iter().all(is_zero),
2450 _ => false,
2451 }
2452 }
2453
2454 /// Determine if this expression is a "dangerous initialization".
2455 fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2456 if let hir::ExprKind::Call(path_expr, args) = expr.kind
2457 // Find calls to `mem::{uninitialized,zeroed}` methods.
2458 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2459 {
2460 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2461 match cx.tcx.get_diagnostic_name(def_id) {
2462 Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2463 Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2464 Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2465 _ => {}
2466 }
2467 } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2468 // Find problematic calls to `MaybeUninit::assume_init`.
2469 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2470 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2471 // This is a call to *some* method named `assume_init`.
2472 // See if the `self` parameter is one of the dangerous constructors.
2473 if let hir::ExprKind::Call(path_expr, _) = receiver.kind
2474 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2475 {
2476 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2477 match cx.tcx.get_diagnostic_name(def_id) {
2478 Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2479 Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2480 _ => {}
2481 }
2482 }
2483 }
2484 }
2485
2486 None
2487 }
2488
2489 fn variant_find_init_error<'tcx>(
2490 cx: &LateContext<'tcx>,
2491 ty: Ty<'tcx>,
2492 variant: &VariantDef,
2493 args: ty::GenericArgsRef<'tcx>,
2494 descr: &str,
2495 init: InitKind,
2496 ) -> Option<InitError> {
2497 let mut field_err = variant.fields.iter().find_map(|field| {
2498 ty_find_init_error(cx, field.ty(cx.tcx, args), init).map(|mut err| {
2499 if !field.did.is_local() {
2500 err
2501 } else if err.span.is_none() {
2502 err.span = Some(cx.tcx.def_span(field.did));
2503 write!(&mut err.message, " (in this {descr})").unwrap();
2504 err
2505 } else {
2506 InitError::from(format!("in this {descr}"))
2507 .spanned(cx.tcx.def_span(field.did))
2508 .nested(err)
2509 }
2510 })
2511 });
2512
2513 // Check if this ADT has a constrained layout (like `NonNull` and friends).
2514 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(ty)) {
2515 if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair(scalar, _) =
2516 &layout.backend_repr
2517 {
2518 let range = scalar.valid_range(cx);
2519 let msg = if !range.contains(0) {
2520 "must be non-null"
2521 } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2522 // Prefer reporting on the fields over the entire struct for uninit,
2523 // as the information bubbles out and it may be unclear why the type can't
2524 // be null from just its outside signature.
2525
2526 "must be initialized inside its custom valid range"
2527 } else {
2528 return field_err;
2529 };
2530 if let Some(field_err) = &mut field_err {
2531 // Most of the time, if the field error is the same as the struct error,
2532 // the struct error only happens because of the field error.
2533 if field_err.message.contains(msg) {
2534 field_err.message = format!("because {}", field_err.message);
2535 }
2536 }
2537 return Some(InitError::from(format!("`{ty}` {msg}")).nested(field_err));
2538 }
2539 }
2540 field_err
2541 }
2542
2543 /// Return `Some` only if we are sure this type does *not*
2544 /// allow zero initialization.
2545 fn ty_find_init_error<'tcx>(
2546 cx: &LateContext<'tcx>,
2547 ty: Ty<'tcx>,
2548 init: InitKind,
2549 ) -> Option<InitError> {
2550 let ty = cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty);
2551
2552 match ty.kind() {
2553 // Primitive types that don't like 0 as a value.
2554 ty::Ref(..) => Some("references must be non-null".into()),
2555 ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2556 ty::FnPtr(..) => Some("function pointers must be non-null".into()),
2557 ty::Never => Some("the `!` type has no valid value".into()),
2558 ty::RawPtr(ty, _) if matches!(ty.kind(), ty::Dynamic(..)) =>
2559 // raw ptr to dyn Trait
2560 {
2561 Some("the vtable of a wide raw pointer must be non-null".into())
2562 }
2563 // Primitive types with other constraints.
2564 ty::Bool if init == InitKind::Uninit => {
2565 Some("booleans must be either `true` or `false`".into())
2566 }
2567 ty::Char if init == InitKind::Uninit => {
2568 Some("characters must be a valid Unicode codepoint".into())
2569 }
2570 ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => {
2571 Some("integers must be initialized".into())
2572 }
2573 ty::Float(_) if init == InitKind::Uninit => {
2574 Some("floats must be initialized".into())
2575 }
2576 ty::RawPtr(_, _) if init == InitKind::Uninit => {
2577 Some("raw pointers must be initialized".into())
2578 }
2579 // Recurse and checks for some compound types. (but not unions)
2580 ty::Adt(adt_def, args) if !adt_def.is_union() => {
2581 // Handle structs.
2582 if adt_def.is_struct() {
2583 return variant_find_init_error(
2584 cx,
2585 ty,
2586 adt_def.non_enum_variant(),
2587 args,
2588 "struct field",
2589 init,
2590 );
2591 }
2592 // And now, enums.
2593 let span = cx.tcx.def_span(adt_def.did());
2594 let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2595 let definitely_inhabited = match variant
2596 .inhabited_predicate(cx.tcx, *adt_def)
2597 .instantiate(cx.tcx, args)
2598 .apply_any_module(cx.tcx, cx.typing_env())
2599 {
2600 // Entirely skip uninhabited variants.
2601 Some(false) => return None,
2602 // Forward the others, but remember which ones are definitely inhabited.
2603 Some(true) => true,
2604 None => false,
2605 };
2606 Some((variant, definitely_inhabited))
2607 });
2608 let Some(first_variant) = potential_variants.next() else {
2609 return Some(
2610 InitError::from("enums with no inhabited variants have no valid value")
2611 .spanned(span),
2612 );
2613 };
2614 // So we have at least one potentially inhabited variant. Might we have two?
2615 let Some(second_variant) = potential_variants.next() else {
2616 // There is only one potentially inhabited variant. So we can recursively
2617 // check that variant!
2618 return variant_find_init_error(
2619 cx,
2620 ty,
2621 first_variant.0,
2622 args,
2623 "field of the only potentially inhabited enum variant",
2624 init,
2625 );
2626 };
2627 // So we have at least two potentially inhabited variants. If we can prove that
2628 // we have at least two *definitely* inhabited variants, then we have a tag and
2629 // hence leaving this uninit is definitely disallowed. (Leaving it zeroed could
2630 // be okay, depending on which variant is encoded as zero tag.)
2631 if init == InitKind::Uninit {
2632 let definitely_inhabited = (first_variant.1 as usize)
2633 + (second_variant.1 as usize)
2634 + potential_variants
2635 .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2636 .count();
2637 if definitely_inhabited > 1 {
2638 return Some(InitError::from(
2639 "enums with multiple inhabited variants have to be initialized to a variant",
2640 ).spanned(span));
2641 }
2642 }
2643 // We couldn't find anything wrong here.
2644 None
2645 }
2646 ty::Tuple(..) => {
2647 // Proceed recursively, check all fields.
2648 ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2649 }
2650 ty::Array(ty, len) => {
2651 if matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
2652 // Array length known at array non-empty -- recurse.
2653 ty_find_init_error(cx, *ty, init)
2654 } else {
2655 // Empty array or size unknown.
2656 None
2657 }
2658 }
2659 // Conservative fallback.
2660 _ => None,
2661 }
2662 }
2663
2664 if let Some(init) = is_dangerous_init(cx, expr) {
2665 // This conjures an instance of a type out of nothing,
2666 // using zeroed or uninitialized memory.
2667 // We are extremely conservative with what we warn about.
2668 let conjured_ty = cx.typeck_results().expr_ty(expr);
2669 if let Some(err) = with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2670 let msg = match init {
2671 InitKind::Zeroed => fluent::lint_builtin_unpermitted_type_init_zeroed,
2672 InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit,
2673 };
2674 let sub = BuiltinUnpermittedTypeInitSub { err };
2675 cx.emit_span_lint(
2676 INVALID_VALUE,
2677 expr.span,
2678 BuiltinUnpermittedTypeInit {
2679 msg,
2680 ty: conjured_ty,
2681 label: expr.span,
2682 sub,
2683 tcx: cx.tcx,
2684 },
2685 );
2686 }
2687 }
2688 }
2689}
2690
2691declare_lint! {
2692 /// The `deref_nullptr` lint detects when a null pointer is dereferenced,
2693 /// which causes [undefined behavior].
2694 ///
2695 /// ### Example
2696 ///
2697 /// ```rust,no_run
2698 /// # #![allow(unused)]
2699 /// use std::ptr;
2700 /// unsafe {
2701 /// let x = &*ptr::null::<i32>();
2702 /// let x = ptr::addr_of!(*ptr::null::<i32>());
2703 /// let x = *(0 as *const i32);
2704 /// }
2705 /// ```
2706 ///
2707 /// {{produces}}
2708 ///
2709 /// ### Explanation
2710 ///
2711 /// Dereferencing a null pointer causes [undefined behavior] if it is accessed
2712 /// (loaded from or stored to).
2713 ///
2714 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2715 pub DEREF_NULLPTR,
2716 Warn,
2717 "detects when an null pointer is dereferenced"
2718}
2719
2720declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
2721
2722impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
2723 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2724 /// test if expression is a null ptr
2725 fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
2726 match &expr.kind {
2727 hir::ExprKind::Cast(expr, ty) => {
2728 if let hir::TyKind::Ptr(_) = ty.kind {
2729 return is_zero(expr) || is_null_ptr(cx, expr);
2730 }
2731 }
2732 // check for call to `core::ptr::null` or `core::ptr::null_mut`
2733 hir::ExprKind::Call(path, _) => {
2734 if let hir::ExprKind::Path(ref qpath) = path.kind
2735 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
2736 {
2737 return matches!(
2738 cx.tcx.get_diagnostic_name(def_id),
2739 Some(sym::ptr_null | sym::ptr_null_mut)
2740 );
2741 }
2742 }
2743 _ => {}
2744 }
2745 false
2746 }
2747
2748 /// test if expression is the literal `0`
2749 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2750 match &expr.kind {
2751 hir::ExprKind::Lit(lit) => {
2752 if let LitKind::Int(a, _) = lit.node {
2753 return a == 0;
2754 }
2755 }
2756 _ => {}
2757 }
2758 false
2759 }
2760
2761 if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind
2762 && is_null_ptr(cx, expr_deref)
2763 {
2764 if let hir::Node::Expr(hir::Expr {
2765 kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..),
2766 ..
2767 }) = cx.tcx.parent_hir_node(expr.hir_id)
2768 {
2769 // `&raw *NULL` is ok.
2770 } else {
2771 cx.emit_span_lint(
2772 DEREF_NULLPTR,
2773 expr.span,
2774 BuiltinDerefNullptr { label: expr.span },
2775 );
2776 }
2777 }
2778 }
2779}
2780
2781declare_lint! {
2782 /// The `named_asm_labels` lint detects the use of named labels in the
2783 /// inline `asm!` macro.
2784 ///
2785 /// ### Example
2786 ///
2787 /// ```rust,compile_fail
2788 /// # #![feature(asm_experimental_arch)]
2789 /// use std::arch::asm;
2790 ///
2791 /// fn main() {
2792 /// unsafe {
2793 /// asm!("foo: bar");
2794 /// }
2795 /// }
2796 /// ```
2797 ///
2798 /// {{produces}}
2799 ///
2800 /// ### Explanation
2801 ///
2802 /// LLVM is allowed to duplicate inline assembly blocks for any
2803 /// reason, for example when it is in a function that gets inlined. Because
2804 /// of this, GNU assembler [local labels] *must* be used instead of labels
2805 /// with a name. Using named labels might cause assembler or linker errors.
2806 ///
2807 /// See the explanation in [Rust By Example] for more details.
2808 ///
2809 /// [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels
2810 /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2811 pub NAMED_ASM_LABELS,
2812 Deny,
2813 "named labels in inline assembly",
2814}
2815
2816declare_lint! {
2817 /// The `binary_asm_labels` lint detects the use of numeric labels containing only binary
2818 /// digits in the inline `asm!` macro.
2819 ///
2820 /// ### Example
2821 ///
2822 /// ```rust,ignore (fails on non-x86_64)
2823 /// #![cfg(target_arch = "x86_64")]
2824 ///
2825 /// use std::arch::asm;
2826 ///
2827 /// fn main() {
2828 /// unsafe {
2829 /// asm!("0: jmp 0b");
2830 /// }
2831 /// }
2832 /// ```
2833 ///
2834 /// This will produce:
2835 ///
2836 /// ```text
2837 /// error: avoid using labels containing only the digits `0` and `1` in inline assembly
2838 /// --> <source>:7:15
2839 /// |
2840 /// 7 | asm!("0: jmp 0b");
2841 /// | ^ use a different label that doesn't start with `0` or `1`
2842 /// |
2843 /// = help: start numbering with `2` instead
2844 /// = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86
2845 /// = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information
2846 /// = note: `#[deny(binary_asm_labels)]` on by default
2847 /// ```
2848 ///
2849 /// ### Explanation
2850 ///
2851 /// An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary
2852 /// literal instead of a reference to the previous local label `0`. To work around this bug,
2853 /// don't use labels that could be confused with a binary literal.
2854 ///
2855 /// This behavior is platform-specific to x86 and x86-64.
2856 ///
2857 /// See the explanation in [Rust By Example] for more details.
2858 ///
2859 /// [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547
2860 /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2861 pub BINARY_ASM_LABELS,
2862 Deny,
2863 "labels in inline assembly containing only 0 or 1 digits",
2864}
2865
2866declare_lint_pass!(AsmLabels => [NAMED_ASM_LABELS, BINARY_ASM_LABELS]);
2867
2868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2869enum AsmLabelKind {
2870 Named,
2871 FormatArg,
2872 Binary,
2873}
2874
2875impl<'tcx> LateLintPass<'tcx> for AsmLabels {
2876 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
2877 if let hir::Expr {
2878 kind:
2879 hir::ExprKind::InlineAsm(hir::InlineAsm {
2880 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
2881 template_strs,
2882 options,
2883 ..
2884 }),
2885 ..
2886 } = expr
2887 {
2888 // Non-generic naked functions are allowed to define arbitrary
2889 // labels.
2890 if *asm_macro == AsmMacro::NakedAsm {
2891 let def_id = expr.hir_id.owner.def_id;
2892 if !cx.tcx.generics_of(def_id).requires_monomorphization(cx.tcx) {
2893 return;
2894 }
2895 }
2896
2897 // asm with `options(raw)` does not do replacement with `{` and `}`.
2898 let raw = options.contains(InlineAsmOptions::RAW);
2899
2900 for (template_sym, template_snippet, template_span) in template_strs.iter() {
2901 let template_str = template_sym.as_str();
2902 let find_label_span = |needle: &str| -> Option<Span> {
2903 if let Some(template_snippet) = template_snippet {
2904 let snippet = template_snippet.as_str();
2905 if let Some(pos) = snippet.find(needle) {
2906 let end = pos
2907 + snippet[pos..]
2908 .find(|c| c == ':')
2909 .unwrap_or(snippet[pos..].len() - 1);
2910 let inner = InnerSpan::new(pos, end);
2911 return Some(template_span.from_inner(inner));
2912 }
2913 }
2914
2915 None
2916 };
2917
2918 // diagnostics are emitted per-template, so this is created here as opposed to the outer loop
2919 let mut spans = Vec::new();
2920
2921 // A semicolon might not actually be specified as a separator for all targets, but
2922 // it seems like LLVM accepts it always.
2923 let statements = template_str.split(|c| matches!(c, '\n' | ';'));
2924 for statement in statements {
2925 // If there's a comment, trim it from the statement
2926 let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
2927
2928 // In this loop, if there is ever a non-label, no labels can come after it.
2929 let mut start_idx = 0;
2930 'label_loop: for (idx, _) in statement.match_indices(':') {
2931 let possible_label = statement[start_idx..idx].trim();
2932 let mut chars = possible_label.chars();
2933
2934 let Some(start) = chars.next() else {
2935 // Empty string means a leading ':' in this section, which is not a
2936 // label.
2937 break 'label_loop;
2938 };
2939
2940 // Whether a { bracket has been seen and its } hasn't been found yet.
2941 let mut in_bracket = false;
2942 let mut label_kind = AsmLabelKind::Named;
2943
2944 // A label can also start with a format arg, if it's not a raw asm block.
2945 if !raw && start == '{' {
2946 in_bracket = true;
2947 label_kind = AsmLabelKind::FormatArg;
2948 } else if matches!(start, '0' | '1') {
2949 // Binary labels have only the characters `0` or `1`.
2950 label_kind = AsmLabelKind::Binary;
2951 } else if !(start.is_ascii_alphabetic() || matches!(start, '.' | '_')) {
2952 // Named labels start with ASCII letters, `.` or `_`.
2953 // anything else is not a label
2954 break 'label_loop;
2955 }
2956
2957 for c in chars {
2958 // Inside a template format arg, any character is permitted for the
2959 // puproses of label detection because we assume that it can be
2960 // replaced with some other valid label string later. `options(raw)`
2961 // asm blocks cannot have format args, so they are excluded from this
2962 // special case.
2963 if !raw && in_bracket {
2964 if c == '{' {
2965 // Nested brackets are not allowed in format args, this cannot
2966 // be a label.
2967 break 'label_loop;
2968 }
2969
2970 if c == '}' {
2971 // The end of the format arg.
2972 in_bracket = false;
2973 }
2974 } else if !raw && c == '{' {
2975 // Start of a format arg.
2976 in_bracket = true;
2977 label_kind = AsmLabelKind::FormatArg;
2978 } else {
2979 let can_continue = match label_kind {
2980 // Format arg labels are considered to be named labels for the purposes
2981 // of continuing outside of their {} pair.
2982 AsmLabelKind::Named | AsmLabelKind::FormatArg => {
2983 c.is_ascii_alphanumeric() || matches!(c, '_' | '$')
2984 }
2985 AsmLabelKind::Binary => matches!(c, '0' | '1'),
2986 };
2987
2988 if !can_continue {
2989 // The potential label had an invalid character inside it, it
2990 // cannot be a label.
2991 break 'label_loop;
2992 }
2993 }
2994 }
2995
2996 // If all characters passed the label checks, this is a label.
2997 spans.push((find_label_span(possible_label), label_kind));
2998 start_idx = idx + 1;
2999 }
3000 }
3001
3002 for (span, label_kind) in spans {
3003 let missing_precise_span = span.is_none();
3004 let span = span.unwrap_or(*template_span);
3005 match label_kind {
3006 AsmLabelKind::Named => {
3007 cx.emit_span_lint(
3008 NAMED_ASM_LABELS,
3009 span,
3010 InvalidAsmLabel::Named { missing_precise_span },
3011 );
3012 }
3013 AsmLabelKind::FormatArg => {
3014 cx.emit_span_lint(
3015 NAMED_ASM_LABELS,
3016 span,
3017 InvalidAsmLabel::FormatArg { missing_precise_span },
3018 );
3019 }
3020 // the binary asm issue only occurs when using intel syntax on x86 targets
3021 AsmLabelKind::Binary
3022 if !options.contains(InlineAsmOptions::ATT_SYNTAX)
3023 && matches!(
3024 cx.tcx.sess.asm_arch,
3025 Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None
3026 ) =>
3027 {
3028 cx.emit_span_lint(
3029 BINARY_ASM_LABELS,
3030 span,
3031 InvalidAsmLabel::Binary { missing_precise_span, span },
3032 )
3033 }
3034 // No lint on anything other than x86
3035 AsmLabelKind::Binary => (),
3036 };
3037 }
3038 }
3039 }
3040 }
3041}
3042
3043declare_lint! {
3044 /// The `special_module_name` lint detects module
3045 /// declarations for files that have a special meaning.
3046 ///
3047 /// ### Example
3048 ///
3049 /// ```rust,compile_fail
3050 /// mod lib;
3051 ///
3052 /// fn main() {
3053 /// lib::run();
3054 /// }
3055 /// ```
3056 ///
3057 /// {{produces}}
3058 ///
3059 /// ### Explanation
3060 ///
3061 /// Cargo recognizes `lib.rs` and `main.rs` as the root of a
3062 /// library or binary crate, so declaring them as modules
3063 /// will lead to miscompilation of the crate unless configured
3064 /// explicitly.
3065 ///
3066 /// To access a library from a binary target within the same crate,
3067 /// use `your_crate_name::` as the path instead of `lib::`:
3068 ///
3069 /// ```rust,compile_fail
3070 /// // bar/src/lib.rs
3071 /// fn run() {
3072 /// // ...
3073 /// }
3074 ///
3075 /// // bar/src/main.rs
3076 /// fn main() {
3077 /// bar::run();
3078 /// }
3079 /// ```
3080 ///
3081 /// Binary targets cannot be used as libraries and so declaring
3082 /// one as a module is not allowed.
3083 pub SPECIAL_MODULE_NAME,
3084 Warn,
3085 "module declarations for files with a special meaning",
3086}
3087
3088declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3089
3090impl EarlyLintPass for SpecialModuleName {
3091 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3092 for item in &krate.items {
3093 if let ast::ItemKind::Mod(
3094 _,
3095 ident,
3096 ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No { .. }, _),
3097 ) = item.kind
3098 {
3099 if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3100 continue;
3101 }
3102
3103 match ident.name.as_str() {
3104 "lib" => cx.emit_span_lint(
3105 SPECIAL_MODULE_NAME,
3106 item.span,
3107 BuiltinSpecialModuleNameUsed::Lib,
3108 ),
3109 "main" => cx.emit_span_lint(
3110 SPECIAL_MODULE_NAME,
3111 item.span,
3112 BuiltinSpecialModuleNameUsed::Main,
3113 ),
3114 _ => continue,
3115 }
3116 }
3117 }
3118 }
3119}