Skip to content
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

Rollup of 6 pull requests #96502

Closed
wants to merge 23 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
54daf49
std: directly use pthread in UNIX parker implementation
joboet Apr 25, 2022
eb55cdc
use `ParseSess` instead of `Session` in `into_diagnostic`
pvdrz Apr 25, 2022
519dd8e
migrate ambiguous plus diagnostic
pvdrz Apr 25, 2022
d6da5fb
update lockfile
pvdrz Apr 25, 2022
5874b09
fix formatting
pvdrz Apr 25, 2022
530f4dc
remove old code
pvdrz Apr 25, 2022
2e261a8
add `struct_warn` method
pvdrz Apr 25, 2022
35b42cb
avoid `format!`
pvdrz Apr 26, 2022
6c3e793
move `AmbigousPlus` outside
pvdrz Apr 26, 2022
1e35bab
separate messages by a newline
pvdrz Apr 26, 2022
2a6a370
Add more diagnostic items
Serial-ATA Apr 26, 2022
a1e0cfa
Update ui test
Serial-ATA Apr 27, 2022
e7ae9eb
rename `sum_with_parens`
pvdrz Apr 27, 2022
332f326
Fixed grammatical error in example comment
user-simon Apr 27, 2022
2b71201
std: simplify UNIX parker timeouts
joboet Apr 27, 2022
2c94218
Recover suggestions to introduce named lifetime under NLL
marmeladema Apr 25, 2022
d9240d7
Ensure that `'_` and GAT yields errors
marmeladema Mar 25, 2022
a67b394
Rollup merge of #95312 - marmeladema:tests-for-issue-95305, r=jackh726
Dylan-DPC Apr 28, 2022
bccac01
Rollup merge of #96302 - Serial-ATA:more-diagnostic-items, r=manishearth
Dylan-DPC Apr 28, 2022
ef079b8
Rollup merge of #96393 - joboet:pthread_parker, r=thomcc
Dylan-DPC Apr 28, 2022
16d029b
Rollup merge of #96405 - pvdrz:ambiguous-plus-diagnostic, r=davidtwco
Dylan-DPC Apr 28, 2022
021a4ff
Rollup merge of #96409 - marmeladema:fix-nll-introduce-named-lifetime…
Dylan-DPC Apr 28, 2022
439d24e
Rollup merge of #96480 - user-simon:patch-1, r=Dylan-DPC
Dylan-DPC Apr 28, 2022
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 Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4149,6 +4149,7 @@ dependencies = [
"rustc_errors",
"rustc_feature",
"rustc_lexer",
"rustc_macros",
"rustc_session",
"rustc_span",
"tracing",
Expand Down
35 changes: 34 additions & 1 deletion compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

use rustc_errors::{Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
use rustc_infer::infer::{
error_reporting::nice_region_error::{self, find_param_with_region, NiceRegionError},
error_reporting::nice_region_error::{
self, find_anon_type, find_param_with_region, suggest_adding_lifetime_params,
NiceRegionError,
},
error_reporting::unexpected_hidden_region_diagnostic,
NllRegionVariableOrigin, RelateParamBound,
};
Expand Down Expand Up @@ -630,6 +633,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
}

self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
self.suggest_adding_lifetime_params(&mut diag, *fr, *outlived_fr);

diag
}
Expand Down Expand Up @@ -694,4 +698,33 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
);
}
}

fn suggest_adding_lifetime_params(
&self,
diag: &mut Diagnostic,
sub: RegionVid,
sup: RegionVid,
) {
let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else {
return
};

let Some((ty_sub, _)) = self
.infcx
.tcx
.is_suitable_region(sub)
.and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else {
return
};

let Some((ty_sup, _)) = self
.infcx
.tcx
.is_suitable_region(sup)
.and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else {
return
};

suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag);
}
}
4 changes: 4 additions & 0 deletions compiler/rustc_error_messages/locales/en-US/parser.ftl
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
parser-struct-literal-body-without-path =
struct literal body without path
.suggestion = you might have forgotten to add the struct literal inside the block

