Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
a4bd5f5
compiler: suggest `.collect()` when `String` is expected and `Iterato…
thiago-fealves May 3, 2026
e1941ff
Update compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
thiago-fealves May 4, 2026
ecf0191
Avoid rustfix suggestions for macro-expanded unused imports
cijiugechu May 15, 2026
9d76912
comment for issue id
cijiugechu May 15, 2026
209ee9d
use edition 2021
cijiugechu May 15, 2026
5f2e455
rustdoc: add test case for `-Drustdoc::` CLI param
notriddle May 15, 2026
0344a02
rustdoc: add test case for `--cap-lints=allow`
notriddle May 15, 2026
124126e
Test EII UI tests with prefer-dynamic
AsakuraMizu May 14, 2026
87821d9
Add regression test for issue 41261
eval-exec May 16, 2026
6d91f14
fix
bb1yd May 16, 2026
053761d
minor `rustc_mir_transform` cleanup
Human9000-bit May 11, 2026
e599831
suggest hex escapes for C-style escapes
euclio May 9, 2026
2071c66
Add interior-mutability suggestion to `static_mut_refs`
JohnTitor Jan 19, 2026
cbaee5d
Tweak note condition
JohnTitor Mar 5, 2026
33d92f7
Add test for the case span is unavailable
JohnTitor May 17, 2026
ee8949e
Add FIXME for `interior_mutability_suggestion`
JohnTitor May 17, 2026
ae7fb7c
Rollup merge of #151362 - JohnTitor:interior-mutability-sugg, r=estebank
JonathanBrouwer May 17, 2026
5aa6e4b
Rollup merge of #156121 - thiago-fealves:suggest-collect-string, r=es…
JonathanBrouwer May 17, 2026
5ac3b46
Rollup merge of #156376 - euclio:foreign-escapes, r=mu001999
JonathanBrouwer May 17, 2026
67488f6
Rollup merge of #156577 - AsakuraMizu:eii-default-dynamic, r=mejrs
JonathanBrouwer May 17, 2026
149960f
Rollup merge of #156598 - cijiugechu:decl-macro-diag, r=mu001999
JonathanBrouwer May 17, 2026
33a4f42
Rollup merge of #156616 - notriddle:rustdoc-ui-test-cli, r=GuillaumeG…
JonathanBrouwer May 17, 2026
1d670eb
Rollup merge of #156633 - eval-exec:issue-41261-regression-test, r=mu…
JonathanBrouwer May 17, 2026
9d5d8d8
Rollup merge of #156635 - bb1yd:rename_unexpected_try_recover, r=John…
JonathanBrouwer May 17, 2026
fa73156
Rollup merge of #156636 - Human9000-bit:mir-transform-ref, r=Kivooeo
JonathanBrouwer May 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|| self.suggest_semicolon_in_repeat_expr(err, expr, expr_ty)
|| self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
|| self.suggest_option_to_bool(err, expr, expr_ty, expected)
|| self.suggest_collect(err, expr, expected, expr_ty)
|| self.suggest_compatible_variants(err, expr, expected, expr_ty)
|| self.suggest_non_zero_new_unwrap(err, expr, expected, expr_ty)
|| self.suggest_calling_boxed_future_when_appropriate(err, expr, expected, expr_ty)
Expand Down
68 changes: 68 additions & 0 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,74 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

/// Suggests calling `.collect()` on an `Iterator` it can be collected in the return type
/// ```compile_fail
/// let x: String = "foo".chars().map(|c| c); // with a .collect() here the code compiles
/// ```
pub(crate) fn suggest_collect(
&self,
err: &mut Diag<'_>,
expr: &hir::Expr<'_>,
expected_type: Ty<'tcx>,
found_type: Ty<'tcx>,
) -> bool {
let tcx = self.tcx;
let expected = self.resolve_vars_if_possible(expected_type);
let found = self.resolve_vars_if_possible(found_type);

if expected.references_error() || found.references_error() || expected.is_unit() {
return false;
}

let Some(iterator_trait_id) = tcx.get_diagnostic_item(sym::Iterator) else {
return false;
};

if !self
.infcx
.type_implements_trait(iterator_trait_id, [found], self.param_env)
.must_apply_modulo_regions()
{
return false;
}

let Some(from_iterator_trait_id) = tcx.get_diagnostic_item(sym::FromIterator) else {
return false;
};

let Some(iterator_item_id) = tcx
.associated_items(iterator_trait_id)
.in_definition_order()
.find(|item| item.name() == sym::Item)
.map(|item| item.def_id)
else {
return false;
};

let item_type = Ty::new_projection(tcx, iterator_item_id, [found]);
let item_type =
self.normalize(expr.span, rustc_middle::ty::Unnormalized::new_wip(item_type));

let can_collect = self
.infcx
.type_implements_trait(from_iterator_trait_id, [expected, item_type], self.param_env)
.may_apply();

if can_collect {
err.span_suggestion_verbose(
expr.span.shrink_to_hi(),
format!(
"consider using `.collect()` to convert the `Iterator` into a `{expected}`"
),
".collect()",
rustc_errors::Applicability::MaybeIncorrect,
);
return true;
}

false
}

