Skip to content

Rollup of 6 pull requests #107593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 14 commits into from
Closed
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion compiler/rustc_ast_pretty/src/pprust/state.rs
Original file line number Diff line number Diff line change
@@ -131,7 +131,7 @@ pub fn print_crate<'a>(

// Currently, in Rust 2018 we don't have `extern crate std;` at the crate
// root, so this is not needed, and actually breaks things.
if edition.rust_2015() {
if edition.is_rust_2015() {
// `#![no_std]`
let fake_attr = attr::mk_attr_word(g, ast::AttrStyle::Inner, sym::no_std, DUMMY_SP);
s.print_attribute(&fake_attr);
2 changes: 1 addition & 1 deletion compiler/rustc_error_messages/locales/en-US/borrowck.ftl
Original file line number Diff line number Diff line change
@@ -33,7 +33,7 @@ borrowck_var_here_defined = variable defined here

borrowck_var_here_captured = variable captured here

borrowck_closure_inferred_mut = inferred to be a `FnMut` closure
borrowck_closure_inferred_mut = inferred to be a `FnMut` closure

borrowck_returned_closure_escaped =
returns a closure that contains a reference to a captured variable, which then escapes the closure body
1 change: 1 addition & 0 deletions compiler/rustc_error_messages/locales/en-US/lint.ftl
Original file line number Diff line number Diff line change
@@ -309,6 +309,7 @@ lint_unused_generator =
.note = generators are lazy and do nothing unless resumed

lint_unused_def = unused {$pre}`{$def}`{$post} that must be used
.suggestion = use `let _ = ...` to ignore the resulting value

lint_path_statement_drop = path statement drops value
.suggestion = use `drop` to clarify the intent
4 changes: 2 additions & 2 deletions compiler/rustc_error_messages/locales/en-US/parse.ftl
Original file line number Diff line number Diff line change
@@ -535,8 +535,8 @@ parse_dot_dot_dot_range_to_pattern_not_allowed = range-to patterns with `...` ar

parse_enum_pattern_instead_of_identifier = expected identifier, found enum pattern

parse_dot_dot_dot_for_remaining_fields = expected field pattern, found `...`
.suggestion = to omit remaining fields, use one fewer `.`
parse_dot_dot_dot_for_remaining_fields = expected field pattern, found `{$token_str}`
.suggestion = to omit remaining fields, use `..`

parse_expected_comma_after_pattern_field = expected `,`

3 changes: 1 addition & 2 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
@@ -454,8 +454,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
None if let Some(e) = self.tainted_by_errors() => self.tcx.ty_error_with_guaranteed(e),
None => {
bug!(
"no type for node {}: {} in fcx {}",
id,
"no type for node {} in fcx {}",
self.tcx.hir().node_to_string(id),
self.tag()
);
3 changes: 1 addition & 2 deletions compiler/rustc_hir_typeck/src/mem_categorization.rs
Original file line number Diff line number Diff line change
@@ -155,8 +155,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
None if self.is_tainted_by_errors() => Err(()),
None => {
bug!(
"no type for node {}: {} in mem_categorization",
id,
"no type for node {} in mem_categorization",
self.tcx().hir().node_to_string(id)
);
}
18 changes: 18 additions & 0 deletions compiler/rustc_lint/src/lints.rs
Original file line number Diff line number Diff line change
@@ -1402,6 +1402,21 @@ pub struct UnusedDef<'a, 'b> {
pub cx: &'a LateContext<'b>,
pub def_id: DefId,
pub note: Option<Symbol>,
pub suggestion: Option<UnusedDefSuggestion>,
}

#[derive(Subdiagnostic)]
pub enum UnusedDefSuggestion {
#[suggestion(
suggestion,
style = "verbose",
code = "let _ = ",
applicability = "machine-applicable"
)]
Default {
#[primary_span]
span: Span,
},
}

// Needed because of def_path_str
@@ -1417,6 +1432,9 @@ impl<'a> DecorateLint<'a, ()> for UnusedDef<'_, '_> {
if let Some(note) = self.note {
diag.note(note.as_str());
}
if let Some(sugg) = self.suggestion {
diag.subdiagnostic(sugg);
}
diag
}

18 changes: 16 additions & 2 deletions compiler/rustc_lint/src/unused.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::lints::{
PathStatementDrop, PathStatementDropSub, PathStatementNoEffect, UnusedAllocationDiag,
UnusedAllocationMutDiag, UnusedClosure, UnusedDef, UnusedDelim, UnusedDelimSuggestion,
UnusedGenerator, UnusedImportBracesDiag, UnusedOp, UnusedResult,
UnusedAllocationMutDiag, UnusedClosure, UnusedDef, UnusedDefSuggestion, UnusedDelim,
UnusedDelimSuggestion, UnusedGenerator, UnusedImportBracesDiag, UnusedOp, UnusedResult,
};
use crate::Lint;
use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
@@ -418,6 +418,19 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
);
}
MustUsePath::Def(span, def_id, reason) => {
let suggestion = if matches!(
cx.tcx.get_diagnostic_name(*def_id),
Some(sym::add)
| Some(sym::sub)
| Some(sym::mul)
| Some(sym::div)
| Some(sym::rem)
| Some(sym::neg),
) {
Some(UnusedDefSuggestion::Default { span: span.shrink_to_lo() })
} else {
None
};
cx.emit_spanned_lint(
UNUSED_MUST_USE,
*span,
@@ -427,6 +440,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
cx,
def_id: *def_id,
note: *reason,
suggestion,
},
);
}
27 changes: 12 additions & 15 deletions compiler/rustc_middle/src/hir/map/mod.rs
Original file line number Diff line number Diff line change
@@ -290,7 +290,7 @@ impl<'hir> Map<'hir> {
#[track_caller]
pub fn parent_id(self, hir_id: HirId) -> HirId {
self.opt_parent_id(hir_id)
.unwrap_or_else(|| bug!("No parent for node {:?}", self.node_to_string(hir_id)))
.unwrap_or_else(|| bug!("No parent for node {}", self.node_to_string(hir_id)))
}

pub fn get_parent(self, hir_id: HirId) -> Node<'hir> {
@@ -1191,12 +1191,10 @@ fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> {
}

fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
let id_str = format!(" (hir_id={})", id);

let path_str = |def_id: LocalDefId| map.tcx.def_path_str(def_id.to_def_id());

let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default();
let node_str = |prefix| format!("{} {}{}", prefix, span_str(), id_str);
let node_str = |prefix| format!("{id} ({prefix} `{}`)", span_str());

match map.find(id) {
Some(Node::Item(item)) => {
@@ -1225,18 +1223,18 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
ItemKind::TraitAlias(..) => "trait alias",
ItemKind::Impl { .. } => "impl",
};
format!("{} {}{}", item_str, path_str(item.owner_id.def_id), id_str)
format!("{id} ({item_str} {})", path_str(item.owner_id.def_id))
}
Some(Node::ForeignItem(item)) => {
format!("foreign item {}{}", path_str(item.owner_id.def_id), id_str)
format!("{id} (foreign item {})", path_str(item.owner_id.def_id))
}
Some(Node::ImplItem(ii)) => {
let kind = match ii.kind {
ImplItemKind::Const(..) => "assoc const",
ImplItemKind::Fn(..) => "method",
ImplItemKind::Type(_) => "assoc type",
};
format!("{} {} in {}{}", kind, ii.ident, path_str(ii.owner_id.def_id), id_str)
format!("{id} ({kind} `{}` in {})", ii.ident, path_str(ii.owner_id.def_id))
}
Some(Node::TraitItem(ti)) => {
let kind = match ti.kind {
@@ -1245,13 +1243,13 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
TraitItemKind::Type(..) => "assoc type",
};

format!("{} {} in {}{}", kind, ti.ident, path_str(ti.owner_id.def_id), id_str)
format!("{id} ({kind} `{}` in {})", ti.ident, path_str(ti.owner_id.def_id))
}
Some(Node::Variant(ref variant)) => {
format!("variant {} in {}{}", variant.ident, path_str(variant.def_id), id_str)
format!("{id} (variant `{}` in {})", variant.ident, path_str(variant.def_id))
}
Some(Node::Field(ref field)) => {
format!("field {} in {}{}", field.ident, path_str(field.def_id), id_str)
format!("{id} (field `{}` in {})", field.ident, path_str(field.def_id))
}
Some(Node::AnonConst(_)) => node_str("const"),
Some(Node::Expr(_)) => node_str("expr"),
@@ -1269,16 +1267,15 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String {
Some(Node::Infer(_)) => node_str("infer"),
Some(Node::Local(_)) => node_str("local"),
Some(Node::Ctor(ctor)) => format!(
"ctor {}{}",
"{id} (ctor {})",
ctor.ctor_def_id().map_or("<missing path>".into(), |def_id| path_str(def_id)),
id_str
),
Some(Node::Lifetime(_)) => node_str("lifetime"),
Some(Node::GenericParam(ref param)) => {
format!("generic_param {}{}", path_str(param.def_id), id_str)
format!("{id} (generic_param {})", path_str(param.def_id))
}
Some(Node::Crate(..)) => String::from("root_crate"),
None => format!("unknown node{}", id_str),
Some(Node::Crate(..)) => String::from("(root_crate)"),
None => format!("{id} (unknown node)"),
}
}

