Skip to content

Commit 41b6f32

Browse files
authored
Merge branch 'rust-lang:master' into validate-paths
2 parents adbcf2d + 227e43a commit 41b6f32

17 files changed

+370
-144
lines changed

.github/workflows/lintcheck.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ jobs:
4949
path: target/debug/lintcheck
5050
key: lintcheck-bin-${{ hashfiles('lintcheck/**') }}
5151

52+
# Install cmake to build aws-lc-sys to build tokio-rustls
53+
- name: Install cmake
54+
run: sudo apt-get install -y cmake
55+
5256
- name: Build lintcheck
5357
if: steps.cache-lintcheck-bin.outputs.cache-hit != 'true'
5458
run: cargo build --manifest-path=lintcheck/Cargo.toml
@@ -92,6 +96,10 @@ jobs:
9296
path: target/debug/lintcheck
9397
key: lintcheck-bin-${{ hashfiles('lintcheck/**') }}
9498

99+
# Install cmake to build aws-lc-sys to build tokio-rustls
100+
- name: Install cmake
101+
run: sudo apt-get install -y cmake
102+
95103
- name: Build lintcheck
96104
if: steps.cache-lintcheck-bin.outputs.cache-hit != 'true'
97105
run: cargo build --manifest-path=lintcheck/Cargo.toml

clippy_lints/src/doc/missing_headers.rs

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
use super::{DocHeaders, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, MISSING_SAFETY_DOC, UNNECESSARY_SAFETY_DOC};
22
use clippy_utils::diagnostics::{span_lint, span_lint_and_note};
3-
use clippy_utils::ty::{implements_trait_with_env, is_type_diagnostic_item};
4-
use clippy_utils::{is_doc_hidden, return_ty};
3+
use clippy_utils::macros::{is_panic, root_macro_call_first_node};
4+
use clippy_utils::ty::{get_type_diagnostic_name, implements_trait_with_env, is_type_diagnostic_item};
5+
use clippy_utils::visitors::for_each_expr;
6+
use clippy_utils::{fulfill_or_allowed, is_doc_hidden, method_chain_args, return_ty};
57
use rustc_hir::{BodyId, FnSig, OwnerId, Safety};
68
use rustc_lint::LateContext;
79
use rustc_middle::ty;
810
use rustc_span::{Span, sym};
11+
use std::ops::ControlFlow;
912

1013
pub fn check(
1114
cx: &LateContext<'_>,
1215
owner_id: OwnerId,
1316
sig: FnSig<'_>,
1417
headers: DocHeaders,
1518
body_id: Option<BodyId>,
16-
panic_info: Option<(Span, bool)>,
1719
check_private_items: bool,
1820
) {
1921
if !check_private_items && !cx.effective_visibilities.is_exported(owner_id.def_id) {
@@ -46,13 +48,16 @@ pub fn check(
4648
),
4749
_ => (),
4850
}
49-
if !headers.panics && panic_info.is_some_and(|el| !el.1) {
51+
if !headers.panics
52+
&& let Some(body_id) = body_id
53+
&& let Some(panic_span) = find_panic(cx, body_id)
54+
{
5055
span_lint_and_note(
5156
cx,
5257
MISSING_PANICS_DOC,
5358
span,
5459
"docs for function which may panic missing `# Panics` section",
55-
panic_info.map(|el| el.0),
60+
Some(panic_span),
5661
"first possible panic found here",
5762
);
5863
}
@@ -89,3 +94,39 @@ pub fn check(
8994
}
9095
}
9196
}
97+
98+
fn find_panic(cx: &LateContext<'_>, body_id: BodyId) -> Option<Span> {
99+
let mut panic_span = None;
100+
let typeck = cx.tcx.typeck_body(body_id);
101+
for_each_expr(cx, cx.tcx.hir_body(body_id), |expr| {
102+
if let Some(macro_call) = root_macro_call_first_node(cx, expr)
103+
&& (is_panic(cx, macro_call.def_id)
104+
|| matches!(
105+
cx.tcx.get_diagnostic_name(macro_call.def_id),
106+
Some(sym::assert_macro | sym::assert_eq_macro | sym::assert_ne_macro)
107+
))
108+
&& !cx.tcx.hir_is_inside_const_context(expr.hir_id)
109+
&& !fulfill_or_allowed(cx, MISSING_PANICS_DOC, [expr.hir_id])
110+
&& panic_span.is_none()
111+
{
112+
panic_span = Some(macro_call.span);
113+
}
114+
115+
// check for `unwrap` and `expect` for both `Option` and `Result`
116+
if let Some(arglists) = method_chain_args(expr, &["unwrap"]).or_else(|| method_chain_args(expr, &["expect"]))
117+
&& let receiver_ty = typeck.expr_ty(arglists[0].0).peel_refs()
118+
&& matches!(
119+
get_type_diagnostic_name(cx, receiver_ty),
120+
Some(sym::Option | sym::Result)
121+
)
122+
&& !fulfill_or_allowed(cx, MISSING_PANICS_DOC, [expr.hir_id])
123+
&& panic_span.is_none()
124+
{
125+
panic_span = Some(expr.span);
126+
}
127+
128+
// Visit all nodes to fulfill any `#[expect]`s after the first linted panic
129+
ControlFlow::<!>::Continue(())
130+
});
131+
panic_span
132+
}

