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 8 pull requests #98381

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
a336686
Fix trait object reborrow suggestion
compiler-errors Jun 20, 2022
448e00b
Note concrete type being coerced into object
compiler-errors Jun 20, 2022
1e7ab0b
point at private fields in struct literal
TaKO8Ki Jun 20, 2022
3f12fa7
Add support for macro in "jump to def" feature
GuillaumeGomez Nov 26, 2021
dda980d
Rename ContextInfo into HrefContext
GuillaumeGomez Jun 18, 2022
f001795
don't alloc error string if no error emitted
klensy Jun 20, 2022
810254b
Improve code readability and documentation
GuillaumeGomez Jun 18, 2022
f4db07e
Add test for macro support in "jump to def" feature
GuillaumeGomez Nov 26, 2021
987c731
Integrate `generate_macro_def_id_path` into `href_with_root_path`
GuillaumeGomez Jun 20, 2022
beb2f36
Fix panic by checking if `CStore` has the crate data we want before a…
GuillaumeGomez Jun 20, 2022
b37a05b
rustdoc: optimize loading of source sidebar
jsha Jun 20, 2022
e900a35
Give name if anonymous region appears in impl signature
compiler-errors Jun 21, 2022
f924e74
Provide a segment res in more cases
compiler-errors Jun 20, 2022
a0eba66
[RFC 2011] Optimize non-consuming operators
c410-f3r Jun 21, 2022
f847261
stop pointing at definitions of missing fields
TaKO8Ki Jun 22, 2022
eb86daa
add "was" to pluralize macro and use it
TaKO8Ki Jun 22, 2022
ef5ff2f
Rollup merge of #91264 - GuillaumeGomez:macro-jump-to-def, r=jsha
Dylan-DPC Jun 22, 2022
c26b9dd
Rollup merge of #98184 - compiler-errors:elided-lifetime-in-impl-nll,…
Dylan-DPC Jun 22, 2022
9ee8708
Rollup merge of #98269 - compiler-errors:provide-more-segment-res, r=…
Dylan-DPC Jun 22, 2022
4a72e16
Rollup merge of #98277 - compiler-errors:issue-93596, r=estebank
Dylan-DPC Jun 22, 2022
082289e
Rollup merge of #98283 - TaKO8Ki:point-at-private-fields-in-struct-li…
Dylan-DPC Jun 22, 2022
74abe7c
Rollup merge of #98305 - klensy:no-err-alloc, r=compiler-errors
Dylan-DPC Jun 22, 2022
3a97aba
Rollup merge of #98310 - jsha:defer-source-sidebar, r=GuillaumeGomez
Dylan-DPC Jun 22, 2022
77732a5
Rollup merge of #98337 - c410-f3r:assert-compiler, r=oli-obk
Dylan-DPC Jun 22, 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
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ impl OutlivesSuggestionBuilder {
| RegionNameSource::AnonRegionFromUpvar(..)
| RegionNameSource::AnonRegionFromOutput(..)
| RegionNameSource::AnonRegionFromYieldTy(..)
| RegionNameSource::AnonRegionFromAsyncFn(..) => {
| RegionNameSource::AnonRegionFromAsyncFn(..)
| RegionNameSource::AnonRegionFromImplSignature(..) => {
debug!("Region {:?} is NOT suggestable", name);
false
}
Expand Down
58 changes: 54 additions & 4 deletions compiler/rustc_borrowck/src/diagnostics/region_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_middle::ty::print::RegionHighlightMode;
use rustc_middle::ty::subst::{GenericArgKind, SubstsRef};
use rustc_middle::ty::{self, RegionVid, Ty};
use rustc_middle::ty::{self, DefIdTree, RegionVid, Ty};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP};

Expand Down Expand Up @@ -45,6 +45,8 @@ pub(crate) enum RegionNameSource {
AnonRegionFromYieldTy(Span, String),
/// An anonymous region from an async fn.
AnonRegionFromAsyncFn(Span),
/// An anonymous region from an impl self type or trait
AnonRegionFromImplSignature(Span, &'static str),
}

/// Describes what to highlight to explain to the user that we're giving an anonymous region a
Expand Down Expand Up @@ -75,7 +77,8 @@ impl RegionName {
| RegionNameSource::AnonRegionFromUpvar(..)
| RegionNameSource::AnonRegionFromOutput(..)
| RegionNameSource::AnonRegionFromYieldTy(..)
| RegionNameSource::AnonRegionFromAsyncFn(..) => false,
| RegionNameSource::AnonRegionFromAsyncFn(..)
| RegionNameSource::AnonRegionFromImplSignature(..) => false,
}
}

Expand All @@ -87,7 +90,8 @@ impl RegionName {
| RegionNameSource::SynthesizedFreeEnvRegion(span, _)
| RegionNameSource::AnonRegionFromUpvar(span, _)
| RegionNameSource::AnonRegionFromYieldTy(span, _)
| RegionNameSource::AnonRegionFromAsyncFn(span) => Some(span),
| RegionNameSource::AnonRegionFromAsyncFn(span)
| RegionNameSource::AnonRegionFromImplSignature(span, _) => Some(span),
RegionNameSource::AnonRegionFromArgument(ref highlight)
| RegionNameSource::AnonRegionFromOutput(ref highlight, _) => match *highlight {
RegionNameHighlight::MatchedHirTy(span)
Expand Down Expand Up @@ -166,6 +170,12 @@ impl RegionName {
RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
diag.span_label(*span, format!("yield type is {type_name}"));
}
RegionNameSource::AnonRegionFromImplSignature(span, location) => {
diag.span_label(
*span,
format!("lifetime `{self}` appears in the `impl`'s {location}"),
);
}
RegionNameSource::Static => {}
}
}
Expand Down Expand Up @@ -240,7 +250,8 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
.or_else(|| self.give_name_if_anonymous_region_appears_in_arguments(fr))
.or_else(|| self.give_name_if_anonymous_region_appears_in_upvars(fr))
.or_else(|| self.give_name_if_anonymous_region_appears_in_output(fr))
.or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr));
.or_else(|| self.give_name_if_anonymous_region_appears_in_yield_ty(fr))
.or_else(|| self.give_name_if_anonymous_region_appears_in_impl_signature(fr));