pub(crate) fn suggest_remove_last_method_call(
&self,
err: &mut Diag<'_>,
Expand Down
18 changes: 18 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2669,6 +2669,12 @@ pub(crate) struct RefOfMutStatic<'a> {
"mutable references to mutable statics are dangerous; it's undefined behavior if any other pointer to the static is used or if any other reference is created for the static while the mutable reference lives"
)]
pub mut_note: bool,
#[help(
"use a type that relies on \"interior mutability\" instead; to read more on this, visit <https://doc.rust-lang.org/reference/interior-mutability.html>"
)]
pub interior_mutability_help: bool,
#[subdiagnostic]
pub interior_mutability_sugg: Option<StaticMutRefsInteriorMutabilitySugg>,
}

#[derive(Subdiagnostic)]
Expand All @@ -2693,6 +2699,18 @@ pub(crate) enum MutRefSugg {
},
}

#[derive(Subdiagnostic)]
#[suggestion(
"this type already provides \"interior mutability\", so its binding doesn't need to be declared as mutable",
style = "verbose",
applicability = "maybe-incorrect",
code = ""
)]
pub(crate) struct StaticMutRefsInteriorMutabilitySugg {
#[primary_span]
pub span: Span,
}

#[derive(Diagnostic)]
#[diag("`use` of a local item without leading `self::`, `super::`, or `crate::`")]
pub(crate) struct UnqualifiedLocalImportsDiag;
Expand Down
147 changes: 136 additions & 11 deletions compiler/rustc_lint/src/static_mut_refs.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_hir::{Expr, Stmt};
use rustc_middle::ty::{Mutability, TyKind};
use rustc_session::lint::fcw;
use rustc_session::{declare_lint, declare_lint_pass};
use rustc_span::{BytePos, Span};

use crate::lints::{MutRefSugg, RefOfMutStatic};
use crate::lints::{MutRefSugg, RefOfMutStatic, StaticMutRefsInteriorMutabilitySugg};
use crate::{LateContext, LateLintPass, LintContext};

