1
Fork 0

Rollup merge of #137449 - compiler-errors:control-flow, r=Amanieu,lnicola

Denote `ControlFlow` as `#[must_use]`

I've repeatedly hit bugs in the compiler due to `ControlFlow` not being marked `#[must_use]`. There seems to be an accepted ACP to make the type `#[must_use]` (https://github.com/rust-lang/libs-team/issues/444), so this PR implements that part of it.

Most of the usages in the compiler that trigger this new warning are "root" usages (calling into an API that uses control-flow internally, but for which the callee doesn't really care) and have been suppressed by `let _ = ...`, but I did legitimately find one instance of a missing `?` and one for a never-used `ControlFlow` value in #137448.

Presumably this needs an FCP too, so I'm opening this and nominating it for T-libs-api.

This PR also touches the tools (incl. rust-analyzer), but if this went into FCP, I'd split those out into separate PRs which can land before this one does.

r? libs-api
`@rustbot` label: T-libs-api I-libs-api-nominated
This commit is contained in:
Matthias Krüger 2025-03-17 16:34:47 +01:00 committed by GitHub
commit 9adf2189f5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 67 additions and 62 deletions

View file

@ -2136,7 +2136,7 @@ fn add_library_search_dirs(
}
let fallback = Some(NativeLibSearchFallback { self_contained_components, apple_sdk_root });
walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
let _ = walk_native_lib_search_dirs(sess, fallback, |dir, is_framework| {
if is_framework {
cmd.framework_path(dir);
} else {

View file

@ -533,7 +533,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
_ => {
intravisit::walk_pat(self, p);
let _ = intravisit::walk_pat(self, p);
}
}
ControlFlow::Continue(())
@ -556,7 +556,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
method_name,
sugg_let: None,
};
let_visitor.visit_body(&body);
let _ = let_visitor.visit_body(&body);
if let Some(sugg_let) = let_visitor.sugg_let
&& let Some(self_ty) = self.node_ty_opt(sugg_let.init_hir_id)
{

View file

@ -1361,12 +1361,12 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> {
GenericParamDefKind::Lifetime => {}
GenericParamDefKind::Type { has_default, .. } => {
if has_default {
self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
}
}
// FIXME(generic_const_exprs): May want to look inside const here
GenericParamDefKind::Const { .. } => {
self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
let _ = self.visit(self.tcx.type_of(param.def_id).instantiate_identity());
}
}
}
@ -1381,19 +1381,19 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> {
// consider the ones that the user wrote. This is important
// for the inferred outlives rules; see
// `tests/ui/rfc-2093-infer-outlives/privacy.rs`.
self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
let _ = self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id));
self
}
fn bounds(&mut self) -> &mut Self {
self.in_primary_interface = false;
self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
let _ = self.visit_clauses(self.tcx.explicit_item_bounds(self.item_def_id).skip_binder());
self
}
fn ty(&mut self) -> &mut Self {
self.in_primary_interface = true;
self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity());
let _ = self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity());
self
}
@ -1785,7 +1785,7 @@ fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let module = tcx.hir_module_items(module_def_id);
for def_id in module.definitions() {
rustc_ty_utils::sig_types::walk_types(tcx, def_id, &mut visitor);
let _ = rustc_ty_utils::sig_types::walk_types(tcx, def_id, &mut visitor);
if let Some(body_id) = tcx.hir_maybe_body_owned_by(def_id) {
visitor.visit_nested_body(body_id.id());
@ -1798,7 +1798,11 @@ fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
let trait_ref = tcx.impl_trait_ref(id.owner_id.def_id).unwrap();
let trait_ref = trait_ref.instantiate_identity();
visitor.span = item.path.span;
visitor.visit_def_id(trait_ref.def_id, "trait", &trait_ref.print_only_trait_path());
let _ = visitor.visit_def_id(
trait_ref.def_id,
"trait",
&trait_ref.print_only_trait_path(),
);
}
}
}

View file