if let Some(ref value) = value {
self.region_names.try_borrow_mut().unwrap().insert(fr, value.clone());
Expand Down Expand Up @@ -840,4 +851,43 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
})
}

fn give_name_if_anonymous_region_appears_in_impl_signature(
&self,
fr: RegionVid,
) -> Option<RegionName> {
let ty::ReEarlyBound(region) = *self.to_error_region(fr)? else {
return None;
};
if region.has_name() {
return None;
};

let tcx = self.infcx.tcx;
let body_parent_did = tcx.opt_parent(self.mir_def_id().to_def_id())?;
if tcx.parent(region.def_id) != body_parent_did
|| tcx.def_kind(body_parent_did) != DefKind::Impl
{
return None;
}

let mut found = false;
tcx.fold_regions(tcx.type_of(body_parent_did), &mut true, |r: ty::Region<'tcx>, _| {
if *r == ty::ReEarlyBound(region) {
found = true;
}
r
});

Some(RegionName {
name: self.synthesize_region_name(),
source: RegionNameSource::AnonRegionFromImplSignature(
tcx.def_span(region.def_id),
// FIXME(compiler-errors): Does this ever actually show up
// anywhere other than the self type? I couldn't create an
// example of a `'_` in the impl's trait being referenceable.
if found { "self type" } else { "header" },
),
})
}
}
96 changes: 81 additions & 15 deletions compiler/rustc_builtin_macros/src/assert/context.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use crate::assert::expr_if_not;
use rustc_ast::{
attr,
ptr::P,
token,
tokenstream::{DelimSpan, TokenStream, TokenTree},
BorrowKind, Expr, ExprKind, ItemKind, MacArgs, MacCall, MacDelimiter, Mutability, Path,
PathSegment, Stmt, StructRest, UseTree, UseTreeKind, DUMMY_NODE_ID,
BinOpKind, BorrowKind, Expr, ExprKind, ItemKind, MacArgs, MacCall, MacDelimiter, Mutability,
Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, DUMMY_NODE_ID,
};
use rustc_ast_pretty::pprust;
use rustc_data_structures::fx::FxHashSet;
Expand All @@ -16,11 +15,19 @@ use rustc_span::{
};

