Skip to content

Commit 0c15adc

Browse files
committed
Auto merge of #67742 - mark-i-m:describe-it, r=matthewjasper
Generalized article_and_description r? @matthewjasper The logic of finding the right word and article to print seems to be repeated elsewhere... this is an experimental method to unify this logic...
2 parents abc3073 + 9434d6b commit 0c15adc

32 files changed

+169
-125
lines changed

src/librustc/query/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,9 @@ rustc_queries! {
308308
/// Returns `Some(mutability)` if the node pointed to by `def_id` is a static item.
309309
query static_mutability(_: DefId) -> Option<hir::Mutability> {}
310310

311+
/// Returns `Some(generator_kind)` if the node pointed to by `def_id` is a generator.
312+
query generator_kind(_: DefId) -> Option<hir::GeneratorKind> {}
313+
311314
/// Gets a map with the variance of every item; use `item_variance` instead.
312315
query crate_variances(_: CrateNum) -> &'tcx ty::CrateVariancesMap<'tcx> {
313316
desc { "computing the variances for items in this crate" }

src/librustc/ty/context.rs

+20-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::dep_graph::DepGraph;
55
use crate::dep_graph::{self, DepConstructor};
66
use crate::hir::exports::Export;
77
use crate::hir::map as hir_map;
8-
use crate::hir::map::DefPathHash;
8+
use crate::hir::map::{DefPathData, DefPathHash};
99
use crate::ich::{NodeIdHashingMode, StableHashingContext};
1010
use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
1111
use crate::lint::{struct_lint_level, LintSource};
@@ -209,7 +209,7 @@ fn validate_hir_id_for_typeck_tables(
209209
ty::tls::with(|tcx| {
210210
bug!(
211211
"node {} with HirId::owner {:?} cannot be placed in \
212-
TypeckTables with local_id_root {:?}",
212+
TypeckTables with local_id_root {:?}",
213213
tcx.hir().node_to_string(hir_id),
214214
DefId::local(hir_id.owner),
215215
local_id_root
@@ -1512,6 +1512,24 @@ impl<'tcx> TyCtxt<'tcx> {
15121512
.subst(*self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
15131513
)
15141514
}
1515+
1516+
/// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
1517+
pub fn article_and_description(&self, def_id: DefId) -> (&'static str, &'static str) {
1518+
match self.def_key(def_id).disambiguated_data.data {
1519+
DefPathData::TypeNs(..) | DefPathData::ValueNs(..) | DefPathData::MacroNs(..) => {
1520+
let kind = self.def_kind(def_id).unwrap();
1521+
(kind.article(), kind.descr(def_id))
1522+
}
1523+
DefPathData::ClosureExpr => match self.generator_kind(def_id) {
1524+
None => ("a", "closure"),
1525+
Some(rustc_hir::GeneratorKind::Async(..)) => ("an", "async closure"),
1526+
Some(rustc_hir::GeneratorKind::Gen) => ("a", "generator"),
1527+
},
1528+
DefPathData::LifetimeNs(..) => ("a", "lifetime"),
1529+
DefPathData::Impl => ("an", "implementation"),
1530+
_ => bug!("article_and_description called on def_id {:?}", def_id),
1531+
}
1532+
}
15151533
}
15161534

15171535
impl<'tcx> GlobalCtxt<'tcx> {

src/librustc_metadata/rmeta/decoder.rs

+13-6
Original file line numberDiff line numberDiff line change
@@ -492,7 +492,7 @@ impl MetadataBlob {
492492
}
493493
}
494494

495-
impl<'tcx> EntryKind<'tcx> {
495+
impl EntryKind {
496496
fn def_kind(&self) -> Option<DefKind> {
497497
Some(match *self {
498498
EntryKind::Const(..) => DefKind::Const,
@@ -606,11 +606,11 @@ impl<'a, 'tcx> CrateMetadata {
606606
self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
607607
}
608608

609-
fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind<'tcx>> {
609+
fn maybe_kind(&self, item_id: DefIndex) -> Option<EntryKind> {
610610
self.root.per_def.kind.get(self, item_id).map(|k| k.decode(self))
611611
}
612612

613-
fn kind(&self, item_id: DefIndex) -> EntryKind<'tcx> {
613+
fn kind(&self, item_id: DefIndex) -> EntryKind {
614614
assert!(!self.is_proc_macro(item_id));
615615
self.maybe_kind(item_id).unwrap_or_else(|| {
616616
bug!(
@@ -715,7 +715,7 @@ impl<'a, 'tcx> CrateMetadata {
715715
fn get_variant(
716716
&self,
717717
tcx: TyCtxt<'tcx>,
718-
kind: &EntryKind<'_>,
718+
kind: &EntryKind,
719719
index: DefIndex,
720720
parent_did: DefId,
721721
) -> ty::VariantDef {
@@ -1382,6 +1382,13 @@ impl<'a, 'tcx> CrateMetadata {
13821382
}
13831383
}
13841384

1385+
fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
1386+
match self.kind(id) {
1387+
EntryKind::Generator(data) => Some(data),
1388+
_ => None,
1389+
}
1390+
}
1391+
13851392
fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
13861393
self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
13871394
}
@@ -1491,8 +1498,8 @@ impl<'a, 'tcx> CrateMetadata {
14911498
);
14921499
debug!(
14931500
"CrateMetaData::imported_source_files alloc \
1494-
source_file {:?} original (start_pos {:?} end_pos {:?}) \
1495-
translated (start_pos {:?} end_pos {:?})",
1501+
source_file {:?} original (start_pos {:?} end_pos {:?}) \
1502+
translated (start_pos {:?} end_pos {:?})",
14961503
local_version.name,
14971504
start_pos,
14981505
end_pos,

src/librustc_metadata/rmeta/decoder/cstore_impl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
134134
asyncness => { cdata.asyncness(def_id.index) }
135135
is_foreign_item => { cdata.is_foreign_item(def_id.index) }
136136
static_mutability => { cdata.static_mutability(def_id.index) }
137+
generator_kind => { cdata.generator_kind(def_id.index) }
137138
def_kind => { cdata.def_kind(def_id.index) }
138139
def_span => { cdata.get_span(def_id.index, &tcx.sess) }
139140
lookup_stability => {

src/librustc_metadata/rmeta/encoder.rs

+5-13
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ impl<'tcx> EncodeContext<'tcx> {
306306
assert!(
307307
last_min_end <= lazy.position,
308308
"make sure that the calls to `lazy*` \
309-
are in the same order as the metadata fields",
309+
are in the same order as the metadata fields",
310310
);
311311
lazy.position.get() - last_min_end.get()
312312
}
@@ -1248,12 +1248,7 @@ impl EncodeContext<'tcx> {
12481248
self.encode_deprecation(def_id);
12491249
}
12501250

1251-
fn encode_info_for_generic_param(
1252-
&mut self,
1253-
def_id: DefId,
1254-
kind: EntryKind<'tcx>,
1255-
encode_type: bool,
1256-
) {
1251+
fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
12571252
record!(self.per_def.kind[def_id] <- kind);
12581253
record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
12591254
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
@@ -1271,12 +1266,9 @@ impl EncodeContext<'tcx> {
12711266
let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);
12721267

12731268
record!(self.per_def.kind[def_id] <- match ty.kind {
1274-
ty::Generator(def_id, ..) => {
1275-
let layout = self.tcx.generator_layout(def_id);
1276-
let data = GeneratorData {
1277-
layout: layout.clone(),
1278-
};
1279-
EntryKind::Generator(self.lazy(data))
1269+
ty::Generator(..) => {
1270+
let data = self.tcx.generator_kind(def_id).unwrap();
1271+
EntryKind::Generator(data)
12801272
}
12811273

12821274
ty::Closure(..) => EntryKind::Closure,

src/librustc_metadata/rmeta/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ macro_rules! define_per_def_tables {
252252
}
253253

254254
define_per_def_tables! {
255-
kind: Table<DefIndex, Lazy!(EntryKind<'tcx>)>,
255+
kind: Table<DefIndex, Lazy<EntryKind>>,
256256
visibility: Table<DefIndex, Lazy<ty::Visibility>>,
257257
span: Table<DefIndex, Lazy<Span>>,
258258
attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
@@ -279,7 +279,7 @@ define_per_def_tables! {
279279
}
280280

281281
#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
282-
enum EntryKind<'tcx> {
282+
enum EntryKind {
283283
Const(mir::ConstQualifs, Lazy<RenderedConst>),
284284
ImmStatic,
285285
MutStatic,
@@ -302,7 +302,7 @@ enum EntryKind<'tcx> {
302302
Mod(Lazy<ModData>),
303303
MacroDef(Lazy<MacroDef>),
304304
Closure,
305-
Generator(Lazy!(GeneratorData<'tcx>)),
305+
Generator(hir::GeneratorKind),
306306
Trait(Lazy<TraitData>),
307307
Impl(Lazy<ImplData>),
308308
Method(Lazy<MethodData>),

src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs

+2-12
Original file line numberDiff line numberDiff line change
@@ -1257,7 +1257,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12571257
}
12581258
_ => bug!(
12591259
"report_escaping_closure_capture called with unexpected constraint \
1260-
category: `{:?}`",
1260+
category: `{:?}`",
12611261
category
12621262
),
12631263
};
@@ -1275,17 +1275,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
12751275
) -> DiagnosticBuilder<'cx> {
12761276
let tcx = self.infcx.tcx;
12771277

1278-
let escapes_from = if tcx.is_closure(self.mir_def_id) {
1279-
let tables = tcx.typeck_tables_of(self.mir_def_id);
1280-
let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
1281-
match tables.node_type(mir_hir_id).kind {
1282-
ty::Closure(..) => "closure",
1283-
ty::Generator(..) => "generator",
1284-
_ => bug!("Closure body doesn't have a closure or generator type"),
1285-
}
1286-
} else {
1287-
"function"
1288-
};
1278+
let (_, escapes_from) = tcx.article_and_description(self.mir_def_id);
12891279

12901280
let mut err =
12911281
borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);

src/librustc_mir/borrow_check/diagnostics/region_errors.rs

+8-10
Original file line numberDiff line numberDiff line change
@@ -427,18 +427,17 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
427427
errci.outlived_fr,
428428
);
429429

430-
let escapes_from = match self.regioncx.universal_regions().defining_ty {
431-
DefiningTy::Closure(..) => "closure",
432-
DefiningTy::Generator(..) => "generator",
433-
DefiningTy::FnDef(..) => "function",
434-
DefiningTy::Const(..) => "const",
435-
};
430+
let (_, escapes_from) = self
431+
.infcx
432+
.tcx
433+
.article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
436434

437435
// Revert to the normal error in these cases.
438436
// Assignments aren't "escapes" in function items.
439437
if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
440-
|| (*category == ConstraintCategory::Assignment && escapes_from == "function")
441-
|| escapes_from == "const"
438+
|| (*category == ConstraintCategory::Assignment
439+
&& self.regioncx.universal_regions().defining_ty.is_fn_def())
440+
|| self.regioncx.universal_regions().defining_ty.is_const()
442441
{
443442
return self.report_general_error(&ErrorConstraintInfo {
444443
fr_is_local: true,
@@ -504,8 +503,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
504503
let mut diag =
505504
self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
506505

507-
let mir_def_name =
508-
if self.infcx.tcx.is_closure(self.mir_def_id) { "closure" } else { "function" };
506+
let (_, mir_def_name) = self.infcx.tcx.article_and_description(self.mir_def_id);
509507

510508
let fr_name = self.give_region_a_name(*fr).unwrap();
511509
fr_name.highlight_region_name(&mut diag);

src/librustc_mir/borrow_check/universal_regions.rs

+23
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,29 @@ impl<'tcx> DefiningTy<'tcx> {
131131
DefiningTy::FnDef(..) | DefiningTy::Const(..) => 0,
132132
}
133133
}
134+
135+
pub fn is_fn_def(&self) -> bool {
136+
match *self {
137+
DefiningTy::FnDef(..) => true,
138+
_ => false,
139+
}
140+
}
141+
142+
pub fn is_const(&self) -> bool {
143+
match *self {
144+
DefiningTy::Const(..) => true,
145+
_ => false,
146+
}
147+
}
148+
149+
pub fn def_id(&self) -> DefId {
150+
match *self {
151+
DefiningTy::Closure(def_id, ..)
152+
| DefiningTy::Generator(def_id, ..)
153+
| DefiningTy::FnDef(def_id, ..)
154+
| DefiningTy::Const(def_id, ..) => def_id,
155+
}
156+
}
134157
}
135158

136159
#[derive(Debug)]

src/librustc_typeck/collect.rs

+14-2
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ pub fn provide(providers: &mut Providers<'_>) {
7676
impl_polarity,
7777
is_foreign_item,
7878
static_mutability,
79+
generator_kind,
7980
codegen_fn_attrs,
8081
collect_mod_item_types,
8182
..*providers
@@ -1006,7 +1007,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
10061007
.struct_span_err(
10071008
item.span,
10081009
"the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
1009-
which traits can use parenthetical notation",
1010+
which traits can use parenthetical notation",
10101011
)
10111012
.help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
10121013
.emit();
@@ -2106,7 +2107,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
21062107
ast_ty.span,
21072108
&format!(
21082109
"use of SIMD type `{}` in FFI is highly experimental and \
2109-
may result in invalid code",
2110+
may result in invalid code",
21102111
tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
21112112
),
21122113
)
@@ -2145,6 +2146,17 @@ fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability>
21452146
}
21462147
}
21472148

2149+
fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
2150+
match tcx.hir().get_if_local(def_id) {
2151+
Some(Node::Expr(&rustc_hir::Expr {
2152+
kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
2153+
..
2154+
})) => tcx.hir().body(body_id).generator_kind(),
2155+
Some(_) => None,
2156+
_ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
2157+
}
2158+
}
2159+
21482160
fn from_target_feature(
21492161
tcx: TyCtxt<'_>,
21502162
id: DefId,

src/test/ui/async-await/issues/issue-62097.nll.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,13 @@ help: to force the closure to take ownership of `self` (and any other referenced
1616
LL | foo(move || self.bar()).await;
1717
| ^^^^^^^
1818

19-
error[E0521]: borrowed data escapes outside of function
19+
error[E0521]: borrowed data escapes outside of method
2020
--> $DIR/issue-62097.rs:13:9
2121
|
2222
LL | pub async fn run_dummy_fn(&self) {
23-
| ----- `self` is a reference that is only valid in the function body
23+
| ----- `self` is a reference that is only valid in the method body
2424
LL | foo(|| self.bar()).await;
25-
| ^^^^^^^^^^^^^^^^^^ `self` escapes the function body here
25+
| ^^^^^^^^^^^^^^^^^^ `self` escapes the method body here
2626

2727
error: aborting due to 2 previous errors
2828

src/test/ui/async-await/issues/issue-63388-1.nll.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ LL | ) -> &dyn Foo
99
LL | / {
1010
LL | | foo
1111
LL | | }
12-
| |_____^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
12+
| |_____^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
1313

1414
error: aborting due to previous error
1515

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
error[E0521]: borrowed data escapes outside of function
1+
error[E0521]: borrowed data escapes outside of method
22
--> $DIR/issue-16683.rs:4:9
33
|
44
LL | fn b(&self) {
5-
| ----- `self` is a reference that is only valid in the function body
5+
| ----- `self` is a reference that is only valid in the method body
66
LL | self.a();
7-
| ^^^^^^^^ `self` escapes the function body here
7+
| ^^^^^^^^ `self` escapes the method body here
88

99
error: aborting due to previous error
1010

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
error[E0521]: borrowed data escapes outside of function
1+
error[E0521]: borrowed data escapes outside of method
22
--> $DIR/issue-17758.rs:7:9
33
|
44
LL | fn bar(&self) {
5-
| ----- `self` is a reference that is only valid in the function body
5+
| ----- `self` is a reference that is only valid in the method body
66
LL | self.foo();
7-
| ^^^^^^^^^^ `self` escapes the function body here
7+
| ^^^^^^^^^^ `self` escapes the method body here
88

99
error: aborting due to previous error
1010

src/test/ui/lifetimes/lifetime-errors/ex1-return-one-existing-name-if-else-using-impl.nll.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ LL | fn foo<'a>(x: &i32, y: &'a i32) -> &'a i32 {
77
| lifetime `'a` defined here
88
LL |
99
LL | if x > y { x } else { y }
10-
| ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
10+
| ^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
1111

1212
error: aborting due to previous error
1313

src/test/ui/lifetimes/lifetime-errors/ex1-return-one-existing-name-return-type-is-anon.nll.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ LL | fn foo<'a>(&self, x: &'a i32) -> &i32 {
77
| lifetime `'a` defined here
88
LL |
99
LL | x
10-
| ^ function was supposed to return data with lifetime `'1` but it is returning data with lifetime `'a`
10+
| ^ method was supposed to return data with lifetime `'1` but it is returning data with lifetime `'a`
1111

1212
error: aborting due to previous error
1313

0 commit comments

Comments
 (0)