parser-maybe-report-ambiguous-plus =
ambiguous `+` in a type
.suggestion = use parentheses to disambiguate
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::infer::error_reporting::nice_region_error::util::AnonymousParamInfo;
use crate::infer::error_reporting::nice_region_error::NiceRegionError;
use crate::infer::lexical_region_resolve::RegionResolutionError;
use crate::infer::SubregionOrigin;
use crate::infer::TyCtxt;

use rustc_errors::{struct_span_err, Applicability, Diagnostic, ErrorGuaranteed};
use rustc_hir as hir;
Expand Down Expand Up @@ -145,84 +146,83 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
}
}

self.suggest_adding_lifetime_params(sub, ty_sup, ty_sub, &mut err);
if suggest_adding_lifetime_params(self.tcx(), sub, ty_sup, ty_sub, &mut err) {
err.note("each elided lifetime in input position becomes a distinct lifetime");
}

let reported = err.emit();
Some(reported)
}
}

fn suggest_adding_lifetime_params(
&self,
sub: Region<'tcx>,
ty_sup: &Ty<'_>,
ty_sub: &Ty<'_>,
err: &mut Diagnostic,
) {
if let (
hir::Ty { kind: hir::TyKind::Rptr(lifetime_sub, _), .. },
hir::Ty { kind: hir::TyKind::Rptr(lifetime_sup, _), .. },
) = (ty_sub, ty_sup)
{
if lifetime_sub.name.is_elided() && lifetime_sup.name.is_elided() {
if let Some(anon_reg) = self.tcx().is_suitable_region(sub) {
let hir_id = self.tcx().hir().local_def_id_to_hir_id(anon_reg.def_id);

let node = self.tcx().hir().get(hir_id);
let is_impl = matches!(&node, hir::Node::ImplItem(_));
let generics = match node {
hir::Node::Item(&hir::Item {
kind: hir::ItemKind::Fn(_, ref generics, ..),
..
})
| hir::Node::TraitItem(&hir::TraitItem { ref generics, .. })
| hir::Node::ImplItem(&hir::ImplItem { ref generics, .. }) => generics,
_ => return,
};

let (suggestion_param_name, introduce_new) = generics
.params
.iter()
.find(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }))
.and_then(|p| self.tcx().sess.source_map().span_to_snippet(p.span).ok())
.map(|name| (name, false))
.unwrap_or_else(|| ("'a".to_string(), true));

let mut suggestions = vec![
if let hir::LifetimeName::Underscore = lifetime_sub.name {
(lifetime_sub.span, suggestion_param_name.clone())
} else {
(lifetime_sub.span.shrink_to_hi(), suggestion_param_name.clone() + " ")
},
if let hir::LifetimeName::Underscore = lifetime_sup.name {
(lifetime_sup.span, suggestion_param_name.clone())
} else {
(lifetime_sup.span.shrink_to_hi(), suggestion_param_name.clone() + " ")
},
];

if introduce_new {
let new_param_suggestion = match &generics.params {
[] => (generics.span, format!("<{}>", suggestion_param_name)),
[first, ..] => {
(first.span.shrink_to_lo(), format!("{}, ", suggestion_param_name))
}
};

suggestions.push(new_param_suggestion);
}

let mut sugg = String::from("consider introducing a named lifetime parameter");
if is_impl {
sugg.push_str(" and update trait if needed");
}
err.multipart_suggestion(
sugg.as_str(),
suggestions,
Applicability::MaybeIncorrect,
);
err.note("each elided lifetime in input position becomes a distinct lifetime");
}
}
}
pub fn suggest_adding_lifetime_params<'tcx>(
tcx: TyCtxt<'tcx>,
sub: Region<'tcx>,
ty_sup: &Ty<'_>,
ty_sub: &Ty<'_>,
err: &mut Diagnostic,
) -> bool {
let (
hir::Ty { kind: hir::TyKind::Rptr(lifetime_sub, _), .. },
hir::Ty { kind: hir::TyKind::Rptr(lifetime_sup, _), .. },
) = (ty_sub, ty_sup) else {
return false;
};

if !lifetime_sub.name.is_elided() || !lifetime_sup.name.is_elided() {
return false;
};

let Some(anon_reg) = tcx.is_suitable_region(sub) else {
return false;
};

let hir_id = tcx.hir().local_def_id_to_hir_id(anon_reg.def_id);

let node = tcx.hir().get(hir_id);
let is_impl = matches!(&node, hir::Node::ImplItem(_));
let generics = match node {
hir::Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, ref generics, ..), .. })
| hir::Node::TraitItem(&hir::TraitItem { ref generics, .. })
| hir::Node::ImplItem(&hir::ImplItem { ref generics, .. }) => generics,
_ => return false,
};

