Skip to content

Commit

Permalink
Auto merge of rust-lang#94148 - matthiaskrgr:rollup-jgea68f, r=matthi…
Browse files Browse the repository at this point in the history
…askrgr

Rollup of 7 pull requests

Successful merges:

 - rust-lang#92902 (Improve the documentation of drain members)
 - rust-lang#93658 (Stabilize `#[cfg(panic = "...")]`)
 - rust-lang#93954 (rustdoc-json: buffer output)
 - rust-lang#93979 (Add debug assertions to validate NUL terminator in c strings)
 - rust-lang#93990 (pre rust-lang#89862 cleanup)
 - rust-lang#94006 (Use a `Field` in `ConstraintCategory::ClosureUpvar`)
 - rust-lang#94086 (Fix ScalarInt to char conversion)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
  • Loading branch information
bors committed Feb 19, 2022
2 parents cb4ee81 + 5a083db commit e08d569
Show file tree
Hide file tree
Showing 34 changed files with 256 additions and 214 deletions.
22 changes: 16 additions & 6 deletions compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustc_infer::infer::{
error_reporting::nice_region_error::NiceRegionError,
error_reporting::unexpected_hidden_region_diagnostic, NllRegionVariableOrigin,
};
use rustc_middle::hir::place::PlaceBase;
use rustc_middle::mir::{ConstraintCategory, ReturnConstraint};
use rustc_middle::ty::subst::{InternalSubsts, Subst};
use rustc_middle::ty::{self, RegionVid, Ty};
Expand Down Expand Up @@ -421,17 +422,26 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {

diag.span_label(*span, message);

// FIXME(project-rfc-2229#48): This should store a captured_place not a hir id
if let ReturnConstraint::ClosureUpvar(upvar) = kind {
if let ReturnConstraint::ClosureUpvar(upvar_field) = 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");
let captured_place = &self.upvars[upvar_field.index()].place;
let defined_hir = match captured_place.place.base {
PlaceBase::Local(hirid) => Some(hirid),
PlaceBase::Upvar(upvar) => Some(upvar.var_path.hir_id),
_ => None,
};

if defined_hir.is_some() {
let upvars_map = self.infcx.tcx.upvars_mentioned(def_id).unwrap();
let upvar_def_span = self.infcx.tcx.hir().span(defined_hir.unwrap());
let upvar_span = upvars_map.get(&defined_hir.unwrap()).unwrap().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() {
Expand Down
4 changes: 1 addition & 3 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2530,9 +2530,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
body,
);
let category = if let Some(field) = field {
let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable();
// FIXME(project-rfc-2229#8): Use Place for better diagnostics
ConstraintCategory::ClosureUpvar(var_hir_id)
ConstraintCategory::ClosureUpvar(field)
} else {
ConstraintCategory::Boring
};
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_feature/src/accepted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ declare_features! (
(accepted, cfg_attr_multi, "1.33.0", Some(54881), None),
/// Allows the use of `#[cfg(doctest)]`, set when rustdoc is collecting doctests.
(accepted, cfg_doctest, "1.40.0", Some(62210), None),
/// Enables `#[cfg(panic = "...")]` config key.
(accepted, cfg_panic, "1.60.0", Some(77443), None),
/// Allows `cfg(target_feature = "...")`.
(accepted, cfg_target_feature, "1.27.0", Some(29717), None),
/// Allows `cfg(target_vendor = "...")`.
Expand Down
2 changes: 0 additions & 2 deletions compiler/rustc_feature/src/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,6 @@ declare_features! (
(active, c_variadic, "1.34.0", Some(44930), None),
/// Allows capturing disjoint fields in a closure/generator (RFC 2229).
(incomplete, capture_disjoint_fields, "1.49.0", Some(53488), None),
/// Enables `#[cfg(panic = "...")]` config key.
(active, cfg_panic, "1.49.0", Some(77443), None),
/// Allows the use of `#[cfg(sanitize = "option")]`; set when -Zsanitizer is used.
(active, cfg_sanitize, "1.41.0", Some(39699), None),
/// Allows `cfg(target_abi = "...")`.
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_feature/src/builtin_attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ const GATED_CFGS: &[GatedCfg] = &[
(sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)),
(sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)),
(sym::version, sym::cfg_version, cfg_fn!(cfg_version)),
(sym::panic, sym::cfg_panic, cfg_fn!(cfg_panic)),
];

/// Find a gated cfg determined by the `pred`icate which is given the cfg's name.
Expand Down
30 changes: 23 additions & 7 deletions compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -497,16 +497,32 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let ty_to_string = |ty: Ty<'tcx>| -> String {
let mut s = String::new();
let mut printer = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS);
let mut inner = self.inner.borrow_mut();
let ty_vars = inner.type_variables();
let getter = move |ty_vid| {
let var_origin = ty_vars.var_origin(ty_vid);
if let TypeVariableOriginKind::TypeParameterDefinition(name, _) = var_origin.kind {
let ty_getter = move |ty_vid| {
if let TypeVariableOriginKind::TypeParameterDefinition(name, _) =
self.inner.borrow_mut().type_variables().var_origin(ty_vid).kind
{
Some(name.to_string())
} else {
None
}
};
printer.ty_infer_name_resolver = Some(Box::new(ty_getter));
let const_getter = move |ct_vid| {
if let ConstVariableOriginKind::ConstParameterDefinition(name, _) = self
.inner
.borrow_mut()
.const_unification_table()
.probe_value(ct_vid)
.origin
.kind
{
return Some(name.to_string());
} else {
None
}
None
};
printer.name_resolver = Some(Box::new(&getter));
printer.const_infer_name_resolver = Some(Box::new(const_getter));

let _ = if let ty::FnDef(..) = ty.kind() {
// We don't want the regular output for `fn`s because it includes its path in
// invalid pseudo-syntax, we want the `fn`-pointer output instead.
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/mir/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ pub enum ConstraintCategory {
/// like `Foo { field: my_val }`)
Usage,
OpaqueType,
ClosureUpvar(hir::HirId),
ClosureUpvar(Field),

/// A constraint from a user-written predicate
/// with the provided span, written on the item
Expand All @@ -363,7 +363,7 @@ pub enum ConstraintCategory {
#[derive(TyEncodable, TyDecodable, HashStable)]
pub enum ReturnConstraint {
Normal,
ClosureUpvar(hir::HirId),
ClosureUpvar(Field),
}

/// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
Expand Down
18 changes: 14 additions & 4 deletions compiler/rustc_middle/src/ty/consts/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,12 +294,22 @@ impl From<char> for ScalarInt {
}
}

/// Error returned when a conversion from ScalarInt to char fails.
#[derive(Debug)]
pub struct CharTryFromScalarInt;

impl TryFrom<ScalarInt> for char {
type Error = Size;
type Error = CharTryFromScalarInt;

#[inline]
fn try_from(int: ScalarInt) -> Result<Self, Size> {
int.to_bits(Size::from_bytes(std::mem::size_of::<char>()))
.map(|u| char::from_u32(u.try_into().unwrap()).unwrap())
fn try_from(int: ScalarInt) -> Result<Self, Self::Error> {
let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else {
return Err(CharTryFromScalarInt);
};
match char::from_u32(bits.try_into().unwrap()) {
Some(c) => Ok(c),
None => Err(CharTryFromScalarInt),
}
}
}

Expand Down
31 changes: 24 additions & 7 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ pub trait PrettyPrinter<'tcx>:
ty::Infer(infer_ty) => {
let verbose = self.tcx().sess.verbose();
if let ty::TyVar(ty_vid) = infer_ty {
if let Some(name) = self.infer_ty_name(ty_vid) {
if let Some(name) = self.ty_infer_name(ty_vid) {
p!(write("{}", name))
} else {
if verbose {
Expand Down Expand Up @@ -1015,7 +1015,11 @@ pub trait PrettyPrinter<'tcx>:
}
}

fn infer_ty_name(&self, _: ty::TyVid) -> Option<String> {
fn ty_infer_name(&self, _: ty::TyVid) -> Option<String> {
None
}

fn const_infer_name(&self, _: ty::ConstVid<'tcx>) -> Option<String> {
None
}

Expand Down Expand Up @@ -1203,7 +1207,14 @@ pub trait PrettyPrinter<'tcx>:
}
}
}
ty::ConstKind::Infer(..) => print_underscore!(),
ty::ConstKind::Infer(infer_ct) => {
match infer_ct {
ty::InferConst::Var(ct_vid)
if let Some(name) = self.const_infer_name(ct_vid) =>
p!(write("{}", name)),
_ => print_underscore!(),
}
}
ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)),
ty::ConstKind::Value(value) => {
return self.pretty_print_const_value(value, ct.ty(), print_ty);
Expand Down Expand Up @@ -1559,7 +1570,8 @@ pub struct FmtPrinterData<'a, 'tcx, F> {

pub region_highlight_mode: RegionHighlightMode<'tcx>,

pub name_resolver: Option<Box<&'a dyn Fn(ty::TyVid) -> Option<String>>>,
pub ty_infer_name_resolver: Option<Box<dyn Fn(ty::TyVid) -> Option<String> + 'a>>,
pub const_infer_name_resolver: Option<Box<dyn Fn(ty::ConstVid<'tcx>) -> Option<String> + 'a>>,
}

impl<'a, 'tcx, F> Deref for FmtPrinter<'a, 'tcx, F> {
Expand Down Expand Up @@ -1588,7 +1600,8 @@ impl<'a, 'tcx, F> FmtPrinter<'a, 'tcx, F> {
binder_depth: 0,
printed_type_count: 0,
region_highlight_mode: RegionHighlightMode::new(tcx),
name_resolver: None,
ty_infer_name_resolver: None,
const_infer_name_resolver: None,
}))
}
}
Expand Down Expand Up @@ -1843,8 +1856,12 @@ impl<'tcx, F: fmt::Write> Printer<'tcx> for FmtPrinter<'_, 'tcx, F> {
}

impl<'tcx, F: fmt::Write> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx, F> {
fn infer_ty_name(&self, id: ty::TyVid) -> Option<String> {
self.0.name_resolver.as_ref().and_then(|func| func(id))
fn ty_infer_name(&self, id: ty::TyVid) -> Option<String> {
self.0.ty_infer_name_resolver.as_ref().and_then(|func| func(id))
}

fn const_infer_name(&self, id: ty::ConstVid<'tcx>) -> Option<String> {
self.0.const_infer_name_resolver.as_ref().and_then(|func| func(id))
}

fn print_value_path(
Expand Down
33 changes: 32 additions & 1 deletion compiler/rustc_middle/src/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use rustc_data_structures::intern::Interned;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_hir as hir;
use rustc_hir::def::DefKind;
use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::DefId;
use rustc_macros::HashStable;
use rustc_query_system::ich::NodeIdHashingMode;
Expand Down Expand Up @@ -146,6 +146,37 @@ impl<'tcx> TyCtxt<'tcx> {
hasher.finish()
}

pub fn res_generics_def_id(self, res: Res) -> Option<DefId> {
match res {
Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => {
Some(self.parent(def_id).and_then(|def_id| self.parent(def_id)).unwrap())
}
Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
Some(self.parent(def_id).unwrap())
}
// Other `DefKind`s don't have generics and would ICE when calling
// `generics_of`.
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::OpaqueTy
| DefKind::TyAlias
| DefKind::ForeignTy
| DefKind::TraitAlias
| DefKind::AssocTy
| DefKind::Fn
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::Impl,
def_id,
) => Some(def_id),
Res::Err => None,
_ => None,
}
}

pub fn has_error_field(self, ty: Ty<'tcx>) -> bool {
if let ty::Adt(def, substs) = *ty.kind() {
for field in def.all_fields() {
Expand Down
40 changes: 5 additions & 35 deletions compiler/rustc_typeck/src/collect/type_of.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use rustc_errors::{Applicability, ErrorReported, StashKey};
use rustc_hir as hir;
use rustc_hir::def::CtorOf;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::def::Res;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit;
use rustc_hir::intravisit::Visitor;
use rustc_hir::{HirId, Node};
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::subst::InternalSubsts;
use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable, TypeFolder};
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeFolder};
use rustc_span::symbol::Ident;
use rustc_span::{Span, DUMMY_SP};

Expand Down Expand Up @@ -198,38 +197,9 @@ pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<
// Try to use the segment resolution if it is valid, otherwise we
// default to the path resolution.
let res = segment.res.filter(|&r| r != Res::Err).unwrap_or(path.res);
let generics = match res {
Res::Def(DefKind::Ctor(CtorOf::Variant, _), def_id) => tcx
.generics_of(tcx.parent(def_id).and_then(|def_id| tcx.parent(def_id)).unwrap()),
Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Struct, _), def_id) => {
tcx.generics_of(tcx.parent(def_id).unwrap())
}
// Other `DefKind`s don't have generics and would ICE when calling
// `generics_of`.
Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
| DefKind::Trait
| DefKind::OpaqueTy
| DefKind::TyAlias
| DefKind::ForeignTy
| DefKind::TraitAlias
| DefKind::AssocTy
| DefKind::Fn
| DefKind::AssocFn
| DefKind::AssocConst
| DefKind::Impl,
def_id,
) => tcx.generics_of(def_id),
Res::Err => {
tcx.sess.delay_span_bug(tcx.def_span(def_id), "anon const with Res::Err");
return None;
}
_ => {
// If the user tries to specify generics on a type that does not take them,
// e.g. `usize<T>`, we may hit this branch, in which case we treat it as if
// no arguments have been passed. An error should already have been emitted.
let generics = match tcx.res_generics_def_id(res) {
Some(def_id) => tcx.generics_of(def_id),
None => {
tcx.sess.delay_span_bug(
tcx.def_span(def_id),
&format!("unexpected anon const res {:?} in path: {:?}", res, path),
Expand Down
16 changes: 11 additions & 5 deletions library/alloc/src/collections/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -746,9 +746,12 @@ impl<T: Ord> BinaryHeap<T> {
self.rebuild_tail(start);
}

/// Returns an iterator which retrieves elements in heap order.
/// The retrieved elements are removed from the original heap.
/// The remaining elements will be removed on drop in heap order.
/// Clears the binary heap, returning an iterator over the removed elements
/// in heap order. If the iterator is dropped before being fully consumed,
/// it drops the remaining elements in heap order.
///
/// The returned iterator keeps a mutable borrow on the heap to optimize
/// its implementation.
///
/// Note:
/// * `.drain_sorted()` is *O*(*n* \* log(*n*)); much slower than `.drain()`.
Expand Down Expand Up @@ -1158,9 +1161,12 @@ impl<T> BinaryHeap<T> {
self.len() == 0
}

/// Clears the binary heap, returning an iterator over the removed elements.
/// Clears the binary heap, returning an iterator over the removed elements
/// in arbitrary order. If the iterator is dropped before being fully
/// consumed, it drops the remaining elements in arbitrary order.
///
/// The elements are removed in arbitrary order.
/// The returned iterator keeps a mutable borrow on the heap to optimize
/// its implementation.
///
/// # Examples
///
Expand Down
Loading

0 comments on commit e08d569

Please sign in to comment.