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