clippy_lints/src/doc/mod.rs

Lines changed: 19 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,8 @@
33
use clippy_config::Conf;
44
use clippy_utils::attrs::is_doc_hidden;
55
use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_then};
6-
use clippy_utils::macros::{is_panic, root_macro_call_first_node};
76
use clippy_utils::source::snippet_opt;
8-
use clippy_utils::ty::is_type_diagnostic_item;
9-
use clippy_utils::visitors::Visitable;
10-
use clippy_utils::{is_entrypoint_fn, is_trait_impl_item, method_chain_args};
7+
use clippy_utils::{is_entrypoint_fn, is_trait_impl_item};
118
use pulldown_cmark::Event::{
129
Code, DisplayMath, End, FootnoteReference, HardBreak, Html, InlineHtml, InlineMath, Rule, SoftBreak, Start,
1310
TaskListMarker, Text,
@@ -16,18 +13,15 @@ use pulldown_cmark::Tag::{BlockQuote, CodeBlock, FootnoteDefinition, Heading, It
1613
use pulldown_cmark::{BrokenLink, CodeBlockKind, CowStr, Options, TagEnd};
1714
use rustc_data_structures::fx::FxHashSet;
1815
use rustc_errors::Applicability;
19-
use rustc_hir::intravisit::{self, Visitor};
20-
use rustc_hir::{AnonConst, Attribute, Expr, ImplItemKind, ItemKind, Node, Safety, TraitItemKind};
16+
use rustc_hir::{Attribute, ImplItemKind, ItemKind, Node, Safety, TraitItemKind};
2117
use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
22-
use rustc_middle::hir::nested_filter;
23-
use rustc_middle::ty;
2418
use rustc_resolve::rustdoc::{
2519
DocFragment, add_doc_fragment, attrs_to_doc_fragments, main_body_opts, source_span_for_markdown_range,
2620
span_of_fragments,
2721
};
2822
use rustc_session::impl_lint_pass;
23+
use rustc_span::Span;
2924
use rustc_span::edition::Edition;
30-
use rustc_span::{Span, sym};
3125
use std::ops::Range;
3226
use url::Url;
3327

@@ -194,6 +188,19 @@ declare_clippy_lint! {
194188
/// }
195189
/// }
196190
/// ```
191+
///
192+
/// Individual panics within a function can be ignored with `#[expect]` or
193+
/// `#[allow]`:
194+
///
195+
/// ```no_run
196+
/// # use std::num::NonZeroUsize;
197+
/// pub fn will_not_panic(x: usize) {
198+
/// #[expect(clippy::missing_panics_doc, reason = "infallible")]
199+
/// let y = NonZeroUsize::new(1).unwrap();
200+
///
201+
/// // If any panics are added in the future the lint will still catch them
202+
/// }
203+
/// ```
197204
#[clippy::version = "1.51.0"]
198205
pub MISSING_PANICS_DOC,
199206
pedantic,
@@ -657,20 +664,16 @@ impl<'tcx> LateLintPass<'tcx> for Documentation {
657664
self.check_private_items,
658665
);
659666
match item.kind {
660-
ItemKind::Fn { sig, body: body_id, .. } => {
667+
ItemKind::Fn { sig, body, .. } => {
661668
if !(is_entrypoint_fn(cx, item.owner_id.to_def_id())
662669
|| item.span.in_external_macro(cx.tcx.sess.source_map()))
663670
{
664-
let body = cx.tcx.hir_body(body_id);
665-
666-
let panic_info = FindPanicUnwrap::find_span(cx, cx.tcx.typeck(item.owner_id), body.value);
667671
missing_headers::check(
668672
cx,
669673
item.owner_id,
670674
sig,
671675
headers,
672-
Some(body_id),
673-
panic_info,
676+
Some(body),
674677
self.check_private_items,
675678
);
676679
}
@@ -697,32 +700,20 @@ impl<'tcx> LateLintPass<'tcx> for Documentation {
697700
if let TraitItemKind::Fn(sig, ..) = trait_item.kind
698701
&& !trait_item.span.in_external_macro(cx.tcx.sess.source_map())
699702
{
700-
missing_headers::check(
701-
cx,
702-
trait_item.owner_id,
703-
sig,
704-
headers,
705-
None,
706-
None,
707-
self.check_private_items,
708-
);
703+
missing_headers::check(cx, trait_item.owner_id, sig, headers, None, self.check_private_items);
709704
}
710705
},
711706
Node::ImplItem(impl_item) => {
712707
if let ImplItemKind::Fn(sig, body_id) = impl_item.kind
713708
&& !impl_item.span.in_external_macro(cx.tcx.sess.source_map())
714709
&& !is_trait_impl_item(cx, impl_item.hir_id())
715710
{
716-
let body = cx.tcx.hir_body(body_id);
717-
718-
let panic_span = FindPanicUnwrap::find_span(cx, cx.tcx.typeck(impl_item.owner_id), body.value);
719711
missing_headers::check(
720712
cx,
721713
impl_item.owner_id,
722714
sig,
723715
headers,
724716
Some(body_id),
725-
panic_span,
726717
self.check_private_items,
727718
);
728719
}
@@ -1168,71 +1159,6 @@ fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize
11681159
headers
11691160
}
11701161

1171-
struct FindPanicUnwrap<'a, 'tcx> {
1172-
cx: &'a LateContext<'tcx>,
1173-
is_const: bool,
1174-
panic_span: Option<Span>,
1175-
typeck_results: &'tcx ty::TypeckResults<'tcx>,
1176-
}
1177-
1178-
impl<'a, 'tcx> FindPanicUnwrap<'a, 'tcx> {
1179-
pub fn find_span(
1180-
cx: &'a LateContext<'tcx>,
1181-
typeck_results: &'tcx ty::TypeckResults<'tcx>,
1182-
body: impl Visitable<'tcx>,
1183-
) -> Option<(Span, bool)> {
1184-
let mut vis = Self {
1185-
cx,
1186-
is_const: false,
1187-
panic_span: None,
1188-
typeck_results,
1189-
};
1190-
body.visit(&mut vis);
1191-
vis.panic_span.map(|el| (el, vis.is_const))
1192-
}
1193-
}
1194-
1195-
impl<'tcx> Visitor<'tcx> for FindPanicUnwrap<'_, 'tcx> {
1196-
type NestedFilter = nested_filter::OnlyBodies;
1197-
1198-
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
1199-
if self.panic_span.is_some() {
1200-
return;
1201-
}
1202-
1203-
if let Some(macro_call) = root_macro_call_first_node(self.cx, expr)
1204-
&& (is_panic(self.cx, macro_call.def_id)
1205-
|| matches!(
1206-
self.cx.tcx.item_name(macro_call.def_id).as_str(),
1207-
"assert" | "assert_eq" | "assert_ne"
1208-
))
1209-
{
1210-
self.is_const = self.cx.tcx.hir_is_inside_const_context(expr.hir_id);
1211-
self.panic_span = Some(macro_call.span);
1212-
}
1213-
1214-
// check for `unwrap` and `expect` for both `Option` and `Result`
1215-
if let Some(arglists) = method_chain_args(expr, &["unwrap"]).or(method_chain_args(expr, &["expect"])) {
1216-
let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs();
1217-
if is_type_diagnostic_item(self.cx, receiver_ty, sym::Option)
1218-
|| is_type_diagnostic_item(self.cx, receiver_ty, sym::Result)
1219-
{
1220-
self.panic_span = Some(expr.span);
1221-
}
1222-
}
1223-
1224-
// and check sub-expressions
1225-
intravisit::walk_expr(self, expr);
1226-
}
1227-
1228-
// Panics in const blocks will cause compilation to fail.
1229-
fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
1230-
1231-
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
1232-
self.cx.tcx
1233-
}
1234-
}
1235-
12361162
#[expect(clippy::range_plus_one)] // inclusive ranges aren't the same type
12371163
fn looks_like_refdef(doc: &str, range: Range<usize>) -> Option<Range<usize>> {
12381164
if range.end < range.start {

clippy_lints/src/len_zero.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,11 @@ impl<'tcx> LateLintPass<'tcx> for LenZero {
202202
expr.span,
203203
lhs_expr,
204204
peel_ref_operators(cx, rhs_expr),
205-
(method.ident.name == sym::ne).then_some("!").unwrap_or_default(),
205+
if method.ident.name == sym::ne {
206+
"!"
207+
} else {
208+
Default::default()
209+
},
206210
);
207211
}
208212

clippy_lints/src/matches/single_match.rs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
use clippy_utils::diagnostics::span_lint_and_then;
2-
use clippy_utils::source::{SpanRangeExt, expr_block, snippet, snippet_block_with_context};
2+
use clippy_utils::source::{
3+
SpanRangeExt, expr_block, snippet, snippet_block_with_context, snippet_with_applicability, snippet_with_context,
4+
};
35
use clippy_utils::ty::implements_trait;
46
use clippy_utils::{
57
is_lint_allowed, is_unit_expr, peel_blocks, peel_hir_pat_refs, peel_middle_ty_refs, peel_n_hir_expr_refs,
@@ -34,8 +36,7 @@ fn empty_arm_has_comment(cx: &LateContext<'_>, span: Span) -> bool {
3436
#[rustfmt::skip]
3537
pub(crate) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>], expr: &'tcx Expr<'_>, contains_comments: bool) {
3638
if let [arm1, arm2] = arms
37-
&& arm1.guard.is_none()
38-
&& arm2.guard.is_none()
39+
&& !arms.iter().any(|arm| arm.guard.is_some() || arm.pat.span.from_expansion())
3940
&& !expr.span.from_expansion()
4041
// don't lint for or patterns for now, this makes
4142
// the lint noisy in unnecessary situations
@@ -106,7 +107,7 @@ fn report_single_pattern(
106107
format!(" else {}", expr_block(cx, els, ctxt, "..", Some(expr.span), &mut app))
107108
});
108109

109-
if snippet(cx, ex.span, "..") == snippet(cx, arm.pat.span, "..") {
110+
if ex.span.eq_ctxt(expr.span) && snippet(cx, ex.span, "..") == snippet(cx, arm.pat.span, "..") {
110111
let msg = "this pattern is irrefutable, `match` is useless";
111112
let (sugg, help) = if is_unit_expr(arm.body) {
112113
(String::new(), "`match` expression can be removed")
@@ -163,19 +164,19 @@ fn report_single_pattern(
163164
let msg = "you seem to be trying to use `match` for an equality check. Consider using `if`";
164165
let sugg = format!(
165166
"if {} == {}{} {}{els_str}",
166-
snippet(cx, ex.span, ".."),
167+
snippet_with_context(cx, ex.span, ctxt, "..", &mut app).0,
167168
// PartialEq for different reference counts may not exist.
168169
"&".repeat(ref_count_diff),
169-
snippet(cx, arm.pat.span, ".."),
170+
snippet_with_applicability(cx, arm.pat.span, "..", &mut app),
170171
expr_block(cx, arm.body, ctxt, "..", Some(expr.span), &mut app),
171172
);
172173
(msg, sugg)
173174
} else {
174175
let msg = "you seem to be trying to use `match` for destructuring a single pattern. Consider using `if let`";
175176
let sugg = format!(
176177
"if let {} = {} {}{els_str}",
177-
snippet(cx, arm.pat.span, ".."),
178-
snippet(cx, ex.span, ".."),
178+
snippet_with_applicability(cx, arm.pat.span, "..", &mut app),
179+
snippet_with_context(cx, ex.span, ctxt, "..", &mut app).0,
179180
expr_block(cx, arm.body, ctxt, "..", Some(expr.span), &mut app),
180181
);
181182
(msg, sugg)

0 commit comments

Comments
 (0)