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

Generalized article_and_description #67742

Merged
merged 9 commits into from
Feb 27, 2020
Merged
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions src/librustc/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ rustc_queries! {
/// Returns `Some(mutability)` if the node pointed to by `def_id` is a static item.
query static_mutability(_: DefId) -> Option<hir::Mutability> {}

/// Returns `Some(generator_kind)` if the node pointed to by `def_id` is a generator.
query generator_kind(_: DefId) -> Option<hir::GeneratorKind> {}

/// Gets a map with the variance of every item; use `item_variance` instead.
query crate_variances(_: CrateNum) -> &'tcx ty::CrateVariancesMap<'tcx> {
desc { "computing the variances for items in this crate" }
Expand Down
22 changes: 20 additions & 2 deletions src/librustc/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::dep_graph::DepGraph;
use crate::dep_graph::{self, DepConstructor};
use crate::hir::exports::Export;
use crate::hir::map as hir_map;
use crate::hir::map::DefPathHash;
use crate::hir::map::{DefPathData, DefPathHash};
use crate::ich::{NodeIdHashingMode, StableHashingContext};
use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos};
use crate::lint::{struct_lint_level, LintSource};
Expand Down Expand Up @@ -209,7 +209,7 @@ fn validate_hir_id_for_typeck_tables(
ty::tls::with(|tcx| {
bug!(
"node {} with HirId::owner {:?} cannot be placed in \
TypeckTables with local_id_root {:?}",
TypeckTables with local_id_root {:?}",
tcx.hir().node_to_string(hir_id),
DefId::local(hir_id.owner),
local_id_root
Expand Down Expand Up @@ -1512,6 +1512,24 @@ impl<'tcx> TyCtxt<'tcx> {
.subst(*self, self.mk_substs([self.lifetimes.re_static.into()].iter())),
)
}

/// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`).
pub fn article_and_description(&self, def_id: DefId) -> (&'static str, &'static str) {
match self.def_key(def_id).disambiguated_data.data {
DefPathData::TypeNs(..) | DefPathData::ValueNs(..) | DefPathData::MacroNs(..) => {
let kind = self.def_kind(def_id).unwrap();
(kind.article(), kind.descr(def_id))
Comment on lines +1520 to +1521
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish I saw this earlier - I think you should always call def_kind and only look at the def_key or other things if def_kind returned None.

The reason is that DefKind should eventually encompass every possible DefId, and the current situation is a transitional one (since DefKind was split out of name resolution, which only needs the current set of possible DefKinds).

Copy link
Member

@eddyb eddyb Feb 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if there is an issue for finishing DefKind, but feel free to work on that, or open one if there isn't one already.

Ideally def_key would be used in as few places as possible, as it's really the "name" of a definition more than anything else.

}
DefPathData::ClosureExpr => match self.generator_kind(def_id) {
None => ("a", "closure"),
Some(rustc_hir::GeneratorKind::Async(..)) => ("an", "async closure"),
Some(rustc_hir::GeneratorKind::Gen) => ("a", "generator"),
},
DefPathData::LifetimeNs(..) => ("a", "lifetime"),
DefPathData::Impl => ("an", "implementation"),
_ => bug!("article_and_description called on def_id {:?}", def_id),
mark-i-m marked this conversation as resolved.
Show resolved Hide resolved
}
}
}

impl<'tcx> GlobalCtxt<'tcx> {
Expand Down
19 changes: 13 additions & 6 deletions src/librustc_metadata/rmeta/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ impl MetadataBlob {
}
}

impl<'tcx> EntryKind<'tcx> {
impl EntryKind {
fn def_kind(&self) -> Option<DefKind> {
Some(match *self {
EntryKind::Const(..) => DefKind::Const,
Expand Down Expand Up @@ -614,11 +614,11 @@ impl<'a, 'tcx> CrateMetadata {
self.root.proc_macro_data.and_then(|data| data.decode(self).find(|x| *x == id)).is_some()
}

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

fn kind(&self, item_id: DefIndex) -> EntryKind<'tcx> {
fn kind(&self, item_id: DefIndex) -> EntryKind {
assert!(!self.is_proc_macro(item_id));
self.maybe_kind(item_id).unwrap_or_else(|| {
bug!(
Expand Down Expand Up @@ -723,7 +723,7 @@ impl<'a, 'tcx> CrateMetadata {
fn get_variant(
&self,
tcx: TyCtxt<'tcx>,
kind: &EntryKind<'_>,
kind: &EntryKind,
index: DefIndex,
parent_did: DefId,
) -> ty::VariantDef {
Expand Down Expand Up @@ -1390,6 +1390,13 @@ impl<'a, 'tcx> CrateMetadata {
}
}

fn generator_kind(&self, id: DefIndex) -> Option<hir::GeneratorKind> {
match self.kind(id) {
EntryKind::Generator(data) => Some(data),
_ => None,
}
}

fn fn_sig(&self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> {
self.root.per_def.fn_sig.get(self, id).unwrap().decode((self, tcx))
}
Expand Down Expand Up @@ -1499,8 +1506,8 @@ impl<'a, 'tcx> CrateMetadata {
);
debug!(
"CrateMetaData::imported_source_files alloc \
source_file {:?} original (start_pos {:?} end_pos {:?}) \
translated (start_pos {:?} end_pos {:?})",
source_file {:?} original (start_pos {:?} end_pos {:?}) \
translated (start_pos {:?} end_pos {:?})",
local_version.name,
start_pos,
end_pos,
Expand Down
1 change: 1 addition & 0 deletions src/librustc_metadata/rmeta/decoder/cstore_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
asyncness => { cdata.asyncness(def_id.index) }
is_foreign_item => { cdata.is_foreign_item(def_id.index) }
static_mutability => { cdata.static_mutability(def_id.index) }
generator_kind => { cdata.generator_kind(def_id.index) }
def_kind => { cdata.def_kind(def_id.index) }
def_span => { cdata.get_span(def_id.index, &tcx.sess) }
lookup_stability => {
Expand Down
18 changes: 5 additions & 13 deletions src/librustc_metadata/rmeta/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ impl<'tcx> EncodeContext<'tcx> {
assert!(
last_min_end <= lazy.position,
"make sure that the calls to `lazy*` \
are in the same order as the metadata fields",
are in the same order as the metadata fields",
);
lazy.position.get() - last_min_end.get()
}
Expand Down Expand Up @@ -1248,12 +1248,7 @@ impl EncodeContext<'tcx> {
self.encode_deprecation(def_id);
}

fn encode_info_for_generic_param(
&mut self,
def_id: DefId,
kind: EntryKind<'tcx>,
encode_type: bool,
) {
fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) {
record!(self.per_def.kind[def_id] <- kind);
record!(self.per_def.visibility[def_id] <- ty::Visibility::Public);
record!(self.per_def.span[def_id] <- self.tcx.def_span(def_id));
Expand All @@ -1271,12 +1266,9 @@ impl EncodeContext<'tcx> {
let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id);

record!(self.per_def.kind[def_id] <- match ty.kind {
ty::Generator(def_id, ..) => {
let layout = self.tcx.generator_layout(def_id);
let data = GeneratorData {
layout: layout.clone(),
};
EntryKind::Generator(self.lazy(data))
ty::Generator(..) => {
let data = self.tcx.generator_kind(def_id).unwrap();
EntryKind::Generator(data)
}

ty::Closure(..) => EntryKind::Closure,
Expand Down
6 changes: 3 additions & 3 deletions src/librustc_metadata/rmeta/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ macro_rules! define_per_def_tables {
}

define_per_def_tables! {
kind: Table<DefIndex, Lazy!(EntryKind<'tcx>)>,
kind: Table<DefIndex, Lazy<EntryKind>>,
visibility: Table<DefIndex, Lazy<ty::Visibility>>,
span: Table<DefIndex, Lazy<Span>>,
attributes: Table<DefIndex, Lazy<[ast::Attribute]>>,
Expand All @@ -279,7 +279,7 @@ define_per_def_tables! {
}

#[derive(Copy, Clone, RustcEncodable, RustcDecodable)]
enum EntryKind<'tcx> {
enum EntryKind {
Const(mir::ConstQualifs, Lazy<RenderedConst>),
ImmStatic,
MutStatic,
Expand All @@ -302,7 +302,7 @@ enum EntryKind<'tcx> {
Mod(Lazy<ModData>),
MacroDef(Lazy<MacroDef>),
Closure,
Generator(Lazy!(GeneratorData<'tcx>)),
Generator(hir::GeneratorKind),
Trait(Lazy<TraitData>),
Impl(Lazy<ImplData>),
Method(Lazy<MethodData>),
Expand Down
14 changes: 2 additions & 12 deletions src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1257,7 +1257,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
}
_ => bug!(
"report_escaping_closure_capture called with unexpected constraint \
category: `{:?}`",
category: `{:?}`",
category
),
};
Expand All @@ -1275,17 +1275,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
) -> DiagnosticBuilder<'cx> {
let tcx = self.infcx.tcx;

let escapes_from = if tcx.is_closure(self.mir_def_id) {
let tables = tcx.typeck_tables_of(self.mir_def_id);
let mir_hir_id = tcx.hir().def_index_to_hir_id(self.mir_def_id.index);
match tables.node_type(mir_hir_id).kind {
ty::Closure(..) => "closure",
ty::Generator(..) => "generator",
_ => bug!("Closure body doesn't have a closure or generator type"),
}
} else {
"function"
};
let (_, escapes_from) = tcx.article_and_description(self.mir_def_id);

let mut err =
borrowck_errors::borrowed_data_escapes_closure(tcx, escape_span, escapes_from);
Expand Down
18 changes: 8 additions & 10 deletions src/librustc_mir/borrow_check/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,18 +427,17 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
errci.outlived_fr,
);

let escapes_from = match self.regioncx.universal_regions().defining_ty {
DefiningTy::Closure(..) => "closure",
DefiningTy::Generator(..) => "generator",
DefiningTy::FnDef(..) => "function",
DefiningTy::Const(..) => "const",
};
let (_, escapes_from) = self
.infcx
.tcx
.article_and_description(self.regioncx.universal_regions().defining_ty.def_id());

// Revert to the normal error in these cases.
// Assignments aren't "escapes" in function items.
if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
|| (*category == ConstraintCategory::Assignment && escapes_from == "function")
|| escapes_from == "const"
|| (*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,
Expand Down Expand Up @@ -504,8 +503,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
let mut diag =
self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");

let mir_def_name =
if self.infcx.tcx.is_closure(self.mir_def_id) { "closure" } else { "function" };
let (_, mir_def_name) = self.infcx.tcx.article_and_description(self.mir_def_id);

let fr_name = self.give_region_a_name(*fr).unwrap();
fr_name.highlight_region_name(&mut diag);
Expand Down
23 changes: 23 additions & 0 deletions src/librustc_mir/borrow_check/universal_regions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,29 @@ impl<'tcx> DefiningTy<'tcx> {
DefiningTy::FnDef(..) | DefiningTy::Const(..) => 0,
}
}

pub fn is_fn_def(&self) -> bool {
match *self {
DefiningTy::FnDef(..) => true,
_ => false,
}
}

pub fn is_const(&self) -> bool {
match *self {
DefiningTy::Const(..) => true,
_ => false,
}
}

pub fn def_id(&self) -> DefId {
match *self {
DefiningTy::Closure(def_id, ..)
| DefiningTy::Generator(def_id, ..)
| DefiningTy::FnDef(def_id, ..)
| DefiningTy::Const(def_id, ..) => def_id,
}
}
}

#[derive(Debug)]
Expand Down
16 changes: 14 additions & 2 deletions src/librustc_typeck/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ pub fn provide(providers: &mut Providers<'_>) {
impl_polarity,
is_foreign_item,
static_mutability,
generator_kind,
codegen_fn_attrs,
collect_mod_item_types,
..*providers
Expand Down Expand Up @@ -1006,7 +1007,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: DefId) -> &ty::TraitDef {
.struct_span_err(
item.span,
"the `#[rustc_paren_sugar]` attribute is a temporary means of controlling \
which traits can use parenthetical notation",
which traits can use parenthetical notation",
)
.help("add `#![feature(unboxed_closures)]` to the crate attributes to use it")
.emit();
Expand Down Expand Up @@ -2106,7 +2107,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
ast_ty.span,
&format!(
"use of SIMD type `{}` in FFI is highly experimental and \
may result in invalid code",
may result in invalid code",
tcx.hir().hir_to_pretty_string(ast_ty.hir_id)
),
)
Expand Down Expand Up @@ -2145,6 +2146,17 @@ fn static_mutability(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::Mutability>
}
}

fn generator_kind(tcx: TyCtxt<'_>, def_id: DefId) -> Option<hir::GeneratorKind> {
match tcx.hir().get_if_local(def_id) {
Some(Node::Expr(&rustc_hir::Expr {
kind: rustc_hir::ExprKind::Closure(_, _, body_id, _, _),
..
})) => tcx.hir().body(body_id).generator_kind(),
Some(_) => None,
_ => bug!("generator_kind applied to non-local def-id {:?}", def_id),
}
}

fn from_target_feature(
tcx: TyCtxt<'_>,
id: DefId,
Expand Down
Loading