let (suggestion_param_name, introduce_new) = generics
.params
.iter()
.find(|p| matches!(p.kind, GenericParamKind::Lifetime { .. }))
.and_then(|p| tcx.sess.source_map().span_to_snippet(p.span).ok())
.map(|name| (name, false))
.unwrap_or_else(|| ("'a".to_string(), true));

let mut suggestions = vec![
if let hir::LifetimeName::Underscore = lifetime_sub.name {
(lifetime_sub.span, suggestion_param_name.clone())
} else {
(lifetime_sub.span.shrink_to_hi(), suggestion_param_name.clone() + " ")
},
if let hir::LifetimeName::Underscore = lifetime_sup.name {
(lifetime_sup.span, suggestion_param_name.clone())
} else {
(lifetime_sup.span.shrink_to_hi(), suggestion_param_name.clone() + " ")
},
];

if introduce_new {
let new_param_suggestion = match &generics.params {
[] => (generics.span, format!("<{}>", suggestion_param_name)),
[first, ..] => (first.span.shrink_to_lo(), format!("{}, ", suggestion_param_name)),
};

suggestions.push(new_param_suggestion);
}

let mut sugg = String::from("consider introducing a named lifetime parameter");
if is_impl {
sugg.push_str(" and update trait if needed");
}
err.multipart_suggestion(sugg.as_str(), suggestions, Applicability::MaybeIncorrect);

true
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use rustc_middle::ty::{self, Region, TyCtxt};
/// ```
/// The function returns the nested type corresponding to the anonymous region
/// for e.g., `&u8` and `Vec<&u8>`.
pub(crate) fn find_anon_type<'tcx>(
pub fn find_anon_type<'tcx>(
tcx: TyCtxt<'tcx>,
region: Region<'tcx>,
br: &ty::BoundRegionKind,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ mod static_impl_trait;
mod trait_impl_difference;
mod util;

pub use different_lifetimes::suggest_adding_lifetime_params;
pub use find_anon_type::find_anon_type;
pub use static_impl_trait::suggest_new_region_bound;
pub use util::find_param_with_region;

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_macros/src/session_diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ impl<'a> SessionDiagnosticDerive<'a> {
{
fn into_diagnostic(
self,
#sess: &'__session_diagnostic_sess rustc_session::Session
#sess: &'__session_diagnostic_sess rustc_session::parse::ParseSess
) -> rustc_errors::DiagnosticBuilder<'__session_diagnostic_sess, #param_ty> {
use rustc_errors::IntoDiagnosticArg;
#implementation
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_parse/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ rustc_ast_pretty = { path = "../rustc_ast_pretty" }
rustc_data_structures = { path = "../rustc_data_structures" }
rustc_feature = { path = "../rustc_feature" }
rustc_lexer = { path = "../rustc_lexer" }
rustc_macros = { path = "../rustc_macros" }
rustc_errors = { path = "../rustc_errors" }
rustc_session = { path = "../rustc_session" }
rustc_span = { path = "../rustc_span" }
Expand Down
21 changes: 12 additions & 9 deletions compiler/rustc_parse/src/parser/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use rustc_errors::{pluralize, struct_span_err, Diagnostic, EmissionGuarantee, Er
use rustc_errors::{
Applicability, DiagnosticBuilder, DiagnosticMessage, Handler, MultiSpan, PResult,
};
use rustc_macros::SessionDiagnostic;
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, Ident};
use rustc_span::{Span, SpanSnippetError, DUMMY_SP};
Expand Down Expand Up @@ -241,6 +242,16 @@ impl MultiSugg {
err.multipart_suggestions(msg, suggestions.map(|s| s.patches), applicability);
}
}

#[derive(SessionDiagnostic)]
#[error(slug = "parser-maybe-report-ambiguous-plus")]
struct AmbiguousPlus {
pub sum_ty: String,
#[primary_span]
#[suggestion(code = "({sum_ty})")]
pub span: Span,
}

// SnapshotParser is used to create a snapshot of the parser
// without causing duplicate errors being emitted when the `Parser`
// is dropped.
Expand Down Expand Up @@ -1196,15 +1207,7 @@ impl<'a> Parser<'a> {
ty: &Ty,
) {
if matches!(allow_plus, AllowPlus::No) && impl_dyn_multi {
let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
self.struct_span_err(ty.span, "ambiguous `+` in a type")
.span_suggestion(
ty.span,
"use parentheses to disambiguate",
sum_with_parens,
Applicability::MachineApplicable,
)
.emit();
self.sess.emit_err(AmbiguousPlus { sum_ty: pprust::ty_to_string(&ty), span: ty.span });
}
}

Expand Down
22 changes: 21 additions & 1 deletion compiler/rustc_session/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@

use crate::config::CheckCfg;
use crate::lint::{BufferedEarlyLint, BuiltinLintDiagnostics, Lint, LintId};
use crate::SessionDiagnostic;
use rustc_ast::node_id::NodeId;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::sync::{Lock, Lrc};
use rustc_errors::{emitter::SilentEmitter, ColorConfig, Handler};
use rustc_errors::{
error_code, fallback_fluent_bundle, Applicability, Diagnostic, DiagnosticBuilder,
ErrorGuaranteed, MultiSpan,
DiagnosticMessage, ErrorGuaranteed, MultiSpan,
};
use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures};
use rustc_span::edition::Edition;
Expand Down Expand Up @@ -287,4 +288,23 @@ impl ParseSess {
pub fn proc_macro_quoted_spans(&self) -> Vec<Span> {
self.proc_macro_quoted_spans.lock().clone()
}

pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
err.into_diagnostic(self).emit()
}

pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
warning.into_diagnostic(self).emit()
}

pub fn struct_err(
&self,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
self.span_diagnostic.struct_err(msg)
}

pub fn struct_warn(&self, msg: impl Into<DiagnosticMessage>) -> DiagnosticBuilder<'_, ()> {
self.span_diagnostic.struct_warn(msg)
}
}
8 changes: 4 additions & 4 deletions compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ pub struct PerfStats {
pub trait SessionDiagnostic<'a, T: EmissionGuarantee = ErrorGuaranteed> {
/// Write out as a diagnostic out of `sess`.
#[must_use]
fn into_diagnostic(self, sess: &'a Session) -> DiagnosticBuilder<'a, T>;
fn into_diagnostic(self, sess: &'a ParseSess) -> DiagnosticBuilder<'a, T>;
}

impl Session {
Expand Down Expand Up @@ -334,7 +334,7 @@ impl Session {
&self,
msg: impl Into<DiagnosticMessage>,
) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
self.diagnostic().struct_err(msg)
self.parse_sess.struct_err(msg)
}
pub fn struct_err_with_code(
&self,
Expand Down Expand Up @@ -414,10 +414,10 @@ impl Session {
self.diagnostic().err(msg)
}
pub fn emit_err<'a>(&'a self, err: impl SessionDiagnostic<'a>) -> ErrorGuaranteed {
err.into_diagnostic(self).emit()
self.parse_sess.emit_err(err)
}
pub fn emit_warning<'a>(&'a self, warning: impl SessionDiagnostic<'a, ()>) {
warning.into_diagnostic(self).emit()
self.parse_sess.emit_warning(warning)
}
#[inline]
pub fn err_count(&self) -> usize {
Expand Down
2 changes: 2 additions & 0 deletions library/core/src/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod nofloat;
mod num;

#[stable(feature = "fmt_flags_align", since = "1.28.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")]
/// Possible alignments returned by `Formatter::align`
#[derive(Debug)]
pub enum Alignment {
Expand Down Expand Up @@ -462,6 +463,7 @@ impl<'a> Arguments<'a> {
///
/// [`format()`]: ../../std/fmt/fn.format.html
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Arguments")]
#[derive(Copy, Clone)]
pub struct Arguments<'a> {
// Format string pieces to print.
Expand Down
Loading