Skip to content

Commit

Permalink
Auto merge of rust-lang#121086 - GuillaumeGomez:rollup-y82fs9y, r=Gui…
Browse files Browse the repository at this point in the history
…llaumeGomez

Rollup of 6 pull requests

Successful merges:

 - rust-lang#120893 (Move some tests)
 - rust-lang#120966 (Remove importing suggestions when there is a shadowed typo candidate)
 - rust-lang#121035 (Format `async` trait bounds in rustfmt)
 - rust-lang#121075 (Fix false positive with if let and ranges)
 - rust-lang#121083 (Extend documentation for `Ty::to_opt_closure_kind` method)
 - rust-lang#121084 (Make sure `tcx.create_def` also depends on the forever red node, instead of just `tcx.at(span).create_def`)

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 14, 2024
2 parents 340bb19 + 2062325 commit 502ce82
Show file tree
Hide file tree
Showing 24 changed files with 125 additions and 43 deletions.
16 changes: 12 additions & 4 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,9 +651,11 @@ trait UnusedDelimLint {

fn is_expr_delims_necessary(
inner: &ast::Expr,
ctx: UnusedDelimsCtx,
followed_by_block: bool,
followed_by_else: bool,
) -> bool {
let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;

if followed_by_else {
match inner.kind {
ast::ExprKind::Binary(op, ..) if op.node.is_lazy() => return true,
Expand All @@ -662,6 +664,13 @@ trait UnusedDelimLint {
}
}

// Check it's range in LetScrutineeExpr
if let ast::ExprKind::Range(..) = inner.kind
&& matches!(ctx, UnusedDelimsCtx::LetScrutineeExpr)
{
return true;
}

// Check if LHS needs parens to prevent false-positives in cases like `fn x() -> u8 { ({ 0 } + 1) }`.
{
let mut innermost = inner;
Expand Down Expand Up @@ -1007,8 +1016,7 @@ impl UnusedDelimLint for UnusedParens {
) {
match value.kind {
ast::ExprKind::Paren(ref inner) => {
let followed_by_else = ctx == UnusedDelimsCtx::AssignedValueLetElse;
if !Self::is_expr_delims_necessary(inner, followed_by_block, followed_by_else)
if !Self::is_expr_delims_necessary(inner, ctx, followed_by_block)
&& value.attrs.is_empty()
&& !value.span.from_expansion()
&& (ctx != UnusedDelimsCtx::LetScrutineeExpr
Expand Down Expand Up @@ -1334,7 +1342,7 @@ impl UnusedDelimLint for UnusedBraces {
// FIXME(const_generics): handle paths when #67075 is fixed.
if let [stmt] = inner.stmts.as_slice() {
if let ast::StmtKind::Expr(ref expr) = stmt.kind {
if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
if !Self::is_expr_delims_necessary(expr, ctx, followed_by_block)
&& (ctx != UnusedDelimsCtx::AnonConst
|| (matches!(expr.kind, ast::ExprKind::Lit(_))
&& !expr.span.from_expansion()))
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1053,12 +1053,6 @@ impl<'tcx> TyCtxtAt<'tcx> {
name: Symbol,
def_kind: DefKind,
) -> TyCtxtFeed<'tcx, LocalDefId> {
// This function modifies `self.definitions` using a side-effect.
// We need to ensure that these side effects are re-run by the incr. comp. engine.
// Depending on the forever-red node will tell the graph that the calling query
// needs to be re-evaluated.
self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);

// The following call has the side effect of modifying the tables inside `definitions`.
// These very tables are relied on by the incr. comp. engine to decode DepNodes and to
// decode the on-disk cache.
Expand Down Expand Up @@ -1087,6 +1081,12 @@ impl<'tcx> TyCtxt<'tcx> {
let data = def_kind.def_path_data(name);
let def_id = self.untracked.definitions.write().create_def(parent, data);

// This function modifies `self.definitions` using a side-effect.
// We need to ensure that these side effects are re-run by the incr. comp. engine.
// Depending on the forever-red node will tell the graph that the calling query
// needs to be re-evaluated.
self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);

let feed = self.feed_local_def_id(def_id);
feed.def_kind(def_kind);
// Unique types created for closures participate in type privacy checking.
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2373,6 +2373,20 @@ impl<'tcx> Ty<'tcx> {
/// to represent the closure kind, because it has not yet been
/// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
/// is complete, that type variable will be unified.
///
/// To be noted that you can use [`ClosureArgs::kind()`] or [`CoroutineClosureArgs::kind()`]
/// to get the same information, which you can get by calling [`GenericArgs::as_closure()`]
/// or [`GenericArgs::as_coroutine_closure()`], depending on the type of the closure.
///
/// Otherwise, this method can be used as follows:
///
/// ```rust,ignore (snippet of compiler code)
/// let TyKind::Closure(def_id, [closure_fn_kind_ty, ..]) = closure_ty.kind()
/// && let Some(closure_kind) = closure_fn_kind_ty.expect_ty().to_opt_closure_kind()
/// {
/// // your code
/// }
/// ```
pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
match self.kind() {
Int(int_ty) => match int_ty {
Expand Down
62 changes: 39 additions & 23 deletions compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
return (err, Vec::new());
}

let (found, candidates) = self.try_lookup_name_relaxed(
let (found, mut candidates) = self.try_lookup_name_relaxed(
&mut err,
source,
path,
Expand All @@ -473,10 +473,12 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
return (err, candidates);
}

let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
if self.suggest_shadowed(&mut err, source, path, following_seg, span) {
// if there is already a shadowed name, don'suggest candidates for importing
candidates.clear();
}

// if we have suggested using pattern matching, then don't add needless suggestions
// for typos.
let mut fallback = self.suggest_trait_and_bounds(&mut err, source, res, span, &base_error);
fallback |= self.suggest_typo(&mut err, source, path, following_seg, span, &base_error);

if fallback {
Expand Down Expand Up @@ -872,25 +874,6 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
let ident_span = path.last().map_or(span, |ident| ident.ident.span);
let typo_sugg =
self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
let is_in_same_file = &|sp1, sp2| {
let source_map = self.r.tcx.sess.source_map();
let file1 = source_map.span_to_filename(sp1);
let file2 = source_map.span_to_filename(sp2);
file1 == file2
};
// print 'you might have meant' if the candidate is (1) is a shadowed name with
// accessible definition and (2) either defined in the same crate as the typo
// (could be in a different file) or introduced in the same file as the typo
// (could belong to a different crate)
if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
&& res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
{
err.span_label(
sugg_span,
format!("you might have meant to refer to this {}", res.descr()),
);
return true;
}
let mut fallback = false;
let typo_sugg = typo_sugg.to_opt_suggestion();
if !self.r.add_typo_suggestion(err, typo_sugg, ident_span) {
Expand Down Expand Up @@ -918,6 +901,39 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
fallback
}

fn suggest_shadowed(
&mut self,
err: &mut Diagnostic,
source: PathSource<'_>,
path: &[Segment],
following_seg: Option<&Segment>,
span: Span,
) -> bool {
let is_expected = &|res| source.is_expected(res);
let typo_sugg =
self.lookup_typo_candidate(path, following_seg, source.namespace(), is_expected);
let is_in_same_file = &|sp1, sp2| {
let source_map = self.r.tcx.sess.source_map();
let file1 = source_map.span_to_filename(sp1);
let file2 = source_map.span_to_filename(sp2);
file1 == file2
};
// print 'you might have meant' if the candidate is (1) is a shadowed name with
// accessible definition and (2) either defined in the same crate as the typo
// (could be in a different file) or introduced in the same file as the typo
// (could belong to a different crate)
if let TypoCandidate::Shadowed(res, Some(sugg_span)) = typo_sugg
&& res.opt_def_id().is_some_and(|id| id.is_local() || is_in_same_file(span, sugg_span))
{
err.span_label(
sugg_span,
format!("you might have meant to refer to this {}", res.descr()),
);
return true;
}
false
}

fn err_code_special_cases(
&mut self,
err: &mut Diagnostic,
Expand Down
19 changes: 15 additions & 4 deletions src/tools/rustfmt/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -537,18 +537,29 @@ impl Rewrite for ast::Lifetime {
impl Rewrite for ast::GenericBound {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
match *self {
ast::GenericBound::Trait(ref poly_trait_ref, modifiers) => {
ast::GenericBound::Trait(
ref poly_trait_ref,
ast::TraitBoundModifiers {
constness,
asyncness,
polarity,
},
) => {
let snippet = context.snippet(self.span());
let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
let mut constness = modifiers.constness.as_str().to_string();
let mut constness = constness.as_str().to_string();
if !constness.is_empty() {
constness.push(' ');
}
let polarity = modifiers.polarity.as_str();
let mut asyncness = asyncness.as_str().to_string();
if !asyncness.is_empty() {
asyncness.push(' ');
}
let polarity = polarity.as_str();
let shape = shape.offset_left(constness.len() + polarity.len())?;
poly_trait_ref
.rewrite(context, shape)
.map(|s| format!("{constness}{polarity}{s}"))
.map(|s| format!("{constness}{asyncness}{polarity}{s}"))
.map(|s| if has_paren { format!("({})", s) } else { s })
}
ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
Expand Down
3 changes: 3 additions & 0 deletions src/tools/rustfmt/tests/target/asyncness.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// rustfmt-edition: 2018

fn foo() -> impl async Fn() {}
2 changes: 1 addition & 1 deletion src/tools/tidy/src/ui_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use std::path::{Path, PathBuf};
// #73494.
const ENTRY_LIMIT: usize = 900;
// FIXME: The following limits should be reduced eventually.
const ISSUES_ENTRY_LIMIT: usize = 1794;
const ISSUES_ENTRY_LIMIT: usize = 1781;
const ROOT_ENTRY_LIMIT: usize = 870;

const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
16 changes: 16 additions & 0 deletions tests/ui/lint/issue-121070-let-range.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// check-pass

#![feature(let_chains)]
#![allow(irrefutable_let_patterns)]
fn main() {
let _a = 0..1;

if let x = (0..1) {
eprintln!("x: {:?}", x);
}
if let x = (0..1) &&
let _y = (0..2)
{
eprintln!("x: {:?}", x);
}
}
File renamed without changes.
5 changes: 5 additions & 0 deletions tests/ui/resolve/issue-120559.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use std::io::Read;

fn f<T: Read, U, Read>() {} //~ ERROR expected trait, found type parameter `Read`

fn main() {}
14 changes: 14 additions & 0 deletions tests/ui/resolve/issue-120559.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
error[E0404]: expected trait, found type parameter `Read`
--> $DIR/issue-120559.rs:3:9
|
LL | use std::io::Read;
| ---- you might have meant to refer to this trait
LL |
LL | fn f<T: Read, U, Read>() {}
| ^^^^ ---- found this type parameter
| |
| not a trait

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0404`.
5 changes: 0 additions & 5 deletions tests/ui/span/issue-35987.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ LL | impl<T: Clone, Add> Add for Foo<T> {
| --- ^^^ not a trait
| |
| found this type parameter
|
help: consider importing this trait instead
|
LL + use std::ops::Add;
|

error: aborting due to 1 previous error

Expand Down

0 comments on commit 502ce82

Please sign in to comment.