2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
@@ -2171,7 +2171,7 @@ impl<'tcx> TyCtxt<'tcx> {
self.late_bound_vars_map(id.owner)
.and_then(|map| map.get(&id.local_id).cloned())
.unwrap_or_else(|| {
bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id)
bug!("No bound vars found for {}", self.hir().node_to_string(id))
})
.iter(),
)
5 changes: 2 additions & 3 deletions compiler/rustc_middle/src/ty/typeck_results.rs
Original file line number Diff line number Diff line change
@@ -372,7 +372,7 @@ impl<'tcx> TypeckResults<'tcx> {

pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> {
self.node_type_opt(id).unwrap_or_else(|| {
bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id)))
bug!("node_type: no type for node {}", tls::with(|tcx| tcx.hir().node_to_string(id)))
})
}

@@ -551,9 +551,8 @@ fn validate_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) {
fn invalid_hir_id_for_typeck_results(hir_owner: OwnerId, hir_id: hir::HirId) {
ty::tls::with(|tcx| {
bug!(
"node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}",
"node {} cannot be placed in TypeckResults with hir_owner {:?}",
tcx.hir().node_to_string(hir_id),
hir_id.owner,
hir_owner
)
});
5 changes: 4 additions & 1 deletion compiler/rustc_parse/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::borrow::Cow;

use rustc_ast::token::Token;
use rustc_ast::{Path, Visibility};
use rustc_errors::{fluent, AddToDiagnostic, Applicability, EmissionGuarantee, IntoDiagnostic};
@@ -1802,8 +1804,9 @@ pub(crate) struct EnumPatternInsteadOfIdentifier {
#[diag(parse_dot_dot_dot_for_remaining_fields)]
pub(crate) struct DotDotDotForRemainingFields {
#[primary_span]
#[suggestion(code = "..", applicability = "machine-applicable")]
#[suggestion(code = "..", style = "verbose", applicability = "machine-applicable")]
pub span: Span,
pub token_str: Cow<'static, str>,
}

#[derive(Diagnostic)]
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
@@ -2109,7 +2109,7 @@ impl<'a> Parser<'a> {
ClosureBinder::NotPresent
};

let constness = self.parse_constness(Case::Sensitive);
let constness = self.parse_closure_constness(Case::Sensitive);

let movability =
if self.eat_keyword(kw::Static) { Movability::Static } else { Movability::Movable };
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/item.rs
Original file line number Diff line number Diff line change
@@ -2247,7 +2247,7 @@ impl<'a> Parser<'a> {
let ext = self.parse_extern(case);

if let Async::Yes { span, .. } = asyncness {
if span.rust_2015() {
if span.is_rust_2015() {
self.sess.emit_err(AsyncFnIn2015 { span, help: HelpUseLatestEdition::new() });
}
}
21 changes: 16 additions & 5 deletions compiler/rustc_parse/src/parser/mod.rs
Original file line number Diff line number Diff line change
@@ -739,9 +739,10 @@ impl<'a> Parser<'a> {
fn check_const_closure(&self) -> bool {
self.is_keyword_ahead(0, &[kw::Const])
&& self.look_ahead(1, |t| match &t.kind {
token::Ident(kw::Move | kw::Static | kw::Async, _)
| token::OrOr
| token::BinOp(token::Or) => true,
// async closures do not work with const closures, so we do not parse that here.
token::Ident(kw::Move | kw::Static, _) | token::OrOr | token::BinOp(token::Or) => {
true
}
_ => false,
})
}
@@ -1203,8 +1204,18 @@ impl<'a> Parser<'a> {

/// Parses constness: `const` or nothing.
fn parse_constness(&mut self, case: Case) -> Const {
// Avoid const blocks to be parsed as const items
if self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
self.parse_constness_(case, false)
}

/// Parses constness for closures
fn parse_closure_constness(&mut self, case: Case) -> Const {
self.parse_constness_(case, true)
}

fn parse_constness_(&mut self, case: Case, is_closure: bool) -> Const {
// Avoid const blocks and const closures to be parsed as const items
if (self.check_const_closure() == is_closure)
&& self.look_ahead(1, |t| t != &token::OpenDelim(Delimiter::Brace))
&& self.eat_keyword_case(kw::Const, case)
{
Const::Yes(self.prev_token.uninterpolated_span())
18 changes: 11 additions & 7 deletions compiler/rustc_parse/src/parser/pat.rs
Original file line number Diff line number Diff line change
@@ -963,12 +963,15 @@ impl<'a> Parser<'a> {
}
ate_comma = false;

if self.check(&token::DotDot) || self.token == token::DotDotDot {
if self.check(&token::DotDot)
|| self.check_noexpect(&token::DotDotDot)
|| self.check_keyword(kw::Underscore)
{
etc = true;
let mut etc_sp = self.token.span;

self.recover_one_fewer_dotdot();
self.bump(); // `..` || `...`
self.recover_bad_dot_dot();
self.bump(); // `..` || `...` || `_`

if self.token == token::CloseDelim(Delimiter::Brace) {
etc_span = Some(etc_sp);
@@ -1061,14 +1064,15 @@ impl<'a> Parser<'a> {
Ok((fields, etc))
}

/// Recover on `...` as if it were `..` to avoid further errors.
/// Recover on `...` or `_` as if it were `..` to avoid further errors.
/// See issue #46718.
fn recover_one_fewer_dotdot(&self) {
if self.token != token::DotDotDot {
fn recover_bad_dot_dot(&self) {
if self.token == token::DotDot {
return;
}

self.sess.emit_err(DotDotDotForRemainingFields { span: self.token.span });
let token_str = pprust::token_to_string(&self.token);
self.sess.emit_err(DotDotDotForRemainingFields { span: self.token.span, token_str });
}

fn parse_pat_field(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, PatField> {
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/ty.rs
Original file line number Diff line number Diff line change
@@ -673,7 +673,7 @@ impl<'a> Parser<'a> {
/// Is a `dyn B0 + ... + Bn` type allowed here?
fn is_explicit_dyn_type(&mut self) -> bool {
self.check_keyword(kw::Dyn)
&& (!self.token.uninterpolated_span().rust_2015()
&& (self.token.uninterpolated_span().rust_2018()
|| self.look_ahead(1, |t| {
(t.can_begin_bound() || t.kind == TokenKind::BinOp(token::Star))
&& !can_continue_type_after_non_fn_ident(t)
Loading