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