@ -77,7 +77,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> {
match arg.kind {
hir::TyKind::BareFn(_) => {
self.current_index.shift_in(1);
intravisit::walk_ty(self, arg);
let _ = intravisit::walk_ty(self, arg);
self.current_index.shift_out(1);
return ControlFlow::Continue(());
}
@ -85,7 +85,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> {
hir::TyKind::TraitObject(bounds, ..) => {
for bound in bounds {
self.current_index.shift_in(1);
self.visit_poly_trait_ref(bound);
let _ = self.visit_poly_trait_ref(bound);
self.current_index.shift_out(1);
}
}

View file

@ -743,7 +743,7 @@ fn assemble_candidates_from_trait_def<'cx, 'tcx>(
) {
debug!("assemble_candidates_from_trait_def(..)");
let mut ambiguous = false;
selcx.for_each_item_bound(
let _ = selcx.for_each_item_bound(
obligation.predicate.self_ty(),
|selcx, clause, _| {
let Some(clause) = clause.as_projection_clause() else {

View file

@ -176,7 +176,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// normalization, so try to deduplicate when possible to avoid
// unnecessary ambiguity.
let mut distinct_normalized_bounds = FxHashSet::default();
self.for_each_item_bound::<!>(
let _ = self.for_each_item_bound::<!>(
placeholder_trait_predicate.self_ty(),
|selcx, bound, idx| {
let Some(bound) = bound.as_trait_clause() else {

View file

@ -112,7 +112,7 @@ where
pub fn bind_with_vars(value: T, bound_vars: I::BoundVarKinds) -> Binder<I, T> {
if cfg!(debug_assertions) {
let mut validator = ValidateBoundVars::new(bound_vars);
value.visit_with(&mut validator);
let _ = value.visit_with(&mut validator);
}
Binder { value, bound_vars }
}
@ -196,7 +196,7 @@ impl<I: Interner, T> Binder<I, T> {
let value = f(value);
if cfg!(debug_assertions) {
let mut validator = ValidateBoundVars::new(bound_vars);
value.visit_with(&mut validator);
let _ = value.visit_with(&mut validator);
}
Binder { value, bound_vars }
}
@ -209,7 +209,7 @@ impl<I: Interner, T> Binder<I, T> {
let value = f(value)?;
if cfg!(debug_assertions) {
let mut validator = ValidateBoundVars::new(bound_vars);
value.visit_with(&mut validator);
let _ = value.visit_with(&mut validator);
}
Ok(Binder { value, bound_vars })
}

View file

@ -80,6 +80,7 @@ use crate::{convert, ops};
/// [`Continue`]: ControlFlow::Continue
#[stable(feature = "control_flow_enum_type", since = "1.55.0")]
#[rustc_diagnostic_item = "ControlFlow"]
#[must_use]
// ControlFlow should not implement PartialOrd or Ord, per RFC 3058:
// https://rust-lang.github.io/rfcs/3058-try-trait-v2.html#traits-for-controlflow
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]

View file

@ -9,41 +9,41 @@ fn empty() {
#[test]
fn basic() {
let mut buf = HtmlWithLimit::new(60);
buf.push("Hello ");
let _ = buf.push("Hello ");
buf.open_tag("em");
buf.push("world");
let _ = buf.push("world");
buf.close_tag();
buf.push("!");
let _ = buf.push("!");
assert_eq!(buf.finish(), "Hello <em>world</em>!");
}
#[test]
fn no_tags() {
let mut buf = HtmlWithLimit::new(60);
buf.push("Hello");
buf.push(" world!");
let _ = buf.push("Hello");
let _ = buf.push(" world!");
assert_eq!(buf.finish(), "Hello world!");
}
#[test]
fn limit_0() {
let mut buf = HtmlWithLimit::new(0);
buf.push("Hello ");
let _ = buf.push("Hello ");
buf.open_tag("em");
buf.push("world");
let _ = buf.push("world");
buf.close_tag();
buf.push("!");
let _ = buf.push("!");
assert_eq!(buf.finish(), "");
}
#[test]
fn exactly_limit() {
let mut buf = HtmlWithLimit::new(12);
buf.push("Hello ");
let _ = buf.push("Hello ");
buf.open_tag("em");
buf.push("world");
let _ = buf.push("world");
buf.close_tag();
buf.push("!");
let _ = buf.push("!");
assert_eq!(buf.finish(), "Hello <em>world</em>!");
}
@ -51,11 +51,11 @@ fn exactly_limit() {
fn multiple_nested_tags() {
let mut buf = HtmlWithLimit::new(60);
buf.open_tag("p");
buf.push("This is a ");
let _ = buf.push("This is a ");
buf.open_tag("em");
buf.push("paragraph");
let _ = buf.push("paragraph");
buf.open_tag("strong");
buf.push("!");
let _ = buf.push("!");
buf.close_tag();
buf.close_tag();
buf.close_tag();
@ -66,11 +66,11 @@ fn multiple_nested_tags() {
fn forgot_to_close_tags() {
let mut buf = HtmlWithLimit::new(60);
buf.open_tag("p");
buf.push("This is a ");
let _ = buf.push("This is a ");
buf.open_tag("em");
buf.push("paragraph");
let _ = buf.push("paragraph");
buf.open_tag("strong");
buf.push("!");
let _ = buf.push("!");
assert_eq!(buf.finish(), "<p>This is a <em>paragraph<strong>!</strong></em></p>");
}
@ -78,10 +78,10 @@ fn forgot_to_close_tags() {
fn past_the_limit() {
let mut buf = HtmlWithLimit::new(20);
buf.open_tag("p");
(0..10).try_for_each(|n| {
let _ = (0..10).try_for_each(|n| {
buf.open_tag("strong");
buf.push("word#")?;
buf.push(&n.to_string())?;
let _ = buf.push("word#")?;
let _ = buf.push(&n.to_string())?;
buf.close_tag();
ControlFlow::Continue(())
});
@ -100,8 +100,8 @@ fn past_the_limit() {
fn quickly_past_the_limit() {
let mut buf = HtmlWithLimit::new(6);
buf.open_tag("p");
buf.push("Hello");
buf.push(" World");
let _ = buf.push("Hello");
let _ = buf.push(" World");
// intentionally not closing <p> before finishing
assert_eq!(buf.finish(), "<p>Hello</p>");
}
@ -110,7 +110,7 @@ fn quickly_past_the_limit() {
fn close_too_many() {
let mut buf = HtmlWithLimit::new(60);
buf.open_tag("p");
buf.push("Hello");
let _ = buf.push("Hello");
buf.close_tag();
// This call does not panic because there are valid cases
// where `close_tag()` is called with no tags left to close.

View file

@ -1568,7 +1568,7 @@ fn markdown_summary_with_limit(
let mut buf = HtmlWithLimit::new(length_limit);
let mut stopped_early = false;
p.try_for_each(|event| {
let _ = p.try_for_each(|event| {
match &event {
Event::Text(text) => {
let r =

View file

@ -129,7 +129,7 @@ impl BreakAfterExprVisitor {
};
get_enclosing_block(cx, hir_id).is_some_and(|block| {
visitor.visit_block(block);
let _ = visitor.visit_block(block);
visitor.break_after_expr
})
}

View file

@ -40,7 +40,7 @@ pub fn check(cx: &LateContext<'_>, call: &Expr<'_>, recv: &Expr<'_>, arg: &Expr<
// We've checked that `call` is a call to `Stdin::read_line()` with the right receiver,
// now let's check if the first use of the string passed to `::read_line()`
// is used for operations that will always fail (e.g. parsing "6\n" into a number)
for_each_local_use_after_expr(cx, local_id, call.hir_id, |expr| {
let _ = for_each_local_use_after_expr(cx, local_id, call.hir_id, |expr| {
if let Some(parent) = get_parent_expr(cx, expr) {
let data = if let ExprKind::MethodCall(segment, recv, args, span) = parent.kind {
if args.is_empty()

View file

@ -141,7 +141,7 @@ impl PassByRefOrValue {
// Gather all the lifetimes found in the output type which may affect whether
// `TRIVIALLY_COPY_PASS_BY_REF` should be linted.
let mut output_regions = FxHashSet::default();
for_each_top_level_late_bound_region(fn_sig.skip_binder().output(), |region| -> ControlFlow<!> {
let _ = for_each_top_level_late_bound_region(fn_sig.skip_binder().output(), |region| -> ControlFlow<!> {
output_regions.insert(region);
ControlFlow::Continue(())
});

View file

@ -381,7 +381,7 @@ impl UnconditionalRecursion {
implemented_ty_id,
method_span,
};
walk_body(&mut c, body);
let _ = walk_body(&mut c, body);
}
}
}

View file

@ -145,19 +145,19 @@ impl chalk_solve::RustIrDatabase<Interner> for ChalkContext<'_> {
let mut result = vec![];
if fps.is_empty() {
debug!("Unrestricted search for {:?} impls...", trait_);
self.for_trait_impls(trait_, self_ty_fp, |impls| {
let _ = self.for_trait_impls(trait_, self_ty_fp, |impls| {
result.extend(impls.for_trait(trait_).map(id_to_chalk));
ControlFlow::Continue(())
})
});
} else {
self.for_trait_impls(trait_, self_ty_fp, |impls| {
let _ = self.for_trait_impls(trait_, self_ty_fp, |impls| {
result.extend(
fps.iter().flat_map(move |fp| {
impls.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
}),
);
ControlFlow::Continue(())
})
});
};
debug!("impls_for_trait returned {} impls", result.len());

View file

@ -116,7 +116,7 @@ pub fn dyn_compatibility_of_trait_query(
trait_: TraitId,
) -> Option<DynCompatibilityViolation> {
let mut res = None;
dyn_compatibility_of_trait_with_callback(db, trait_, &mut |osv| {
let _ = dyn_compatibility_of_trait_with_callback(db, trait_, &mut |osv| {
res = Some(osv);
ControlFlow::Break(())
});
@ -597,7 +597,7 @@ fn contains_illegal_impl_trait_in_trait(
let ret = sig.skip_binders().ret();
let mut visitor = OpaqueTypeCollector(FxHashSet::default());
ret.visit_with(visitor.as_dyn(), DebruijnIndex::INNERMOST);
let _ = ret.visit_with(visitor.as_dyn(), DebruijnIndex::INNERMOST);
// Since we haven't implemented RPITIT in proper way like rustc yet,
// just check whether `ret` contains RPIT for now

View file

@ -53,7 +53,7 @@ fn check_dyn_compatibility<'a>(
continue;
};
let mut osvs = FxHashSet::default();
dyn_compatibility_with_callback(&db, trait_id, &mut |osv| {
let _ = dyn_compatibility_with_callback(&db, trait_id, &mut |osv| {
osvs.insert(match osv {
DynCompatibilityViolation::SizedSelf => SizedSelf,
DynCompatibilityViolation::SelfReferential => SelfReferential,

View file

@ -1143,7 +1143,7 @@ impl<'a> InferenceContext<'a> {
non_assocs: FxHashMap::default(),
};
for ty in tait_candidates {
ty.visit_with(collector.as_dyn(), DebruijnIndex::INNERMOST);
let _ = ty.visit_with(collector.as_dyn(), DebruijnIndex::INNERMOST);
}
// Non-assoc TAITs can be define-used everywhere as long as they are

View file

@ -1033,7 +1033,7 @@ where
T: ?Sized + TypeVisitable<Interner>,
{
let mut collector = PlaceholderCollector { db, placeholders: FxHashSet::default() };
value.visit_with(&mut collector, DebruijnIndex::INNERMOST);
let _ = value.visit_with(&mut collector, DebruijnIndex::INNERMOST);
collector.placeholders.into_iter().collect()
}

View file

@ -596,7 +596,7 @@ pub(crate) fn iterate_method_candidates<T>(
mut callback: impl FnMut(ReceiverAdjustments, AssocItemId, bool) -> Option<T>,
) -> Option<T> {
let mut slot = None;
iterate_method_candidates_dyn(
let _ = iterate_method_candidates_dyn(
ty,
db,
env,

View file

@ -260,7 +260,7 @@ fn resolve_impl_trait_item(
// attributes here. Use path resolution directly instead.
//
// FIXME: resolve type aliases (which are not yielded by iterate_path_candidates)
method_resolution::iterate_path_candidates(
let _ = method_resolution::iterate_path_candidates(
&canonical,
db,
environment,

View file

@ -2911,7 +2911,7 @@ impl Trait {
db: &dyn HirDatabase,
) -> Option<Vec<DynCompatibilityViolation>> {
let mut violations = vec![];
hir_ty::dyn_compatibility::dyn_compatibility_with_callback(db, self.id, &mut |violation| {
let _ = hir_ty::dyn_compatibility::dyn_compatibility_with_callback(db, self.id, &mut |violation| {
violations.push(violation);
ControlFlow::Continue(())
});
@ -5497,7 +5497,7 @@ impl Type {
.generic_def()
.map_or_else(|| TraitEnvironment::empty(krate.id), |d| db.trait_environment(d));
method_resolution::iterate_method_candidates_dyn(
let _ = method_resolution::iterate_method_candidates_dyn(
&canonical,
db,
environment,
@ -5584,7 +5584,7 @@ impl Type {
.generic_def()
.map_or_else(|| TraitEnvironment::empty(krate.id), |d| db.trait_environment(d));
method_resolution::iterate_path_candidates(
let _ = method_resolution::iterate_path_candidates(
&canonical,
db,
environment,

View file

@ -750,7 +750,7 @@ impl FunctionBody {
ast::Stmt::Item(_) => (),
ast::Stmt::LetStmt(stmt) => {
if let Some(pat) = stmt.pat() {
walk_pat(&pat, &mut |pat| {
let _ = walk_pat(&pat, &mut |pat| {
cb(pat);
std::ops::ControlFlow::<(), ()>::Continue(())
});

View file

@ -121,7 +121,7 @@ pub fn walk_patterns_in_expr(start: &ast::Expr, cb: &mut dyn FnMut(ast::Pat)) {
match ast::Stmt::cast(node.clone()) {
Some(ast::Stmt::LetStmt(l)) => {
if let Some(pat) = l.pat() {
walk_pat(&pat, &mut |pat| {
let _ = walk_pat(&pat, &mut |pat| {
cb(pat);
ControlFlow::<(), ()>::Continue(())
});
@ -159,7 +159,7 @@ pub fn walk_patterns_in_expr(start: &ast::Expr, cb: &mut dyn FnMut(ast::Pat)) {
}
} else if let Some(pat) = ast::Pat::cast(node) {
preorder.skip_subtree();
walk_pat(&pat, &mut |pat| {
let _ = walk_pat(&pat, &mut |pat| {
cb(pat);
ControlFlow::<(), ()>::Continue(())
});