use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_infer::infer::{
error_reporting::nice_region_error::NiceRegionError,
error_reporting::unexpected_hidden_region_diagnostic, NLLRegionVariableOrigin,
};
use rustc_middle::mir::{ConstraintCategory, ReturnConstraint};
use rustc_middle::ty::subst::Subst;
use rustc_middle::ty::{self, RegionVid, Ty};
use rustc_span::symbol::{kw, sym};
use rustc_span::Span;
use crate::util::borrowck_errors;
use crate::borrow_check::{
nll::ConstraintDescription,
region_infer::{values::RegionElement, TypeTest},
universal_regions::DefiningTy,
MirBorrowckCtxt,
};
use super::{OutlivesSuggestionBuilder, RegionName};
impl ConstraintDescription for ConstraintCategory {
fn description(&self) -> &'static str {
match self {
ConstraintCategory::Assignment => "assignment ",
ConstraintCategory::Return(_) => "returning this value ",
ConstraintCategory::Yield => "yielding this value ",
ConstraintCategory::UseAsConst => "using this value as a constant ",
ConstraintCategory::UseAsStatic => "using this value as a static ",
ConstraintCategory::Cast => "cast ",
ConstraintCategory::CallArgument => "argument ",
ConstraintCategory::TypeAnnotation => "type annotation ",
ConstraintCategory::ClosureBounds => "closure body ",
ConstraintCategory::SizedBound => "proving this value is `Sized` ",
ConstraintCategory::CopyBound => "copying this value ",
ConstraintCategory::OpaqueType => "opaque type ",
ConstraintCategory::ClosureUpvar(_) => "closure capture ",
ConstraintCategory::Boring
| ConstraintCategory::BoringNoLocation
| ConstraintCategory::Internal => "",
}
}
}
crate type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
#[derive(Clone, Debug)]
crate enum RegionErrorKind<'tcx> {
TypeTestError { type_test: TypeTest<'tcx> },
UnexpectedHiddenRegion {
span: Span,
hidden_ty: Ty<'tcx>,
member_region: ty::Region<'tcx>,
},
BoundUniversalRegionError {
longer_fr: RegionVid,
error_element: RegionElement,
fr_origin: NLLRegionVariableOrigin,
},
RegionError {
fr_origin: NLLRegionVariableOrigin,
longer_fr: RegionVid,
shorter_fr: RegionVid,
is_reported: bool,
},
}
#[derive(Clone, Debug)]
pub struct ErrorConstraintInfo {
pub(super) fr: RegionVid,
pub(super) fr_is_local: bool,
pub(super) outlived_fr: RegionVid,
pub(super) outlived_fr_is_local: bool,
pub(super) category: ConstraintCategory,
pub(super) span: Span,
}
impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
}
pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
if self.regioncx.universal_regions().is_universal_region(r) {
Some(r)
} else {
let upper_bound = self.regioncx.approx_universal_upper_bound(r);
if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
self.to_error_region_vid(upper_bound)
} else {
None
}
}
}
fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
if let Some(ty::ReFree(free_region)) = self.to_error_region(fr) {
if let ty::BoundRegion::BrEnv = free_region.bound_region {
if let DefiningTy::Closure(_, substs) =
self.regioncx.universal_regions().defining_ty
{
return substs.as_closure().kind() == ty::ClosureKind::FnMut;
}
}
}
false
}
pub(in crate::borrow_check) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
for nll_error in nll_errors.into_iter() {
match nll_error {
RegionErrorKind::TypeTestError { type_test } => {
let lower_bound_region = self.to_error_region(type_test.lower_bound);
let type_test_span = type_test.locations.span(&self.body);
if let Some(lower_bound_region) = lower_bound_region {
self.infcx
.construct_generic_bound_failure(
type_test_span,
None,
type_test.generic_kind,
lower_bound_region,
)
.buffer(&mut self.errors_buffer);
} else {
self.infcx
.tcx
.sess
.struct_span_err(
type_test_span,
&format!("`{}` does not live long enough", type_test.generic_kind),
)
.buffer(&mut self.errors_buffer);
}
}
RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
unexpected_hidden_region_diagnostic(
self.infcx.tcx,
span,
named_ty,
named_region,
)
.buffer(&mut self.errors_buffer);
}
RegionErrorKind::BoundUniversalRegionError {
longer_fr,
fr_origin,
error_element,
} => {
let error_region = self.regioncx.region_from_element(longer_fr, error_element);
let (_, span) = self.regioncx.find_outlives_blame_span(
&self.body,
longer_fr,
fr_origin,
error_region,
);
self.infcx
.tcx
.sess
.struct_span_err(span, "higher-ranked subtype error")
.buffer(&mut self.errors_buffer);
}
RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
if is_reported {
self.report_region_error(
longer_fr,
fr_origin,
shorter_fr,
&mut outlives_suggestion,
);
} else {
debug!(
"Unreported region error: can't prove that {:?}: {:?}",
longer_fr, shorter_fr
);
}
}
}
}
outlives_suggestion.add_suggestion(self);
}
pub(in crate::borrow_check) fn report_region_error(
&mut self,
fr: RegionVid,
fr_origin: NLLRegionVariableOrigin,
outlived_fr: RegionVid,
outlives_suggestion: &mut OutlivesSuggestionBuilder,
) {
debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
let (category, _, span) =
self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
self.regioncx.provides_universal_region(r, fr, outlived_fr)
});
debug!("report_region_error: category={:?} {:?}", category, span);
if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
let nice = NiceRegionError::new_from_span(self.infcx, span, o, f);
if let Some(diag) = nice.try_report_from_nll() {
diag.buffer(&mut self.errors_buffer);
return;
}
}
let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
self.regioncx.universal_regions().is_local_free_region(fr),
self.regioncx.universal_regions().is_local_free_region(outlived_fr),
);
debug!(
"report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
fr_is_local, outlived_fr_is_local, category
);
let errci = ErrorConstraintInfo {
fr,
outlived_fr,
fr_is_local,
outlived_fr_is_local,
category,
span,
};
let diag = match (category, fr_is_local, outlived_fr_is_local) {
(ConstraintCategory::Return(kind), true, false) if self.is_closure_fn_mut(fr) => {
self.report_fnmut_error(&errci, kind)
}
(ConstraintCategory::Assignment, true, false)
| (ConstraintCategory::CallArgument, true, false) => {
let mut db = self.report_escaping_data_error(&errci);
outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
outlives_suggestion.collect_constraint(fr, outlived_fr);
db
}
_ => {
let mut db = self.report_general_error(&errci);
outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
outlives_suggestion.collect_constraint(fr, outlived_fr);
db
}
};
diag.buffer(&mut self.errors_buffer);
}
fn report_fnmut_error(
&self,
errci: &ErrorConstraintInfo,
kind: ReturnConstraint,
) -> DiagnosticBuilder<'tcx> {
let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
let mut diag = self
.infcx
.tcx
.sess
.struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty;
if let ty::Opaque(def_id, _) = *output_ty.kind() {
output_ty = self.infcx.tcx.type_of(def_id)
};
debug!("report_fnmut_error: output_ty={:?}", output_ty);
let message = match output_ty.kind() {
ty::Closure(_, _) => {
"returns a closure that contains a reference to a captured variable, which then \
escapes the closure body"
}
ty::Adt(def, _) if self.infcx.tcx.is_diagnostic_item(sym::gen_future, def.did) => {
"returns an `async` block that contains a reference to a captured variable, which then \
escapes the closure body"
}
_ => "returns a reference to a captured variable which escapes the closure body",
};
diag.span_label(*span, message);
if let ReturnConstraint::ClosureUpvar(upvar) = kind {
let def_id = match self.regioncx.universal_regions().defining_ty {
DefiningTy::Closure(def_id, _) => def_id,
ty => bug!("unexpected DefiningTy {:?}", ty),
};
let upvar_def_span = self.infcx.tcx.hir().span(upvar);
let upvar_span = self.infcx.tcx.upvars_mentioned(def_id).unwrap()[&upvar].span;
diag.span_label(upvar_def_span, "variable defined here");
diag.span_label(upvar_span, "variable captured here");
}
if let Some(fr_span) = self.give_region_a_name(*outlived_fr).unwrap().span() {
diag.span_label(fr_span, "inferred to be a `FnMut` closure");
}
diag.note(
"`FnMut` closures only have access to their captured variables while they are \
executing...",
);
diag.note("...therefore, they cannot allow references to captured variables to escape");
diag
}
fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
let ErrorConstraintInfo { span, category, .. } = errci;
let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
self.infcx.tcx,
&self.body,
&self.local_names,
&self.upvars,
errci.fr,
);
let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
self.infcx.tcx,
&self.body,
&self.local_names,
&self.upvars,
errci.outlived_fr,
);
let (_, escapes_from) = self
.infcx
.tcx
.article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
|| (*category == ConstraintCategory::Assignment
&& self.regioncx.universal_regions().defining_ty.is_fn_def())
|| self.regioncx.universal_regions().defining_ty.is_const()
{
return self.report_general_error(&ErrorConstraintInfo {
fr_is_local: true,
outlived_fr_is_local: false,
..*errci
});
}
let mut diag =
borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
diag.span_label(
outlived_fr_span,
format!(
"`{}` declared here, outside of the {} body",
outlived_fr_name, escapes_from
),
);
}
if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
diag.span_label(
fr_span,
format!(
"`{}` is a reference that is only valid in the {} body",
fr_name, escapes_from
),
);
diag.span_label(*span, format!("`{}` escapes the {} body here", fr_name, escapes_from));
}
diag
}
fn report_general_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
let ErrorConstraintInfo {
fr,
fr_is_local,
outlived_fr,
outlived_fr_is_local,
span,
category,
..
} = errci;
let mut diag =
self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
let (_, mir_def_name) =
self.infcx.tcx.article_and_description(self.mir_def_id().to_def_id());
let fr_name = self.give_region_a_name(*fr).unwrap();
fr_name.highlight_region_name(&mut diag);
let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
outlived_fr_name.highlight_region_name(&mut diag);
match (category, outlived_fr_is_local, fr_is_local) {
(ConstraintCategory::Return(_), true, _) => {
diag.span_label(
*span,
format!(
"{} was supposed to return data with lifetime `{}` but it is returning \
data with lifetime `{}`",
mir_def_name, outlived_fr_name, fr_name
),
);
}
_ => {
diag.span_label(
*span,
format!(
"{}requires that `{}` must outlive `{}`",
category.description(),
fr_name,
outlived_fr_name,
),
);
}
}
self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
diag
}
fn add_static_impl_trait_suggestion(
&self,
diag: &mut DiagnosticBuilder<'tcx>,
fr: RegionVid,
fr_name: RegionName,
outlived_fr: RegionVid,
) {
if let (Some(f), Some(ty::RegionKind::ReStatic)) =
(self.to_error_region(fr), self.to_error_region(outlived_fr))
{
if let Some(&ty::Opaque(did, substs)) = self
.infcx
.tcx
.is_suitable_region(f)
.map(|r| r.def_id)
.and_then(|id| self.infcx.tcx.return_type_impl_trait(id))
.map(|(ty, _)| ty.kind())
{
let has_static_predicate = {
let bounds = self.infcx.tcx.explicit_item_bounds(did);
let mut found = false;
for (bound, _) in bounds {
if let ty::PredicateAtom::TypeOutlives(ty::OutlivesPredicate(_, r)) =
bound.skip_binders()
{
let r = r.subst(self.infcx.tcx, substs);
if let ty::RegionKind::ReStatic = r {
found = true;
break;
} else {
return;
}
}
}
found
};
debug!(
"add_static_impl_trait_suggestion: has_static_predicate={:?}",
has_static_predicate
);
let static_str = kw::StaticLifetime;
if has_static_predicate {
diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
} else {
let span = self.infcx.tcx.def_span(did);
if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
let suggestable_fr_name = if fr_name.was_named() {
fr_name.to_string()
} else {
"'_".to_string()
};
let suggestion = if snippet.ends_with(';') {
format!("{} + {};", &snippet[..snippet.len() - 1], suggestable_fr_name)
} else {
format!("{} + {}", snippet, suggestable_fr_name)
};
diag.span_suggestion(
span,
&format!(
"to allow this `impl Trait` to capture borrowed data with lifetime \
`{}`, add `{}` as a bound",
fr_name, suggestable_fr_name,
),
suggestion,
Applicability::MachineApplicable,
);
}
}
}
}
}
}