pub(super) struct Context<'cx, 'a> {
// An optimization.
//
// Elements that aren't consumed (PartialEq, PartialOrd, ...) can be copied **after** the
// `assert!` expression fails rather than copied on-the-fly.
best_case_captures: Vec<Stmt>,
// Top-level `let captureN = Capture::new()` statements
capture_decls: Vec<Capture>,
cx: &'cx ExtCtxt<'a>,
// Formatting string used for debugging
fmt_string: String,
// If the current expression being visited consumes itself. Used to construct
// `best_case_captures`.
is_consumed: bool,
// Top-level `let __local_bindN = &expr` statements
local_bind_decls: Vec<Stmt>,
// Used to avoid capturing duplicated paths
Expand All @@ -36,9 +43,11 @@ pub(super) struct Context<'cx, 'a> {
impl<'cx, 'a> Context<'cx, 'a> {
pub(super) fn new(cx: &'cx ExtCtxt<'a>, span: Span) -> Self {
Self {
best_case_captures: <_>::default(),
capture_decls: <_>::default(),
cx,
fmt_string: <_>::default(),
is_consumed: true,
local_bind_decls: <_>::default(),
paths: <_>::default(),
span,
Expand Down Expand Up @@ -69,14 +78,22 @@ impl<'cx, 'a> Context<'cx, 'a> {
self.manage_cond_expr(&mut cond_expr);
let initial_imports = self.build_initial_imports();
let panic = self.build_panic(&expr_str, panic_path);
let cond_expr_with_unlikely = self.build_unlikely(cond_expr);

let Self { best_case_captures, capture_decls, cx, local_bind_decls, span, .. } = self;

let Self { capture_decls, cx, local_bind_decls, span, .. } = self;
let mut assert_then_stmts = Vec::with_capacity(2);
assert_then_stmts.extend(best_case_captures);
assert_then_stmts.push(self.cx.stmt_expr(panic));
let assert_then = self.cx.block(span, assert_then_stmts);

let mut stmts = Vec::with_capacity(4);
stmts.push(initial_imports);
stmts.extend(capture_decls.into_iter().map(|c| c.decl));
stmts.extend(local_bind_decls);
stmts.push(cx.stmt_expr(expr_if_not(cx, span, cond_expr, panic, None)));
stmts.push(
cx.stmt_expr(cx.expr(span, ExprKind::If(cond_expr_with_unlikely, assert_then, None))),
);
cx.expr_block(cx.block(span, stmts))
}

Expand Down Expand Up @@ -115,6 +132,16 @@ impl<'cx, 'a> Context<'cx, 'a> {
)
}

/// Takes the conditional expression of `assert!` and then wraps it inside `unlikely`
fn build_unlikely(&self, cond_expr: P<Expr>) -> P<Expr> {
let unlikely_path = self.cx.std_path(&[sym::intrinsics, sym::unlikely]);
self.cx.expr_call(
self.span,
self.cx.expr_path(self.cx.path(self.span, unlikely_path)),
vec![self.cx.expr(self.span, ExprKind::Unary(UnOp::Not, cond_expr))],
)
}

/// The necessary custom `panic!(...)` expression.
///
/// panic!(
Expand Down Expand Up @@ -167,17 +194,39 @@ impl<'cx, 'a> Context<'cx, 'a> {
/// See [Self::manage_initial_capture] and [Self::manage_try_capture]
fn manage_cond_expr(&mut self, expr: &mut P<Expr>) {
match (*expr).kind {
ExprKind::AddrOf(_, _, ref mut local_expr) => {
self.manage_cond_expr(local_expr);
ExprKind::AddrOf(_, mutability, ref mut local_expr) => {
self.with_is_consumed_management(
matches!(mutability, Mutability::Mut),
|this| this.manage_cond_expr(local_expr)
);
}
ExprKind::Array(ref mut local_exprs) => {
for local_expr in local_exprs {
self.manage_cond_expr(local_expr);
}
}
ExprKind::Binary(_, ref mut lhs, ref mut rhs) => {
self.manage_cond_expr(lhs);
self.manage_cond_expr(rhs);
ExprKind::Binary(ref op, ref mut lhs, ref mut rhs) => {
self.with_is_consumed_management(
matches!(
op.node,
BinOpKind::Add
| BinOpKind::And
| BinOpKind::BitAnd
| BinOpKind::BitOr
| BinOpKind::BitXor
| BinOpKind::Div
| BinOpKind::Mul
| BinOpKind::Or
| BinOpKind::Rem
| BinOpKind::Shl
| BinOpKind::Shr
| BinOpKind::Sub
),
|this| {
this.manage_cond_expr(lhs);
this.manage_cond_expr(rhs);
}
);
}
ExprKind::Call(_, ref mut local_exprs) => {
for local_expr in local_exprs {
Expand Down Expand Up @@ -228,8 +277,11 @@ impl<'cx, 'a> Context<'cx, 'a> {
self.manage_cond_expr(local_expr);
}
}
ExprKind::Unary(_, ref mut local_expr) => {
self.manage_cond_expr(local_expr);
ExprKind::Unary(un_op, ref mut local_expr) => {
self.with_is_consumed_management(
matches!(un_op, UnOp::Neg | UnOp::Not),
|this| this.manage_cond_expr(local_expr)
);
}
// Expressions that are not worth or can not be captured.
//
Expand Down Expand Up @@ -337,9 +389,23 @@ impl<'cx, 'a> Context<'cx, 'a> {
))
.add_trailing_semicolon();
let local_bind_path = self.cx.expr_path(Path::from_ident(local_bind));
let ret = self.cx.stmt_expr(local_bind_path);
let block = self.cx.expr_block(self.cx.block(self.span, vec![try_capture_call, ret]));
*expr = self.cx.expr_deref(self.span, block);
let rslt = if self.is_consumed {
let ret = self.cx.stmt_expr(local_bind_path);
self.cx.expr_block(self.cx.block(self.span, vec![try_capture_call, ret]))
} else {
self.best_case_captures.push(try_capture_call);
local_bind_path
};
*expr = self.cx.expr_deref(self.span, rslt);
}

// Calls `f` with the internal `is_consumed` set to `curr_is_consumed` and then
// sets the internal `is_consumed` back to its original value.
fn with_is_consumed_management(&mut self, curr_is_consumed: bool, f: impl FnOnce(&mut Self)) {
let prev_is_consumed = self.is_consumed;
self.is_consumed = curr_is_consumed;
f(self);
self.is_consumed = prev_is_consumed;
}
}

Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_lint_defs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ macro_rules! pluralize {
("is", $x:expr) => {
if $x == 1 { "is" } else { "are" }
};
("was", $x:expr) => {
if $x == 1 { "was" } else { "were" }
};
("this", $x:expr) => {
if $x == 1 { "this" } else { "these" }
};
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ impl CStore {
CrateNum::new(self.metas.len() - 1)
}

pub fn has_crate_data(&self, cnum: CrateNum) -> bool {
self.metas[cnum].is_some()
}

pub(crate) fn get_crate_data(&self, cnum: CrateNum) -> CrateMetadataRef<'_> {
let cdata = self.metas[cnum]
.as_ref()
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub enum ObligationCauseCode<'tcx> {
ObjectTypeBound(Ty<'tcx>, ty::Region<'tcx>),

/// Obligation incurred due to an object cast.
ObjectCastObligation(/* Object type */ Ty<'tcx>),
ObjectCastObligation(/* Concrete type */ Ty<'tcx>, /* Object type */ Ty<'tcx>),

/// Obligation incurred due to a coercion.
Coercion {
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_resolve/src/ident.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1502,6 +1502,7 @@ impl<'a> Resolver<'a> {
return PathResult::NonModule(PartialRes::new(Res::Err));
} else if opt_ns.is_some() && (is_last || maybe_assoc) {
self.lint_if_path_starts_with_module(finalize, path, second_binding);
record_segment_res(self, res);
return PathResult::NonModule(PartialRes::with_unresolved_segments(
res,
path.len() - i - 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -484,10 +484,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
err.span_label(span, explanation);
}

if let ObligationCauseCode::ObjectCastObligation(obj_ty) = obligation.cause.code().peel_derives() &&
let Some(self_ty) = trait_predicate.self_ty().no_bound_vars() &&
if let ObligationCauseCode::ObjectCastObligation(concrete_ty, obj_ty) = obligation.cause.code().peel_derives() &&
Some(trait_ref.def_id()) == self.tcx.lang_items().sized_trait() {
self.suggest_borrowing_for_object_cast(&mut err, &obligation, self_ty, *obj_ty);
self.suggest_borrowing_for_object_cast(&mut err, &root_obligation, *concrete_ty, *obj_ty);
}

if trait_predicate.is_const_if_const() && obligation.param_env.is_const() {
Expand Down Expand Up @@ -1560,7 +1559,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'a, 'tcx> for InferCtxt<'a, 'tcx> {
obligation.cause.code().peel_derives(),
ObligationCauseCode::ItemObligation(_)
| ObligationCauseCode::BindingObligation(_, _)
| ObligationCauseCode::ObjectCastObligation(_)
| ObligationCauseCode::ObjectCastObligation(..)
| ObligationCauseCode::OpaqueType
);
if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2217,9 +2217,10 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
err.span_note(tcx.def_span(item_def_id), &descr);
}
}
ObligationCauseCode::ObjectCastObligation(object_ty) => {
ObligationCauseCode::ObjectCastObligation(concrete_ty, object_ty) => {
err.note(&format!(
"required for the cast to the object type `{}`",
"required for the cast from `{}` to the object type `{}`",
self.ty_to_string(concrete_ty),
self.ty_to_string(object_ty)
));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let cause = ObligationCause::new(
obligation.cause.span,
obligation.cause.body_id,
ObjectCastObligation(target),
ObjectCastObligation(source, target),
);
let outlives = ty::OutlivesPredicate(r_a, r_b);
nested.push(Obligation::with_depth(
Expand Down Expand Up @@ -910,7 +910,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let cause = ObligationCause::new(
obligation.cause.span,
obligation.cause.body_id,
ObjectCastObligation(target),
ObjectCastObligation(source, target),
);
let outlives = ty::OutlivesPredicate(r_a, r_b);
nested.push(Obligation::with_depth(
Expand All @@ -931,7 +931,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
let cause = ObligationCause::new(
obligation.cause.span,
obligation.cause.body_id,
ObjectCastObligation(target),
ObjectCastObligation(source, target),
);

let predicate_to_obligation = |predicate| {
Expand Down
Loading