declare_lint! {
Expand Down Expand Up @@ -67,7 +68,7 @@ impl<'tcx> LateLintPass<'tcx> for StaticMutRefs {
match expr.kind {
hir::ExprKind::AddrOf(borrow_kind, m, ex)
if matches!(borrow_kind, hir::BorrowKind::Ref)
&& let Some(err_span) = path_is_static_mut(ex, err_span) =>
&& let Some(static_mut) = path_is_static_mut(ex, err_span) =>
{
let source_map = cx.sess().source_map();
let snippet = source_map.span_to_snippet(err_span);
Expand All @@ -86,18 +87,32 @@ impl<'tcx> LateLintPass<'tcx> for StaticMutRefs {
err_span.with_hi(ex.span.lo())
};

emit_static_mut_refs(cx, err_span, sugg_span, m, !expr.span.from_expansion());
emit_static_mut_refs(
cx,
static_mut.err_span,
sugg_span,
m,
!expr.span.from_expansion(),
static_mut.def_id,
);
}
hir::ExprKind::MethodCall(_, e, _, _)
if let Some(err_span) = path_is_static_mut(e, expr.span)
if let Some(static_mut) = path_is_static_mut(e, expr.span)
&& let typeck = cx.typeck_results()
&& let Some(method_def_id) = typeck.type_dependent_def_id(expr.hir_id)
&& let inputs =
cx.tcx.fn_sig(method_def_id).skip_binder().inputs().skip_binder()
&& let Some(receiver) = inputs.get(0)
&& let TyKind::Ref(_, _, m) = receiver.kind() =>
{
emit_static_mut_refs(cx, err_span, err_span.shrink_to_lo(), *m, false);
emit_static_mut_refs(
cx,
static_mut.err_span,
static_mut.err_span.shrink_to_lo(),
*m,
false,
static_mut.def_id,
);
}
_ => {}
}
Expand All @@ -108,14 +123,26 @@ impl<'tcx> LateLintPass<'tcx> for StaticMutRefs {
&& let hir::PatKind::Binding(ba, _, _, _) = loc.pat.kind
&& let hir::ByRef::Yes(_, m) = ba.0
&& let Some(init) = loc.init
&& let Some(err_span) = path_is_static_mut(init, init.span)
&& let Some(static_mut) = path_is_static_mut(init, init.span)
{
emit_static_mut_refs(cx, err_span, err_span.shrink_to_lo(), m, false);
emit_static_mut_refs(
cx,
static_mut.err_span,
static_mut.err_span.shrink_to_lo(),
m,
false,
static_mut.def_id,
);
}
}
}

fn path_is_static_mut(mut expr: &hir::Expr<'_>, mut err_span: Span) -> Option<Span> {
struct StaticMutInfo {
err_span: Span,
def_id: DefId,
}

fn path_is_static_mut(mut expr: &hir::Expr<'_>, mut err_span: Span) -> Option<StaticMutInfo> {
if err_span.from_expansion() {
err_span = expr.span;
}
Expand All @@ -126,11 +153,11 @@ fn path_is_static_mut(mut expr: &hir::Expr<'_>, mut err_span: Span) -> Option<Sp

if let hir::ExprKind::Path(qpath) = expr.kind
&& let hir::QPath::Resolved(_, path) = qpath
&& let hir::def::Res::Def(def_kind, _) = path.res
&& let hir::def::Res::Def(def_kind, def_id) = path.res
&& let hir::def::DefKind::Static { safety: _, mutability: Mutability::Mut, nested: false } =
def_kind
{
return Some(err_span);
return Some(StaticMutInfo { err_span, def_id });
}
None
}
Expand All @@ -141,6 +168,7 @@ fn emit_static_mut_refs(
sugg_span: Span,
mutable: Mutability,
suggest_addr_of: bool,
def_id: DefId,
) {
let (shared_label, shared_note, mut_note, sugg) = match mutable {
Mutability::Mut => {
Expand All @@ -155,9 +183,106 @@ fn emit_static_mut_refs(
}
};

let (interior_mutability_help, interior_mutability_sugg) =
interior_mutability_suggestion(cx, def_id);

cx.emit_span_lint(
STATIC_MUT_REFS,
span,
RefOfMutStatic { span, sugg, shared_label, shared_note, mut_note },
RefOfMutStatic {
span,
sugg,
shared_label,
shared_note,
mut_note,
interior_mutability_help,
interior_mutability_sugg,
},
);
}

// FIXME: This builds suggestion spans by handcrafting from source text.
// Replace this with HIR-based handling once we can identify the `mut` token
// in the static declaration that way.
// Context: https://github.com/rust-lang/rust/pull/151362/changes#r3210767018
fn interior_mutability_suggestion(
cx: &LateContext<'_>,
def_id: DefId,
) -> (bool, Option<StaticMutRefsInteriorMutabilitySugg>) {
let static_ty = cx.tcx.type_of(def_id).skip_binder();
let has_interior_mutability = !static_ty.is_freeze(cx.tcx, cx.typing_env());

if !has_interior_mutability {
return (false, None);
}

let sugg =
static_mutability_span(cx, def_id).map(|span| StaticMutRefsInteriorMutabilitySugg { span });
(sugg.is_none(), sugg)
}

fn static_mutability_span(cx: &LateContext<'_>, def_id: DefId) -> Option<Span> {
let hir_id = cx.tcx.hir_get_if_local(def_id)?;
let hir::Node::Item(item) = hir_id else { return None };
let (mutability, ident) = match item.kind {
hir::ItemKind::Static(mutability, ident, _, _) => (mutability, ident),
_ => return None,
};
if mutability != hir::Mutability::Mut {
return None;
}

let vis_span = item.vis_span.find_ancestor_inside(item.span)?;
if !item.span.can_be_used_for_suggestions() || !vis_span.can_be_used_for_suggestions() {
return None;
}

let header_span = vis_span.between(ident.span);
if !header_span.can_be_used_for_suggestions() {
return None;
}

let source_map = cx.sess().source_map();
let snippet = source_map.span_to_snippet(header_span).ok()?;

let (_static_start, static_end) = find_word(&snippet, "static", 0)?;
let (mut_start, mut_end) = find_word(&snippet, "mut", static_end)?;
let mut_end = extend_trailing_space(&snippet, mut_end);

Some(
header_span
.with_lo(header_span.lo() + BytePos(mut_start as u32))
.with_hi(header_span.lo() + BytePos(mut_end as u32)),
)
}

fn find_word(snippet: &str, word: &str, start: usize) -> Option<(usize, usize)> {
let bytes = snippet.as_bytes();
let word_bytes = word.as_bytes();
let mut search = start;
while search <= snippet.len() {
let found = snippet[search..].find(word)?;
let idx = search + found;
let end = idx + word_bytes.len();
let before_ok = idx == 0 || !is_ident_char(bytes[idx - 1]);
let after_ok = end >= bytes.len() || !is_ident_char(bytes[end]);
if before_ok && after_ok {
return Some((idx, end));
}
search = end;
}
None
}

fn is_ident_char(byte: u8) -> bool {
byte.is_ascii_alphanumeric() || byte == b'_'
}

fn extend_trailing_space(snippet: &str, mut end: usize) -> usize {
if let Some(ch) = snippet[end..].chars().next()
&& (ch == ' ' || ch == '\t')
{
end += ch.len_utf8();
}
end
}
3 changes: 1 addition & 2 deletions compiler/rustc_mir_transform/src/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1072,8 +1072,7 @@ fn make_call_args<'tcx, I: Inliner<'tcx>>(
//
// and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
if callsite.fn_sig.abi() == ExternAbi::RustCall && callee_body.spread_arg.is_none() {
// FIXME(edition_2024): switch back to a normal method call.
let mut args = <_>::into_iter(args);
let mut args = args.into_iter();
let self_ = create_temp_if_necessary(
inliner,
args.next().unwrap().node,
Expand Down
9 changes: 4 additions & 5 deletions compiler/rustc_mir_transform/src/pass_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,15 +296,14 @@ fn run_passes_inner<'tcx>(

if is_optimization_stage(body, phase_change, optimizations)
&& let Some(limit) = &tcx.sess.opts.unstable_opts.mir_opt_bisect_limit
{
if limited_by_opt_bisect(
&& limited_by_opt_bisect(
tcx,
tcx.def_path_debug_str(body.source.def_id()),
*limit,
*pass,
) {
continue;
}
)
{
continue;
}

let dumper = if pass.is_mir_dump_enabled()
Expand Down
Loading
Loading