Merge from rustc
This commit is contained in:
commit
1dcc3420d2
356 changed files with 7505 additions and 3189 deletions
|
|
@ -10,8 +10,6 @@ use crate::{AssocItem, Expr, ForeignItem, Item, NodeId};
|
|||
use crate::{AttrItem, AttrKind, Block, Pat, Path, Ty, Visibility};
|
||||
use crate::{AttrVec, Attribute, Stmt, StmtKind};
|
||||
|
||||
use rustc_span::Span;
|
||||
|
||||
use std::fmt;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
|
|
@ -91,37 +89,6 @@ impl<T: AstDeref<Target: HasNodeId>> HasNodeId for T {
|
|||
}
|
||||
}
|
||||
|
||||
/// A trait for AST nodes having a span.
|
||||
pub trait HasSpan {
|
||||
fn span(&self) -> Span;
|
||||
}
|
||||
|
||||
macro_rules! impl_has_span {
|
||||
($($T:ty),+ $(,)?) => {
|
||||
$(
|
||||
impl HasSpan for $T {
|
||||
fn span(&self) -> Span {
|
||||
self.span
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
impl_has_span!(AssocItem, Block, Expr, ForeignItem, Item, Pat, Path, Stmt, Ty, Visibility);
|
||||
|
||||
impl<T: AstDeref<Target: HasSpan>> HasSpan for T {
|
||||
fn span(&self) -> Span {
|
||||
self.ast_deref().span()
|
||||
}
|
||||
}
|
||||
|
||||
impl HasSpan for AttrItem {
|
||||
fn span(&self) -> Span {
|
||||
self.span()
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for AST nodes having (or not having) collected tokens.
|
||||
pub trait HasTokens {
|
||||
fn tokens(&self) -> Option<&LazyAttrTokenStream>;
|
||||
|
|
|
|||
|
|
@ -202,7 +202,8 @@ impl Attribute {
|
|||
}
|
||||
}
|
||||
|
||||
pub fn tokens(&self) -> TokenStream {
|
||||
// Named `get_tokens` to distinguish it from the `<Attribute as HasTokens>::tokens` method.
|
||||
pub fn get_tokens(&self) -> TokenStream {
|
||||
match &self.kind {
|
||||
AttrKind::Normal(normal) => TokenStream::new(
|
||||
normal
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ pub mod tokenstream;
|
|||
pub mod visit;
|
||||
|
||||
pub use self::ast::*;
|
||||
pub use self::ast_traits::{AstDeref, AstNodeWrapper, HasAttrs, HasNodeId, HasSpan, HasTokens};
|
||||
pub use self::ast_traits::{AstDeref, AstNodeWrapper, HasAttrs, HasNodeId, HasTokens};
|
||||
|
||||
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
|
||||
|
||||
|
|
|
|||
|
|
@ -704,7 +704,7 @@ fn visit_attr_tt<T: MutVisitor>(tt: &mut AttrTokenTree, vis: &mut T) {
|
|||
visit_attr_tts(tts, vis);
|
||||
visit_delim_span(dspan, vis);
|
||||
}
|
||||
AttrTokenTree::Attributes(AttributesData { attrs, tokens }) => {
|
||||
AttrTokenTree::AttrsTarget(AttrsTarget { attrs, tokens }) => {
|
||||
visit_attrs(attrs, vis);
|
||||
visit_lazy_tts_opt_mut(Some(tokens), vis);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
//! ownership of the original.
|
||||
|
||||
use crate::ast::{AttrStyle, StmtKind};
|
||||
use crate::ast_traits::{HasAttrs, HasSpan, HasTokens};
|
||||
use crate::ast_traits::{HasAttrs, HasTokens};
|
||||
use crate::token::{self, Delimiter, Nonterminal, Token, TokenKind};
|
||||
use crate::AttrVec;
|
||||
|
||||
|
|
@ -170,8 +170,8 @@ pub enum AttrTokenTree {
|
|||
Delimited(DelimSpan, DelimSpacing, Delimiter, AttrTokenStream),
|
||||
/// Stores the attributes for an attribute target,
|
||||
/// along with the tokens for that attribute target.
|
||||
/// See `AttributesData` for more information
|
||||
Attributes(AttributesData),
|
||||
/// See `AttrsTarget` for more information
|
||||
AttrsTarget(AttrsTarget),
|
||||
}
|
||||
|
||||
impl AttrTokenStream {
|
||||
|
|
@ -180,7 +180,7 @@ impl AttrTokenStream {
|
|||
}
|
||||
|
||||
/// Converts this `AttrTokenStream` to a plain `Vec<TokenTree>`.
|
||||
/// During conversion, `AttrTokenTree::Attributes` get 'flattened'
|
||||
/// During conversion, `AttrTokenTree::AttrsTarget` get 'flattened'
|
||||
/// back to a `TokenStream` of the form `outer_attr attr_target`.
|
||||
/// If there are inner attributes, they are inserted into the proper
|
||||
/// place in the attribute target tokens.
|
||||
|
|
@ -199,13 +199,13 @@ impl AttrTokenStream {
|
|||
TokenStream::new(stream.to_token_trees()),
|
||||
))
|
||||
}
|
||||
AttrTokenTree::Attributes(data) => {
|
||||
let idx = data
|
||||
AttrTokenTree::AttrsTarget(target) => {
|
||||
let idx = target
|
||||
.attrs
|
||||
.partition_point(|attr| matches!(attr.style, crate::AttrStyle::Outer));
|
||||
let (outer_attrs, inner_attrs) = data.attrs.split_at(idx);
|
||||
let (outer_attrs, inner_attrs) = target.attrs.split_at(idx);
|
||||
|
||||
let mut target_tokens = data.tokens.to_attr_token_stream().to_token_trees();
|
||||
let mut target_tokens = target.tokens.to_attr_token_stream().to_token_trees();
|
||||
if !inner_attrs.is_empty() {
|
||||
let mut found = false;
|
||||
// Check the last two trees (to account for a trailing semi)
|
||||
|
|
@ -227,7 +227,7 @@ impl AttrTokenStream {
|
|||
|
||||
let mut stream = TokenStream::default();
|
||||
for inner_attr in inner_attrs {
|
||||
stream.push_stream(inner_attr.tokens());
|
||||
stream.push_stream(inner_attr.get_tokens());
|
||||
}
|
||||
stream.push_stream(delim_tokens.clone());
|
||||
*tree = TokenTree::Delimited(*span, *spacing, *delim, stream);
|
||||
|
|
@ -242,7 +242,7 @@ impl AttrTokenStream {
|
|||
);
|
||||
}
|
||||
for attr in outer_attrs {
|
||||
res.extend(attr.tokens().0.iter().cloned());
|
||||
res.extend(attr.get_tokens().0.iter().cloned());
|
||||
}
|
||||
res.extend(target_tokens);
|
||||
}
|
||||
|
|
@ -262,7 +262,7 @@ impl AttrTokenStream {
|
|||
/// have an `attrs` field containing the `#[cfg(FALSE)]` attr,
|
||||
/// and a `tokens` field storing the (unparsed) tokens `struct Foo {}`
|
||||
#[derive(Clone, Debug, Encodable, Decodable)]
|
||||
pub struct AttributesData {
|
||||
pub struct AttrsTarget {
|
||||
/// Attributes, both outer and inner.
|
||||
/// These are stored in the original order that they were parsed in.
|
||||
pub attrs: AttrVec,
|
||||
|
|
@ -436,17 +436,17 @@ impl TokenStream {
|
|||
TokenStream::new(vec![TokenTree::token_alone(kind, span)])
|
||||
}
|
||||
|
||||
pub fn from_ast(node: &(impl HasAttrs + HasSpan + HasTokens + fmt::Debug)) -> TokenStream {
|
||||
pub fn from_ast(node: &(impl HasAttrs + HasTokens + fmt::Debug)) -> TokenStream {
|
||||
let Some(tokens) = node.tokens() else {
|
||||
panic!("missing tokens for node at {:?}: {:?}", node.span(), node);
|
||||
panic!("missing tokens for node: {:?}", node);
|
||||
};
|
||||
let attrs = node.attrs();
|
||||
let attr_stream = if attrs.is_empty() {
|
||||
tokens.to_attr_token_stream()
|
||||
} else {
|
||||
let attr_data =
|
||||
AttributesData { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
|
||||
AttrTokenStream::new(vec![AttrTokenTree::Attributes(attr_data)])
|
||||
let target =
|
||||
AttrsTarget { attrs: attrs.iter().cloned().collect(), tokens: tokens.clone() };
|
||||
AttrTokenStream::new(vec![AttrTokenTree::AttrsTarget(target)])
|
||||
};
|
||||
TokenStream::new(attr_stream.to_token_trees())
|
||||
}
|
||||
|
|
@ -765,6 +765,7 @@ mod size_asserts {
|
|||
static_assert_size!(AttrTokenStream, 8);
|
||||
static_assert_size!(AttrTokenTree, 32);
|
||||
static_assert_size!(LazyAttrTokenStream, 8);
|
||||
static_assert_size!(Option<LazyAttrTokenStream>, 8); // must be small, used in many AST nodes
|
||||
static_assert_size!(TokenStream, 8);
|
||||
static_assert_size!(TokenTree, 32);
|
||||
// tidy-alphabetical-end
|
||||
|
|
|
|||
|
|
@ -727,6 +727,12 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
|
|||
}
|
||||
self.mutate_place(loc, (*destination, span), Deep, flow_state);
|
||||
}
|
||||
TerminatorKind::TailCall { func, args, fn_span: _ } => {
|
||||
self.consume_operand(loc, (func, span), flow_state);
|
||||
for arg in args {
|
||||
self.consume_operand(loc, (&arg.node, arg.span), flow_state);
|
||||
}
|
||||
}
|
||||
TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
|
||||
self.consume_operand(loc, (cond, span), flow_state);
|
||||
if let AssertKind::BoundsCheck { len, index } = &**msg {
|
||||
|
|
@ -813,9 +819,8 @@ impl<'a, 'mir, 'tcx, R> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx, R>
|
|||
|
||||
TerminatorKind::UnwindResume
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::CoroutineDrop => {
|
||||
// Returning from the function implicitly kills storage for all locals and statics.
|
||||
// Often, the storage will already have been killed by an explicit
|
||||
// StorageDead, but we don't always emit those (notably on unwind paths),
|
||||
// so this "extra check" serves as a kind of backup.
|
||||
let borrow_set = self.borrow_set.clone();
|
||||
|
|
|
|||
|
|
@ -125,6 +125,12 @@ impl<'cx, 'tcx> Visitor<'tcx> for LoanInvalidationsGenerator<'cx, 'tcx> {
|
|||
}
|
||||
self.mutate_place(location, *destination, Deep);
|
||||
}
|
||||
TerminatorKind::TailCall { func, args, .. } => {
|
||||
self.consume_operand(location, func);
|
||||
for arg in args {
|
||||
self.consume_operand(location, &arg.node);
|
||||
}
|
||||
}
|
||||
TerminatorKind::Assert { cond, expected: _, msg, target: _, unwind: _ } => {
|
||||
self.consume_operand(location, cond);
|
||||
use rustc_middle::mir::AssertKind;
|
||||
|
|
|
|||
|
|
@ -38,6 +38,7 @@ use rustc_span::def_id::CRATE_DEF_ID;
|
|||
use rustc_span::source_map::Spanned;
|
||||
use rustc_span::symbol::sym;
|
||||
use rustc_span::Span;
|
||||
use rustc_span::DUMMY_SP;
|
||||
use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
|
||||
use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
|
||||
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
|
||||
|
|
@ -49,6 +50,7 @@ use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
|
|||
use rustc_mir_dataflow::move_paths::MoveData;
|
||||
use rustc_mir_dataflow::ResultsCursor;
|
||||
|
||||
use crate::renumber::RegionCtxt;
|
||||
use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst};
|
||||
use crate::{
|
||||
borrow_set::BorrowSet,
|
||||
|
|
@ -1352,7 +1354,14 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
|
|||
}
|
||||
// FIXME: check the values
|
||||
}
|
||||
TerminatorKind::Call { func, args, destination, call_source, target, .. } => {
|
||||
TerminatorKind::Call { func, args, .. }
|
||||
| TerminatorKind::TailCall { func, args, .. } => {
|
||||
let call_source = match term.kind {
|
||||
TerminatorKind::Call { call_source, .. } => call_source,
|
||||
TerminatorKind::TailCall { .. } => CallSource::Normal,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
self.check_operand(func, term_location);
|
||||
for arg in args {
|
||||
self.check_operand(&arg.node, term_location);
|
||||
|
|
@ -1425,7 +1434,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
|
|||
);
|
||||
}
|
||||
|
||||
self.check_call_dest(body, term, &sig, *destination, *target, term_location);
|
||||
if let TerminatorKind::Call { destination, target, .. } = term.kind {
|
||||
self.check_call_dest(body, term, &sig, destination, target, term_location);
|
||||
}
|
||||
|
||||
// The ordinary liveness rules will ensure that all
|
||||
// regions in the type of the callee are live here. We
|
||||
|
|
@ -1443,7 +1454,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
|
|||
.add_location(region_vid, term_location);
|
||||
}
|
||||
|
||||
self.check_call_inputs(body, term, func, &sig, args, term_location, *call_source);
|
||||
self.check_call_inputs(body, term, func, &sig, args, term_location, call_source);
|
||||
}
|
||||
TerminatorKind::Assert { cond, msg, .. } => {
|
||||
self.check_operand(cond, term_location);
|
||||
|
|
@ -1675,6 +1686,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
|
|||
span_mirbug!(self, block_data, "return on cleanup block")
|
||||
}
|
||||
}
|
||||
TerminatorKind::TailCall { .. } => {
|
||||
if is_cleanup {
|
||||
span_mirbug!(self, block_data, "tailcall on cleanup block")
|
||||
}
|
||||
}
|
||||
TerminatorKind::CoroutineDrop { .. } => {
|
||||
if is_cleanup {
|
||||
span_mirbug!(self, block_data, "coroutine_drop in cleanup block")
|
||||
|
|
@ -2319,7 +2335,57 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
|
|||
let cast_ty_from = CastTy::from_ty(ty_from);
|
||||
let cast_ty_to = CastTy::from_ty(*ty);
|
||||
match (cast_ty_from, cast_ty_to) {
|
||||
(Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
|
||||
(Some(CastTy::Ptr(src)), Some(CastTy::Ptr(dst))) => {
|
||||
let mut normalize = |t| self.normalize(t, location);
|
||||
let src_tail =
|
||||
tcx.struct_tail_with_normalize(src.ty, &mut normalize, || ());
|
||||
let dst_tail =
|
||||
tcx.struct_tail_with_normalize(dst.ty, &mut normalize, || ());
|
||||
|
||||
// This checks (lifetime part of) vtable validity for pointer casts,
|
||||
// which is irrelevant when there are aren't principal traits on both sides (aka only auto traits).
|
||||
//
|
||||
// Note that other checks (such as denying `dyn Send` -> `dyn Debug`) are in `rustc_hir_typeck`.
|
||||
if let ty::Dynamic(src_tty, ..) = src_tail.kind()
|
||||
&& let ty::Dynamic(dst_tty, ..) = dst_tail.kind()
|
||||
&& src_tty.principal().is_some()
|
||||
&& dst_tty.principal().is_some()
|
||||
{
|
||||
// Remove auto traits.
|
||||
// Auto trait checks are handled in `rustc_hir_typeck` as FCW.
|
||||
let src_obj = tcx.mk_ty_from_kind(ty::Dynamic(
|
||||
tcx.mk_poly_existential_predicates(
|
||||
&src_tty.without_auto_traits().collect::<Vec<_>>(),
|
||||
),
|
||||
tcx.lifetimes.re_static,
|
||||
ty::Dyn,
|
||||
));
|
||||
let dst_obj = tcx.mk_ty_from_kind(ty::Dynamic(
|
||||
tcx.mk_poly_existential_predicates(
|
||||
&dst_tty.without_auto_traits().collect::<Vec<_>>(),
|
||||
),
|
||||
tcx.lifetimes.re_static,
|
||||
ty::Dyn,
|
||||
));
|
||||
|
||||
// Replace trait object lifetimes with fresh vars, to allow casts like
|
||||
// `*mut dyn FnOnce() + 'a` -> `*mut dyn FnOnce() + 'static`,
|
||||
let src_obj =
|
||||
freshen_single_trait_object_lifetime(self.infcx, src_obj);
|
||||
let dst_obj =
|
||||
freshen_single_trait_object_lifetime(self.infcx, dst_obj);
|
||||
|
||||
debug!(?src_tty, ?dst_tty, ?src_obj, ?dst_obj);
|
||||
|
||||
self.eq_types(
|
||||
src_obj,
|
||||
dst_obj,
|
||||
location.to_locations(),
|
||||
ConstraintCategory::Cast { unsize_to: None },
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
span_mirbug!(
|
||||
self,
|
||||
|
|
@ -2842,3 +2908,16 @@ impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
|
|||
Ok(output)
|
||||
}
|
||||
}
|
||||
|
||||
fn freshen_single_trait_object_lifetime<'tcx>(
|
||||
infcx: &BorrowckInferCtxt<'tcx>,
|
||||
ty: Ty<'tcx>,
|
||||
) -> Ty<'tcx> {
|
||||
let &ty::Dynamic(tty, _, dyn_kind @ ty::Dyn) = ty.kind() else { bug!("expected trait object") };
|
||||
|
||||
let fresh = infcx
|
||||
.next_region_var(rustc_infer::infer::RegionVariableOrigin::MiscVariable(DUMMY_SP), || {
|
||||
RegionCtxt::Unknown
|
||||
});
|
||||
infcx.tcx.mk_ty_from_kind(ty::Dynamic(tty, fresh, dyn_kind))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -193,7 +193,7 @@ impl CfgEval<'_> {
|
|||
|
||||
// Re-parse the tokens, setting the `capture_cfg` flag to save extra information
|
||||
// to the captured `AttrTokenStream` (specifically, we capture
|
||||
// `AttrTokenTree::AttributesData` for all occurrences of `#[cfg]` and `#[cfg_attr]`)
|
||||
// `AttrTokenTree::AttrsTarget` for all occurrences of `#[cfg]` and `#[cfg_attr]`)
|
||||
let mut parser = Parser::new(&self.0.sess.psess, orig_tokens, None);
|
||||
parser.capture_cfg = true;
|
||||
match parse_annotatable_with(&mut parser) {
|
||||
|
|
|
|||
|
|
@ -491,6 +491,11 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
|
|||
)
|
||||
});
|
||||
}
|
||||
// FIXME(explicit_tail_calls): add support for tail calls to the cranelift backend, once cranelift supports tail calls
|
||||
TerminatorKind::TailCall { fn_span, .. } => span_bug!(
|
||||
*fn_span,
|
||||
"tail calls are not yet supported in `rustc_codegen_cranelift` backend"
|
||||
),
|
||||
TerminatorKind::InlineAsm {
|
||||
template,
|
||||
operands,
|
||||
|
|
|
|||
|
|
@ -567,6 +567,7 @@ pub(crate) fn mir_operand_get_const_val<'tcx>(
|
|||
{
|
||||
return None;
|
||||
}
|
||||
TerminatorKind::TailCall { .. } => return None,
|
||||
TerminatorKind::Call { .. } => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -281,6 +281,7 @@ pub fn cleanup_kinds(mir: &mir::Body<'_>) -> IndexVec<mir::BasicBlock, CleanupKi
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::CoroutineDrop
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::SwitchInt { .. }
|
||||
|
|
|
|||
|
|
@ -1389,6 +1389,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
|
|||
fn_span,
|
||||
mergeable_succ(),
|
||||
),
|
||||
mir::TerminatorKind::TailCall { .. } => {
|
||||
// FIXME(explicit_tail_calls): implement tail calls in ssa backend
|
||||
span_bug!(
|
||||
terminator.source_info.span,
|
||||
"`TailCall` terminator is not yet supported by `rustc_codegen_ssa`"
|
||||
)
|
||||
}
|
||||
mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
|
||||
bug!("coroutine ops in codegen")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -135,6 +135,8 @@ impl<'mir, 'tcx> Qualifs<'mir, 'tcx> {
|
|||
ccx: &'mir ConstCx<'mir, 'tcx>,
|
||||
tainted_by_errors: Option<ErrorGuaranteed>,
|
||||
) -> ConstQualifs {
|
||||
// FIXME(explicit_tail_calls): uhhhh I think we can return without return now, does it change anything
|
||||
|
||||
// Find the `Return` terminator if one exists.
|
||||
//
|
||||
// If no `Return` terminator exists, this MIR is divergent. Just return the conservative
|
||||
|
|
@ -711,7 +713,14 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
|
|||
self.super_terminator(terminator, location);
|
||||
|
||||
match &terminator.kind {
|
||||
TerminatorKind::Call { func, args, fn_span, call_source, .. } => {
|
||||
TerminatorKind::Call { func, args, fn_span, .. }
|
||||
| TerminatorKind::TailCall { func, args, fn_span, .. } => {
|
||||
let call_source = match terminator.kind {
|
||||
TerminatorKind::Call { call_source, .. } => call_source,
|
||||
TerminatorKind::TailCall { .. } => CallSource::Normal,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
let ConstCx { tcx, body, param_env, .. } = *self.ccx;
|
||||
let caller = self.def_id();
|
||||
|
||||
|
|
@ -783,7 +792,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
|
|||
callee,
|
||||
args: fn_args,
|
||||
span: *fn_span,
|
||||
call_source: *call_source,
|
||||
call_source,
|
||||
feature: Some(if tcx.features().const_trait_impl {
|
||||
sym::effects
|
||||
} else {
|
||||
|
|
@ -830,7 +839,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> {
|
|||
callee,
|
||||
args: fn_args,
|
||||
span: *fn_span,
|
||||
call_source: *call_source,
|
||||
call_source,
|
||||
feature: None,
|
||||
});
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -108,6 +108,7 @@ impl<'tcx> Visitor<'tcx> for CheckLiveDrops<'_, 'tcx> {
|
|||
|
||||
mir::TerminatorKind::UnwindTerminate(_)
|
||||
| mir::TerminatorKind::Call { .. }
|
||||
| mir::TerminatorKind::TailCall { .. }
|
||||
| mir::TerminatorKind::Assert { .. }
|
||||
| mir::TerminatorKind::FalseEdge { .. }
|
||||
| mir::TerminatorKind::FalseUnwind { .. }
|
||||
|
|
|
|||
|
|
@ -26,8 +26,8 @@ use rustc_target::abi::{call::FnAbi, Align, HasDataLayout, Size, TargetDataLayou
|
|||
use super::{
|
||||
err_inval, throw_inval, throw_ub, throw_ub_custom, throw_unsup, GlobalId, Immediate,
|
||||
InterpErrorInfo, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, Memory, MemoryKind,
|
||||
OpTy, Operand, Place, PlaceTy, Pointer, PointerArithmetic, Projectable, Provenance, Scalar,
|
||||
StackPopJump,
|
||||
OpTy, Operand, Place, PlaceTy, Pointer, PointerArithmetic, Projectable, Provenance,
|
||||
ReturnAction, Scalar,
|
||||
};
|
||||
use crate::errors;
|
||||
use crate::util;
|
||||
|
|
@ -159,6 +159,19 @@ pub enum StackPopCleanup {
|
|||
Root { cleanup: bool },
|
||||
}
|
||||
|
||||
/// Return type of [`InterpCx::pop_stack_frame`].
|
||||
pub struct StackPopInfo<'tcx, Prov: Provenance> {
|
||||
/// Additional information about the action to be performed when returning from the popped
|
||||
/// stack frame.
|
||||
pub return_action: ReturnAction,
|
||||
|
||||
/// [`return_to_block`](Frame::return_to_block) of the popped stack frame.
|
||||
pub return_to_block: StackPopCleanup,
|
||||
|
||||
/// [`return_place`](Frame::return_place) of the popped stack frame.
|
||||
pub return_place: MPlaceTy<'tcx, Prov>,
|
||||
}
|
||||
|
||||
/// State of a local variable including a memoized layout
|
||||
#[derive(Clone)]
|
||||
pub struct LocalState<'tcx, Prov: Provenance = CtfeProvenance> {
|
||||
|
|
@ -803,14 +816,31 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
return_to_block: StackPopCleanup,
|
||||
) -> InterpResult<'tcx> {
|
||||
trace!("body: {:#?}", body);
|
||||
|
||||
// First push a stack frame so we have access to the local args
|
||||
self.push_new_stack_frame(instance, body, return_to_block, return_place.clone())?;
|
||||
|
||||
self.after_stack_frame_push(instance, body)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Creates a new stack frame, initializes it and pushes it onto the stack.
|
||||
/// A private helper for [`push_stack_frame`](InterpCx::push_stack_frame).
|
||||
fn push_new_stack_frame(
|
||||
&mut self,
|
||||
instance: ty::Instance<'tcx>,
|
||||
body: &'tcx mir::Body<'tcx>,
|
||||
return_to_block: StackPopCleanup,
|
||||
return_place: MPlaceTy<'tcx, M::Provenance>,
|
||||
) -> InterpResult<'tcx> {
|
||||
let dead_local = LocalState { value: LocalValue::Dead, layout: Cell::new(None) };
|
||||
let locals = IndexVec::from_elem(dead_local, &body.local_decls);
|
||||
// First push a stack frame so we have access to the local args
|
||||
let pre_frame = Frame {
|
||||
body,
|
||||
loc: Right(body.span), // Span used for errors caused during preamble.
|
||||
return_to_block,
|
||||
return_place: return_place.clone(),
|
||||
return_place,
|
||||
locals,
|
||||
instance,
|
||||
tracing_span: SpanGuard::new(),
|
||||
|
|
@ -819,6 +849,15 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
let frame = M::init_frame(self, pre_frame)?;
|
||||
self.stack_mut().push(frame);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A private helper for [`push_stack_frame`](InterpCx::push_stack_frame).
|
||||
fn after_stack_frame_push(
|
||||
&mut self,
|
||||
instance: ty::Instance<'tcx>,
|
||||
body: &'tcx mir::Body<'tcx>,
|
||||
) -> InterpResult<'tcx> {
|
||||
// Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
|
||||
for &const_ in &body.required_consts {
|
||||
let c =
|
||||
|
|
@ -839,6 +878,61 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Pops a stack frame from the stack and returns some information about it.
|
||||
///
|
||||
/// This also deallocates locals, if necessary.
|
||||
///
|
||||
/// [`M::before_stack_pop`] should be called before calling this function.
|
||||
/// [`M::after_stack_pop`] is called by this function automatically.
|
||||
///
|
||||
/// [`M::before_stack_pop`]: Machine::before_stack_pop
|
||||
/// [`M::after_stack_pop`]: Machine::after_stack_pop
|
||||
pub fn pop_stack_frame(
|
||||
&mut self,
|
||||
unwinding: bool,
|
||||
) -> InterpResult<'tcx, StackPopInfo<'tcx, M::Provenance>> {
|
||||
let cleanup = self.cleanup_current_frame_locals()?;
|
||||
|
||||
let frame =
|
||||
self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
|
||||
|
||||
let return_to_block = frame.return_to_block;
|
||||
let return_place = frame.return_place.clone();
|
||||
|
||||
let return_action;
|
||||
if cleanup {
|
||||
return_action = M::after_stack_pop(self, frame, unwinding)?;
|
||||
assert_ne!(return_action, ReturnAction::NoCleanup);
|
||||
} else {
|
||||
return_action = ReturnAction::NoCleanup;
|
||||
};
|
||||
|
||||
Ok(StackPopInfo { return_action, return_to_block, return_place })
|
||||
}
|
||||
|
||||
/// A private helper for [`pop_stack_frame`](InterpCx::pop_stack_frame).
|
||||
/// Returns `true` if cleanup has been done, `false` otherwise.
|
||||
fn cleanup_current_frame_locals(&mut self) -> InterpResult<'tcx, bool> {
|
||||
// Cleanup: deallocate locals.
|
||||
// Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
|
||||
// We do this while the frame is still on the stack, so errors point to the callee.
|
||||
let return_to_block = self.frame().return_to_block;
|
||||
let cleanup = match return_to_block {
|
||||
StackPopCleanup::Goto { .. } => true,
|
||||
StackPopCleanup::Root { cleanup, .. } => cleanup,
|
||||
};
|
||||
|
||||
if cleanup {
|
||||
// We need to take the locals out, since we need to mutate while iterating.
|
||||
let locals = mem::take(&mut self.frame_mut().locals);
|
||||
for local in &locals {
|
||||
self.deallocate_local(local.value)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(cleanup)
|
||||
}
|
||||
|
||||
/// Jump to the given block.
|
||||
#[inline]
|
||||
pub fn go_to_block(&mut self, target: mir::BasicBlock) {
|
||||
|
|
@ -886,7 +980,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
}
|
||||
|
||||
/// Pops the current frame from the stack, deallocating the
|
||||
/// memory for allocated locals.
|
||||
/// memory for allocated locals, and jumps to an appropriate place.
|
||||
///
|
||||
/// If `unwinding` is `false`, then we are performing a normal return
|
||||
/// from a function. In this case, we jump back into the frame of the caller,
|
||||
|
|
@ -899,7 +993,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
/// The cleanup block ends with a special `Resume` terminator, which will
|
||||
/// cause us to continue unwinding.
|
||||
#[instrument(skip(self), level = "debug")]
|
||||
pub(super) fn pop_stack_frame(&mut self, unwinding: bool) -> InterpResult<'tcx> {
|
||||
pub(super) fn return_from_current_stack_frame(
|
||||
&mut self,
|
||||
unwinding: bool,
|
||||
) -> InterpResult<'tcx> {
|
||||
info!(
|
||||
"popping stack frame ({})",
|
||||
if unwinding { "during unwinding" } else { "returning from function" }
|
||||
|
|
@ -947,45 +1044,31 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
Ok(())
|
||||
};
|
||||
|
||||
// Cleanup: deallocate locals.
|
||||
// Usually we want to clean up (deallocate locals), but in a few rare cases we don't.
|
||||
// We do this while the frame is still on the stack, so errors point to the callee.
|
||||
let return_to_block = self.frame().return_to_block;
|
||||
let cleanup = match return_to_block {
|
||||
StackPopCleanup::Goto { .. } => true,
|
||||
StackPopCleanup::Root { cleanup, .. } => cleanup,
|
||||
};
|
||||
if cleanup {
|
||||
// We need to take the locals out, since we need to mutate while iterating.
|
||||
let locals = mem::take(&mut self.frame_mut().locals);
|
||||
for local in &locals {
|
||||
self.deallocate_local(local.value)?;
|
||||
}
|
||||
}
|
||||
|
||||
// All right, now it is time to actually pop the frame.
|
||||
// Note that its locals are gone already, but that's fine.
|
||||
let frame =
|
||||
self.stack_mut().pop().expect("tried to pop a stack frame, but there were none");
|
||||
let stack_pop_info = self.pop_stack_frame(unwinding)?;
|
||||
|
||||
// Report error from return value copy, if any.
|
||||
copy_ret_result?;
|
||||
|
||||
// If we are not doing cleanup, also skip everything else.
|
||||
if !cleanup {
|
||||
assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
|
||||
assert!(!unwinding, "tried to skip cleanup during unwinding");
|
||||
// Skip machine hook.
|
||||
return Ok(());
|
||||
}
|
||||
if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump {
|
||||
// The hook already did everything.
|
||||
return Ok(());
|
||||
match stack_pop_info.return_action {
|
||||
ReturnAction::Normal => {}
|
||||
ReturnAction::NoJump => {
|
||||
// The hook already did everything.
|
||||
return Ok(());
|
||||
}
|
||||
ReturnAction::NoCleanup => {
|
||||
// If we are not doing cleanup, also skip everything else.
|
||||
assert!(self.stack().is_empty(), "only the topmost frame should ever be leaked");
|
||||
assert!(!unwinding, "tried to skip cleanup during unwinding");
|
||||
// Skip machine hook.
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
// Normal return, figure out where to jump.
|
||||
if unwinding {
|
||||
// Follow the unwind edge.
|
||||
let unwind = match return_to_block {
|
||||
let unwind = match stack_pop_info.return_to_block {
|
||||
StackPopCleanup::Goto { unwind, .. } => unwind,
|
||||
StackPopCleanup::Root { .. } => {
|
||||
panic!("encountered StackPopCleanup::Root when unwinding!")
|
||||
|
|
@ -995,7 +1078,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
self.unwind_to_block(unwind)
|
||||
} else {
|
||||
// Follow the normal return edge.
|
||||
match return_to_block {
|
||||
match stack_pop_info.return_to_block {
|
||||
StackPopCleanup::Goto { ret, .. } => self.return_to_block(ret),
|
||||
StackPopCleanup::Root { .. } => {
|
||||
assert!(
|
||||
|
|
|
|||
|
|
@ -23,10 +23,11 @@ use super::{
|
|||
MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance,
|
||||
};
|
||||
|
||||
/// Data returned by Machine::stack_pop,
|
||||
/// to provide further control over the popping of the stack frame
|
||||
/// Data returned by [`Machine::after_stack_pop`], and consumed by
|
||||
/// [`InterpCx::return_from_current_stack_frame`] to determine what actions should be done when
|
||||
/// returning from a stack frame.
|
||||
#[derive(Eq, PartialEq, Debug, Copy, Clone)]
|
||||
pub enum StackPopJump {
|
||||
pub enum ReturnAction {
|
||||
/// Indicates that no special handling should be
|
||||
/// done - we'll either return normally or unwind
|
||||
/// based on the terminator for the function
|
||||
|
|
@ -36,6 +37,9 @@ pub enum StackPopJump {
|
|||
/// Indicates that we should *not* jump to the return/unwind address, as the callback already
|
||||
/// took care of everything.
|
||||
NoJump,
|
||||
|
||||
/// Returned by [`InterpCx::pop_stack_frame`] when no cleanup should be done.
|
||||
NoCleanup,
|
||||
}
|
||||
|
||||
/// Whether this kind of memory is allowed to leak
|
||||
|
|
@ -522,10 +526,10 @@ pub trait Machine<'tcx>: Sized {
|
|||
_ecx: &mut InterpCx<'tcx, Self>,
|
||||
_frame: Frame<'tcx, Self::Provenance, Self::FrameExtra>,
|
||||
unwinding: bool,
|
||||
) -> InterpResult<'tcx, StackPopJump> {
|
||||
) -> InterpResult<'tcx, ReturnAction> {
|
||||
// By default, we do not support unwinding from panics
|
||||
assert!(!unwinding);
|
||||
Ok(StackPopJump::Normal)
|
||||
Ok(ReturnAction::Normal)
|
||||
}
|
||||
|
||||
/// Called immediately after actual memory was allocated for a local
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ pub use self::intern::{
|
|||
intern_const_alloc_for_constprop, intern_const_alloc_recursive, HasStaticRootDefId, InternKind,
|
||||
InternResult,
|
||||
};
|
||||
pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, StackPopJump};
|
||||
pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, ReturnAction};
|
||||
pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind};
|
||||
pub use self::operand::{ImmTy, Immediate, OpTy, Readable};
|
||||
pub use self::place::{MPlaceTy, MemPlaceMeta, PlaceTy, Writeable};
|
||||
|
|
|
|||
|
|
@ -32,7 +32,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
// We are unwinding and this fn has no cleanup code.
|
||||
// Just go on unwinding.
|
||||
trace!("unwinding: skipping frame");
|
||||
self.pop_stack_frame(/* unwinding */ true)?;
|
||||
self.return_from_current_stack_frame(/* unwinding */ true)?;
|
||||
return Ok(true);
|
||||
};
|
||||
let basic_block = &self.body().basic_blocks[loc.block];
|
||||
|
|
|
|||
|
|
@ -4,9 +4,8 @@ use either::Either;
|
|||
use rustc_middle::ty::TyCtxt;
|
||||
use tracing::trace;
|
||||
|
||||
use rustc_middle::span_bug;
|
||||
use rustc_middle::{
|
||||
mir,
|
||||
bug, mir, span_bug,
|
||||
ty::{
|
||||
self,
|
||||
layout::{FnAbiOf, IntegerExt, LayoutOf, TyAndLayout},
|
||||
|
|
@ -26,7 +25,10 @@ use super::{
|
|||
InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, Projectable, Provenance, Scalar,
|
||||
StackPopCleanup,
|
||||
};
|
||||
use crate::fluent_generated as fluent;
|
||||
use crate::{
|
||||
fluent_generated as fluent,
|
||||
interpret::{eval_context::StackPopInfo, ReturnAction},
|
||||
};
|
||||
|
||||
/// An argment passed to a function.
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -47,6 +49,15 @@ impl<'tcx, Prov: Provenance> FnArg<'tcx, Prov> {
|
|||
}
|
||||
}
|
||||
|
||||
struct EvaluatedCalleeAndArgs<'tcx, M: Machine<'tcx>> {
|
||||
callee: FnVal<'tcx, M::ExtraFnVal>,
|
||||
args: Vec<FnArg<'tcx, M::Provenance>>,
|
||||
fn_sig: ty::FnSig<'tcx>,
|
||||
fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
|
||||
/// True if the function is marked as `#[track_caller]` ([`ty::InstanceKind::requires_caller_location`])
|
||||
with_caller_location: bool,
|
||||
}
|
||||
|
||||
impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
||||
/// Make a copy of the given fn_arg. Any `InPlace` are degenerated to copies, no protection of the
|
||||
/// original memory occurs.
|
||||
|
|
@ -84,7 +95,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
use rustc_middle::mir::TerminatorKind::*;
|
||||
match terminator.kind {
|
||||
Return => {
|
||||
self.pop_stack_frame(/* unwinding */ false)?
|
||||
self.return_from_current_stack_frame(/* unwinding */ false)?
|
||||
}
|
||||
|
||||
Goto { target } => self.go_to_block(target),
|
||||
|
|
@ -124,40 +135,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
} => {
|
||||
let old_stack = self.frame_idx();
|
||||
let old_loc = self.frame().loc;
|
||||
let func = self.eval_operand(func, None)?;
|
||||
let args = self.eval_fn_call_arguments(args)?;
|
||||
|
||||
let fn_sig_binder = func.layout.ty.fn_sig(*self.tcx);
|
||||
let fn_sig =
|
||||
self.tcx.normalize_erasing_late_bound_regions(self.param_env, fn_sig_binder);
|
||||
let extra_args = &args[fn_sig.inputs().len()..];
|
||||
let extra_args =
|
||||
self.tcx.mk_type_list_from_iter(extra_args.iter().map(|arg| arg.layout().ty));
|
||||
|
||||
let (fn_val, fn_abi, with_caller_location) = match *func.layout.ty.kind() {
|
||||
ty::FnPtr(_sig) => {
|
||||
let fn_ptr = self.read_pointer(&func)?;
|
||||
let fn_val = self.get_ptr_fn(fn_ptr)?;
|
||||
(fn_val, self.fn_abi_of_fn_ptr(fn_sig_binder, extra_args)?, false)
|
||||
}
|
||||
ty::FnDef(def_id, args) => {
|
||||
let instance = self.resolve(def_id, args)?;
|
||||
(
|
||||
FnVal::Instance(instance),
|
||||
self.fn_abi_of_instance(instance, extra_args)?,
|
||||
instance.def.requires_caller_location(*self.tcx),
|
||||
)
|
||||
}
|
||||
_ => span_bug!(
|
||||
terminator.source_info.span,
|
||||
"invalid callee of type {}",
|
||||
func.layout.ty
|
||||
),
|
||||
};
|
||||
let EvaluatedCalleeAndArgs { callee, args, fn_sig, fn_abi, with_caller_location } =
|
||||
self.eval_callee_and_args(terminator, func, args)?;
|
||||
|
||||
let destination = self.force_allocation(&self.eval_place(destination)?)?;
|
||||
self.eval_fn_call(
|
||||
fn_val,
|
||||
callee,
|
||||
(fn_sig.abi, fn_abi),
|
||||
&args,
|
||||
with_caller_location,
|
||||
|
|
@ -172,6 +156,22 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
}
|
||||
}
|
||||
|
||||
TailCall { ref func, ref args, fn_span: _ } => {
|
||||
let old_frame_idx = self.frame_idx();
|
||||
|
||||
let EvaluatedCalleeAndArgs { callee, args, fn_sig, fn_abi, with_caller_location } =
|
||||
self.eval_callee_and_args(terminator, func, args)?;
|
||||
|
||||
self.eval_fn_tail_call(callee, (fn_sig.abi, fn_abi), &args, with_caller_location)?;
|
||||
|
||||
if self.frame_idx() != old_frame_idx {
|
||||
span_bug!(
|
||||
terminator.source_info.span,
|
||||
"evaluating this tail call pushed a new stack frame"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Drop { place, target, unwind, replace: _ } => {
|
||||
let place = self.eval_place(place)?;
|
||||
let instance = Instance::resolve_drop_in_place(*self.tcx, place.layout.ty);
|
||||
|
|
@ -209,7 +209,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
trace!("unwinding: resuming from cleanup");
|
||||
// By definition, a Resume terminator means
|
||||
// that we're unwinding
|
||||
self.pop_stack_frame(/* unwinding */ true)?;
|
||||
self.return_from_current_stack_frame(/* unwinding */ true)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
|
|
@ -514,6 +514,45 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
Ok(())
|
||||
}
|
||||
|
||||
/// Shared part of `Call` and `TailCall` implementation — finding and evaluating all the
|
||||
/// necessary information about callee and arguments to make a call.
|
||||
fn eval_callee_and_args(
|
||||
&self,
|
||||
terminator: &mir::Terminator<'tcx>,
|
||||
func: &mir::Operand<'tcx>,
|
||||
args: &[Spanned<mir::Operand<'tcx>>],
|
||||
) -> InterpResult<'tcx, EvaluatedCalleeAndArgs<'tcx, M>> {
|
||||
let func = self.eval_operand(func, None)?;
|
||||
let args = self.eval_fn_call_arguments(args)?;
|
||||
|
||||
let fn_sig_binder = func.layout.ty.fn_sig(*self.tcx);
|
||||
let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, fn_sig_binder);
|
||||
let extra_args = &args[fn_sig.inputs().len()..];
|
||||
let extra_args =
|
||||
self.tcx.mk_type_list_from_iter(extra_args.iter().map(|arg| arg.layout().ty));
|
||||
|
||||
let (callee, fn_abi, with_caller_location) = match *func.layout.ty.kind() {
|
||||
ty::FnPtr(_sig) => {
|
||||
let fn_ptr = self.read_pointer(&func)?;
|
||||
let fn_val = self.get_ptr_fn(fn_ptr)?;
|
||||
(fn_val, self.fn_abi_of_fn_ptr(fn_sig_binder, extra_args)?, false)
|
||||
}
|
||||
ty::FnDef(def_id, args) => {
|
||||
let instance = self.resolve(def_id, args)?;
|
||||
(
|
||||
FnVal::Instance(instance),
|
||||
self.fn_abi_of_instance(instance, extra_args)?,
|
||||
instance.def.requires_caller_location(*self.tcx),
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
span_bug!(terminator.source_info.span, "invalid callee of type {}", func.layout.ty)
|
||||
}
|
||||
};
|
||||
|
||||
Ok(EvaluatedCalleeAndArgs { callee, args, fn_sig, fn_abi, with_caller_location })
|
||||
}
|
||||
|
||||
/// Call this function -- pushing the stack frame and initializing the arguments.
|
||||
///
|
||||
/// `caller_fn_abi` is used to determine if all the arguments are passed the proper way.
|
||||
|
|
@ -924,6 +963,49 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
|
|||
}
|
||||
}
|
||||
|
||||
pub(crate) fn eval_fn_tail_call(
|
||||
&mut self,
|
||||
fn_val: FnVal<'tcx, M::ExtraFnVal>,
|
||||
(caller_abi, caller_fn_abi): (Abi, &FnAbi<'tcx, Ty<'tcx>>),
|
||||
args: &[FnArg<'tcx, M::Provenance>],
|
||||
with_caller_location: bool,
|
||||
) -> InterpResult<'tcx> {
|
||||
trace!("eval_fn_call: {:#?}", fn_val);
|
||||
|
||||
// This is the "canonical" implementation of tails calls,
|
||||
// a pop of the current stack frame, followed by a normal call
|
||||
// which pushes a new stack frame, with the return address from
|
||||
// the popped stack frame.
|
||||
//
|
||||
// Note that we are using `pop_stack_frame` and not `return_from_current_stack_frame`,
|
||||
// as the latter "executes" the goto to the return block, but we don't want to,
|
||||
// only the tail called function should return to the current return block.
|
||||
M::before_stack_pop(self, self.frame())?;
|
||||
|
||||
let StackPopInfo { return_action, return_to_block, return_place } =
|
||||
self.pop_stack_frame(false)?;
|
||||
|
||||
assert_eq!(return_action, ReturnAction::Normal);
|
||||
|
||||
let StackPopCleanup::Goto { ret, unwind } = return_to_block else {
|
||||
bug!("can't tailcall as root");
|
||||
};
|
||||
|
||||
// FIXME(explicit_tail_calls):
|
||||
// we should check if both caller&callee can/n't unwind,
|
||||
// see <https://github.com/rust-lang/rust/pull/113128#issuecomment-1614979803>
|
||||
|
||||
self.eval_fn_call(
|
||||
fn_val,
|
||||
(caller_abi, caller_fn_abi),
|
||||
args,
|
||||
with_caller_location,
|
||||
&return_place,
|
||||
ret,
|
||||
unwind,
|
||||
)
|
||||
}
|
||||
|
||||
fn check_fn_target_features(&self, instance: ty::Instance<'tcx>) -> InterpResult<'tcx, ()> {
|
||||
// Calling functions with `#[target_feature]` is not unsafe on WASM, see #84988
|
||||
let attrs = self.tcx.codegen_fn_attrs(instance.def_id());
|
||||
|
|
|
|||
|
|
@ -298,15 +298,21 @@ impl IntoDiagArg for hir::def::Namespace {
|
|||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct DiagSymbolList(Vec<Symbol>);
|
||||
pub struct DiagSymbolList<S = Symbol>(Vec<S>);
|
||||
|
||||
impl From<Vec<Symbol>> for DiagSymbolList {
|
||||
fn from(v: Vec<Symbol>) -> Self {
|
||||
impl<S> From<Vec<S>> for DiagSymbolList<S> {
|
||||
fn from(v: Vec<S>) -> Self {
|
||||
DiagSymbolList(v)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoDiagArg for DiagSymbolList {
|
||||
impl<S> FromIterator<S> for DiagSymbolList<S> {
|
||||
fn from_iter<T: IntoIterator<Item = S>>(iter: T) -> Self {
|
||||
iter.into_iter().collect::<Vec<_>>().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: std::fmt::Display> IntoDiagArg for DiagSymbolList<S> {
|
||||
fn into_diag_arg(self) -> DiagArgValue {
|
||||
DiagArgValue::StrListSepByAnd(
|
||||
self.0.into_iter().map(|sym| Cow::Owned(format!("`{sym}`"))).collect(),
|
||||
|
|
|
|||
|
|
@ -172,7 +172,7 @@ impl<'a> StripUnconfigured<'a> {
|
|||
fn configure_tokens(&self, stream: &AttrTokenStream) -> AttrTokenStream {
|
||||
fn can_skip(stream: &AttrTokenStream) -> bool {
|
||||
stream.0.iter().all(|tree| match tree {
|
||||
AttrTokenTree::Attributes(_) => false,
|
||||
AttrTokenTree::AttrsTarget(_) => false,
|
||||
AttrTokenTree::Token(..) => true,
|
||||
AttrTokenTree::Delimited(.., inner) => can_skip(inner),
|
||||
})
|
||||
|
|
@ -185,22 +185,22 @@ impl<'a> StripUnconfigured<'a> {
|
|||
let trees: Vec<_> = stream
|
||||
.0
|
||||
.iter()
|
||||
.flat_map(|tree| match tree.clone() {
|
||||
AttrTokenTree::Attributes(mut data) => {
|
||||
data.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
|
||||
.filter_map(|tree| match tree.clone() {
|
||||
AttrTokenTree::AttrsTarget(mut target) => {
|
||||
target.attrs.flat_map_in_place(|attr| self.process_cfg_attr(&attr));
|
||||
|
||||
if self.in_cfg(&data.attrs) {
|
||||
data.tokens = LazyAttrTokenStream::new(
|
||||
self.configure_tokens(&data.tokens.to_attr_token_stream()),
|
||||
if self.in_cfg(&target.attrs) {
|
||||
target.tokens = LazyAttrTokenStream::new(
|
||||
self.configure_tokens(&target.tokens.to_attr_token_stream()),
|
||||
);
|
||||
Some(AttrTokenTree::Attributes(data)).into_iter()
|
||||
Some(AttrTokenTree::AttrsTarget(target))
|
||||
} else {
|
||||
None.into_iter()
|
||||
None
|
||||
}
|
||||
}
|
||||
AttrTokenTree::Delimited(sp, spacing, delim, mut inner) => {
|
||||
inner = self.configure_tokens(&inner);
|
||||
Some(AttrTokenTree::Delimited(sp, spacing, delim, inner)).into_iter()
|
||||
Some(AttrTokenTree::Delimited(sp, spacing, delim, inner))
|
||||
}
|
||||
AttrTokenTree::Token(
|
||||
Token {
|
||||
|
|
@ -220,9 +220,7 @@ impl<'a> StripUnconfigured<'a> {
|
|||
) => {
|
||||
panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tree);
|
||||
}
|
||||
AttrTokenTree::Token(token, spacing) => {
|
||||
Some(AttrTokenTree::Token(token, spacing)).into_iter()
|
||||
}
|
||||
AttrTokenTree::Token(token, spacing) => Some(AttrTokenTree::Token(token, spacing)),
|
||||
})
|
||||
.collect();
|
||||
AttrTokenStream::new(trees)
|
||||
|
|
@ -294,7 +292,7 @@ impl<'a> StripUnconfigured<'a> {
|
|||
attr: &Attribute,
|
||||
(item, item_span): (ast::AttrItem, Span),
|
||||
) -> Attribute {
|
||||
let orig_tokens = attr.tokens();
|
||||
let orig_tokens = attr.get_tokens();
|
||||
|
||||
// We are taking an attribute of the form `#[cfg_attr(pred, attr)]`
|
||||
// and producing an attribute of the form `#[attr]`. We
|
||||
|
|
@ -310,12 +308,11 @@ impl<'a> StripUnconfigured<'a> {
|
|||
else {
|
||||
panic!("Bad tokens for attribute {attr:?}");
|
||||
};
|
||||
let pound_span = pound_token.span;
|
||||
|
||||
// We don't really have a good span to use for the synthesized `[]`
|
||||
// in `#[attr]`, so just use the span of the `#` token.
|
||||
let bracket_group = AttrTokenTree::Delimited(
|
||||
DelimSpan::from_single(pound_span),
|
||||
DelimSpan::from_single(pound_token.span),
|
||||
DelimSpacing::new(Spacing::JointHidden, Spacing::Alone),
|
||||
Delimiter::Bracket,
|
||||
item.tokens
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use rustc_ast::token::{self, Delimiter, IdentIsRaw};
|
||||
use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, Token, TokenKind};
|
||||
use rustc_ast::tokenstream::{RefTokenTreeCursor, TokenStream, TokenTree};
|
||||
use rustc_ast::{LitIntType, LitKind};
|
||||
use rustc_ast_pretty::pprust;
|
||||
|
|
@ -6,9 +6,10 @@ use rustc_errors::{Applicability, PResult};
|
|||
use rustc_macros::{Decodable, Encodable};
|
||||
use rustc_session::parse::ParseSess;
|
||||
use rustc_span::symbol::Ident;
|
||||
use rustc_span::Span;
|
||||
use rustc_span::{Span, Symbol};
|
||||
|
||||
pub(crate) const RAW_IDENT_ERR: &str = "`${concat(..)}` currently does not support raw identifiers";
|
||||
pub(crate) const UNSUPPORTED_CONCAT_ELEM_ERR: &str = "expected identifier or string literal";
|
||||
|
||||
/// A meta-variable expression, for expansions based on properties of meta-variables.
|
||||
#[derive(Debug, PartialEq, Encodable, Decodable)]
|
||||
|
|
@ -51,11 +52,26 @@ impl MetaVarExpr {
|
|||
let mut result = Vec::new();
|
||||
loop {
|
||||
let is_var = try_eat_dollar(&mut iter);
|
||||
let element_ident = parse_ident(&mut iter, psess, outer_span)?;
|
||||
let token = parse_token(&mut iter, psess, outer_span)?;
|
||||
let element = if is_var {
|
||||
MetaVarExprConcatElem::Var(element_ident)
|
||||
MetaVarExprConcatElem::Var(parse_ident_from_token(psess, token)?)
|
||||
} else if let TokenKind::Literal(Lit {
|
||||
kind: token::LitKind::Str,
|
||||
symbol,
|
||||
suffix: None,
|
||||
}) = token.kind
|
||||
{
|
||||
MetaVarExprConcatElem::Literal(symbol)
|
||||
} else {
|
||||
MetaVarExprConcatElem::Ident(element_ident)
|
||||
match parse_ident_from_token(psess, token) {
|
||||
Err(err) => {
|
||||
err.cancel();
|
||||
return Err(psess
|
||||
.dcx()
|
||||
.struct_span_err(token.span, UNSUPPORTED_CONCAT_ELEM_ERR));
|
||||
}
|
||||
Ok(elem) => MetaVarExprConcatElem::Ident(elem),
|
||||
}
|
||||
};
|
||||
result.push(element);
|
||||
if iter.look_ahead(0).is_none() {
|
||||
|
|
@ -105,11 +121,13 @@ impl MetaVarExpr {
|
|||
|
||||
#[derive(Debug, Decodable, Encodable, PartialEq)]
|
||||
pub(crate) enum MetaVarExprConcatElem {
|
||||
/// There is NO preceding dollar sign, which means that this identifier should be interpreted
|
||||
/// as a literal.
|
||||
/// Identifier WITHOUT a preceding dollar sign, which means that this identifier should be
|
||||
/// interpreted as a literal.
|
||||
Ident(Ident),
|
||||
/// There is a preceding dollar sign, which means that this identifier should be expanded
|
||||
/// and interpreted as a variable.
|
||||
/// For example, a number or a string.
|
||||
Literal(Symbol),
|
||||
/// Identifier WITH a preceding dollar sign, which means that this identifier should be
|
||||
/// expanded and interpreted as a variable.
|
||||
Var(Ident),
|
||||
}
|
||||
|
||||
|
|
@ -158,7 +176,7 @@ fn parse_depth<'psess>(
|
|||
span: Span,
|
||||
) -> PResult<'psess, usize> {
|
||||
let Some(tt) = iter.next() else { return Ok(0) };
|
||||
let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else {
|
||||
let TokenTree::Token(Token { kind: TokenKind::Literal(lit), .. }, _) = tt else {
|
||||
return Err(psess
|
||||
.dcx()
|
||||
.struct_span_err(span, "meta-variable expression depth must be a literal"));
|
||||
|
|
@ -180,12 +198,14 @@ fn parse_ident<'psess>(
|
|||
psess: &'psess ParseSess,
|
||||
fallback_span: Span,
|
||||
) -> PResult<'psess, Ident> {
|
||||
let Some(tt) = iter.next() else {
|
||||
return Err(psess.dcx().struct_span_err(fallback_span, "expected identifier"));
|
||||
};
|
||||
let TokenTree::Token(token, _) = tt else {
|
||||
return Err(psess.dcx().struct_span_err(tt.span(), "expected identifier"));
|
||||
};
|
||||
let token = parse_token(iter, psess, fallback_span)?;
|
||||
parse_ident_from_token(psess, token)
|
||||
}
|
||||
|
||||
fn parse_ident_from_token<'psess>(
|
||||
psess: &'psess ParseSess,
|
||||
token: &Token,
|
||||
) -> PResult<'psess, Ident> {
|
||||
if let Some((elem, is_raw)) = token.ident() {
|
||||
if let IdentIsRaw::Yes = is_raw {
|
||||
return Err(psess.dcx().struct_span_err(elem.span, RAW_IDENT_ERR));
|
||||
|
|
@ -205,10 +225,24 @@ fn parse_ident<'psess>(
|
|||
Err(err)
|
||||
}
|
||||
|
||||
fn parse_token<'psess, 't>(
|
||||
iter: &mut RefTokenTreeCursor<'t>,
|
||||
psess: &'psess ParseSess,
|
||||
fallback_span: Span,
|
||||
) -> PResult<'psess, &'t Token> {
|
||||
let Some(tt) = iter.next() else {
|
||||
return Err(psess.dcx().struct_span_err(fallback_span, UNSUPPORTED_CONCAT_ELEM_ERR));
|
||||
};
|
||||
let TokenTree::Token(token, _) = tt else {
|
||||
return Err(psess.dcx().struct_span_err(tt.span(), UNSUPPORTED_CONCAT_ELEM_ERR));
|
||||
};
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
/// Tries to move the iterator forward returning `true` if there is a comma. If not, then the
|
||||
/// iterator is not modified and the result is `false`.
|
||||
fn try_eat_comma(iter: &mut RefTokenTreeCursor<'_>) -> bool {
|
||||
if let Some(TokenTree::Token(token::Token { kind: token::Comma, .. }, _)) = iter.look_ahead(0) {
|
||||
if let Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) = iter.look_ahead(0) {
|
||||
let _ = iter.next();
|
||||
return true;
|
||||
}
|
||||
|
|
@ -218,8 +252,7 @@ fn try_eat_comma(iter: &mut RefTokenTreeCursor<'_>) -> bool {
|
|||
/// Tries to move the iterator forward returning `true` if there is a dollar sign. If not, then the
|
||||
/// iterator is not modified and the result is `false`.
|
||||
fn try_eat_dollar(iter: &mut RefTokenTreeCursor<'_>) -> bool {
|
||||
if let Some(TokenTree::Token(token::Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0)
|
||||
{
|
||||
if let Some(TokenTree::Token(Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0) {
|
||||
let _ = iter.next();
|
||||
return true;
|
||||
}
|
||||
|
|
@ -232,8 +265,7 @@ fn eat_dollar<'psess>(
|
|||
psess: &'psess ParseSess,
|
||||
span: Span,
|
||||
) -> PResult<'psess, ()> {
|
||||
if let Some(TokenTree::Token(token::Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0)
|
||||
{
|
||||
if let Some(TokenTree::Token(Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0) {
|
||||
let _ = iter.next();
|
||||
return Ok(());
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,11 +11,13 @@ use rustc_ast::token::{self, Delimiter, Token, TokenKind};
|
|||
use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree};
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_errors::{pluralize, Diag, DiagCtxtHandle, PResult};
|
||||
use rustc_parse::lexer::nfc_normalize;
|
||||
use rustc_parse::parser::ParseNtResult;
|
||||
use rustc_session::parse::ParseSess;
|
||||
use rustc_session::parse::SymbolGallery;
|
||||
use rustc_span::hygiene::{LocalExpnId, Transparency};
|
||||
use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent};
|
||||
use rustc_span::{with_metavar_spans, Span, Symbol, SyntaxContext};
|
||||
use rustc_span::{with_metavar_spans, Span, SyntaxContext};
|
||||
use smallvec::{smallvec, SmallVec};
|
||||
use std::mem;
|
||||
|
||||
|
|
@ -312,7 +314,16 @@ pub(super) fn transcribe<'a>(
|
|||
|
||||
// Replace meta-variable expressions with the result of their expansion.
|
||||
mbe::TokenTree::MetaVarExpr(sp, expr) => {
|
||||
transcribe_metavar_expr(dcx, expr, interp, &mut marker, &repeats, &mut result, sp)?;
|
||||
transcribe_metavar_expr(
|
||||
dcx,
|
||||
expr,
|
||||
interp,
|
||||
&mut marker,
|
||||
&repeats,
|
||||
&mut result,
|
||||
sp,
|
||||
&psess.symbol_gallery,
|
||||
)?;
|
||||
}
|
||||
|
||||
// If we are entering a new delimiter, we push its contents to the `stack` to be
|
||||
|
|
@ -669,6 +680,7 @@ fn transcribe_metavar_expr<'a>(
|
|||
repeats: &[(usize, usize)],
|
||||
result: &mut Vec<TokenTree>,
|
||||
sp: &DelimSpan,
|
||||
symbol_gallery: &SymbolGallery,
|
||||
) -> PResult<'a, ()> {
|
||||
let mut visited_span = || {
|
||||
let mut span = sp.entire();
|
||||
|
|
@ -680,16 +692,26 @@ fn transcribe_metavar_expr<'a>(
|
|||
let mut concatenated = String::new();
|
||||
for element in elements.into_iter() {
|
||||
let string = match element {
|
||||
MetaVarExprConcatElem::Ident(ident) => ident.to_string(),
|
||||
MetaVarExprConcatElem::Var(ident) => extract_ident(dcx, *ident, interp)?,
|
||||
MetaVarExprConcatElem::Ident(elem) => elem.to_string(),
|
||||
MetaVarExprConcatElem::Literal(elem) => elem.as_str().into(),
|
||||
MetaVarExprConcatElem::Var(elem) => extract_ident(dcx, *elem, interp)?,
|
||||
};
|
||||
concatenated.push_str(&string);
|
||||
}
|
||||
let symbol = nfc_normalize(&concatenated);
|
||||
let concatenated_span = visited_span();
|
||||
if !rustc_lexer::is_ident(symbol.as_str()) {
|
||||
return Err(dcx.struct_span_err(
|
||||
concatenated_span,
|
||||
"`${concat(..)}` is not generating a valid identifier",
|
||||
));
|
||||
}
|
||||
symbol_gallery.insert(symbol, concatenated_span);
|
||||
// The current implementation marks the span as coming from the macro regardless of
|
||||
// contexts of the concatenated identifiers but this behavior may change in the
|
||||
// future.
|
||||
result.push(TokenTree::Token(
|
||||
Token::from_ast_ident(Ident::new(Symbol::intern(&concatenated), visited_span())),
|
||||
Token::from_ast_ident(Ident::new(symbol, concatenated_span)),
|
||||
Spacing::Alone,
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@ use rustc_middle::ty::{
|
|||
use rustc_middle::ty::{GenericParamDefKind, TyCtxt};
|
||||
use rustc_middle::{bug, span_bug};
|
||||
use rustc_span::Span;
|
||||
use rustc_trait_selection::infer::InferCtxtExt;
|
||||
use rustc_trait_selection::regions::InferCtxtRegionExt;
|
||||
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
|
||||
use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
|
||||
|
|
|
|||
|
|
@ -26,15 +26,12 @@ fn equate_intrinsic_type<'tcx>(
|
|||
n_cts: usize,
|
||||
sig: ty::PolyFnSig<'tcx>,
|
||||
) {
|
||||
let (own_counts, span) = match tcx.hir_node_by_def_id(def_id) {
|
||||
let (generics, span) = match tcx.hir_node_by_def_id(def_id) {
|
||||
hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })
|
||||
| hir::Node::ForeignItem(hir::ForeignItem {
|
||||
kind: hir::ForeignItemKind::Fn(.., generics, _),
|
||||
..
|
||||
}) => {
|
||||
let own_counts = tcx.generics_of(def_id).own_counts();
|
||||
(own_counts, generics.span)
|
||||
}
|
||||
}) => (tcx.generics_of(def_id), generics.span),
|
||||
_ => {
|
||||
struct_span_code_err!(tcx.dcx(), span, E0622, "intrinsic must be a function")
|
||||
.with_span_label(span, "expected a function")
|
||||
|
|
@ -42,6 +39,7 @@ fn equate_intrinsic_type<'tcx>(
|
|||
return;
|
||||
}
|
||||
};
|
||||
let own_counts = generics.own_counts();
|
||||
|
||||
let gen_count_ok = |found: usize, expected: usize, descr: &str| -> bool {
|
||||
if found != expected {
|
||||
|
|
@ -57,9 +55,17 @@ fn equate_intrinsic_type<'tcx>(
|
|||
}
|
||||
};
|
||||
|
||||
// the host effect param should be invisible as it shouldn't matter
|
||||
// whether effects is enabled for the intrinsic provider crate.
|
||||
let consts_count = if generics.host_effect_index.is_some() {
|
||||
own_counts.consts - 1
|
||||
} else {
|
||||
own_counts.consts
|
||||
};
|
||||
|
||||
if gen_count_ok(own_counts.lifetimes, n_lts, "lifetime")
|
||||
&& gen_count_ok(own_counts.types, n_tps, "type")
|
||||
&& gen_count_ok(own_counts.consts, n_cts, "const")
|
||||
&& gen_count_ok(consts_count, n_cts, "const")
|
||||
{
|
||||
let _ = check_function_signature(
|
||||
tcx,
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _
|
|||
use rustc_trait_selection::traits::{
|
||||
self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc,
|
||||
};
|
||||
use rustc_type_ir::solve::NoSolution;
|
||||
use rustc_type_ir::TypeFlags;
|
||||
|
||||
use std::cell::LazyCell;
|
||||
|
|
@ -477,7 +478,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, trait_def_id: LocalDefId) {
|
|||
param_env,
|
||||
item_def_id,
|
||||
tcx.explicit_item_bounds(item_def_id)
|
||||
.instantiate_identity_iter_copied()
|
||||
.iter_identity_copied()
|
||||
.collect::<Vec<_>>(),
|
||||
&FxIndexSet::default(),
|
||||
gat_def_id,
|
||||
|
|
@ -1204,17 +1205,16 @@ fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocIt
|
|||
let bounds = wfcx.tcx().explicit_item_bounds(item.def_id);
|
||||
|
||||
debug!("check_associated_type_bounds: bounds={:?}", bounds);
|
||||
let wf_obligations =
|
||||
bounds.instantiate_identity_iter_copied().flat_map(|(bound, bound_span)| {
|
||||
let normalized_bound = wfcx.normalize(span, None, bound);
|
||||
traits::wf::clause_obligations(
|
||||
wfcx.infcx,
|
||||
wfcx.param_env,
|
||||
wfcx.body_def_id,
|
||||
normalized_bound,
|
||||
bound_span,
|
||||
)
|
||||
});
|
||||
let wf_obligations = bounds.iter_identity_copied().flat_map(|(bound, bound_span)| {
|
||||
let normalized_bound = wfcx.normalize(span, None, bound);
|
||||
traits::wf::clause_obligations(
|
||||
wfcx.infcx,
|
||||
wfcx.param_env,
|
||||
wfcx.body_def_id,
|
||||
normalized_bound,
|
||||
bound_span,
|
||||
)
|
||||
});
|
||||
|
||||
wfcx.register_obligations(wf_obligations);
|
||||
}
|
||||
|
|
@ -1712,13 +1712,12 @@ fn receiver_is_valid<'tcx>(
|
|||
let cause =
|
||||
ObligationCause::new(span, wfcx.body_def_id, traits::ObligationCauseCode::MethodReceiver);
|
||||
|
||||
let can_eq_self = |ty| infcx.can_eq(wfcx.param_env, self_ty, ty);
|
||||
|
||||
// `self: Self` is always valid.
|
||||
if can_eq_self(receiver_ty) {
|
||||
if let Err(err) = wfcx.eq(&cause, wfcx.param_env, self_ty, receiver_ty) {
|
||||
infcx.err_ctxt().report_mismatched_types(&cause, self_ty, receiver_ty, err).emit();
|
||||
}
|
||||
// Special case `receiver == self_ty`, which doesn't necessarily require the `Receiver` lang item.
|
||||
if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
|
||||
let ocx = ObligationCtxt::new(wfcx.infcx);
|
||||
ocx.eq(&cause, wfcx.param_env, self_ty, receiver_ty)?;
|
||||
if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
@ -1729,58 +1728,51 @@ fn receiver_is_valid<'tcx>(
|
|||
autoderef = autoderef.include_raw_pointers();
|
||||
}
|
||||
|
||||
// The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
|
||||
autoderef.next();
|
||||
|
||||
let receiver_trait_def_id = tcx.require_lang_item(LangItem::Receiver, Some(span));
|
||||
|
||||
// Keep dereferencing `receiver_ty` until we get to `self_ty`.
|
||||
loop {
|
||||
if let Some((potential_self_ty, _)) = autoderef.next() {
|
||||
debug!(
|
||||
"receiver_is_valid: potential self type `{:?}` to match `{:?}`",
|
||||
potential_self_ty, self_ty
|
||||
);
|
||||
while let Some((potential_self_ty, _)) = autoderef.next() {
|
||||
debug!(
|
||||
"receiver_is_valid: potential self type `{:?}` to match `{:?}`",
|
||||
potential_self_ty, self_ty
|
||||
);
|
||||
|
||||
if can_eq_self(potential_self_ty) {
|
||||
wfcx.register_obligations(autoderef.into_obligations());
|
||||
|
||||
if let Err(err) = wfcx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty) {
|
||||
infcx
|
||||
.err_ctxt()
|
||||
.report_mismatched_types(&cause, self_ty, potential_self_ty, err)
|
||||
.emit();
|
||||
}
|
||||
// Check if the self type unifies. If it does, then commit the result
|
||||
// since it may have region side-effects.
|
||||
if let Ok(()) = wfcx.infcx.commit_if_ok(|_| {
|
||||
let ocx = ObligationCtxt::new(wfcx.infcx);
|
||||
ocx.eq(&cause, wfcx.param_env, self_ty, potential_self_ty)?;
|
||||
if ocx.select_all_or_error().is_empty() { Ok(()) } else { Err(NoSolution) }
|
||||
}) {
|
||||
wfcx.register_obligations(autoderef.into_obligations());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Without `feature(arbitrary_self_types)`, we require that each step in the
|
||||
// deref chain implement `receiver`.
|
||||
if !arbitrary_self_types_enabled {
|
||||
if !receiver_is_implemented(
|
||||
wfcx,
|
||||
receiver_trait_def_id,
|
||||
cause.clone(),
|
||||
potential_self_ty,
|
||||
) {
|
||||
// We cannot proceed.
|
||||
break;
|
||||
} else {
|
||||
// Without `feature(arbitrary_self_types)`, we require that each step in the
|
||||
// deref chain implement `receiver`
|
||||
if !arbitrary_self_types_enabled
|
||||
&& !receiver_is_implemented(
|
||||
wfcx,
|
||||
receiver_trait_def_id,
|
||||
cause.clone(),
|
||||
potential_self_ty,
|
||||
)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
|
||||
return false;
|
||||
|
||||
// Register the bound, in case it has any region side-effects.
|
||||
wfcx.register_bound(
|
||||
cause.clone(),
|
||||
wfcx.param_env,
|
||||
potential_self_ty,
|
||||
receiver_trait_def_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
|
||||
if !arbitrary_self_types_enabled
|
||||
&& !receiver_is_implemented(wfcx, receiver_trait_def_id, cause.clone(), receiver_ty)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
|
||||
false
|
||||
}
|
||||
|
||||
fn receiver_is_implemented<'tcx>(
|
||||
|
|
|
|||
|
|
@ -286,7 +286,7 @@ fn orphan_check<'tcx>(
|
|||
tcx: TyCtxt<'tcx>,
|
||||
impl_def_id: LocalDefId,
|
||||
mode: OrphanCheckMode,
|
||||
) -> Result<(), OrphanCheckErr<'tcx, FxIndexSet<DefId>>> {
|
||||
) -> Result<(), OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>> {
|
||||
// We only accept this routine to be invoked on implementations
|
||||
// of a trait, not inherent implementations.
|
||||
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
|
||||
|
|
@ -326,17 +326,16 @@ fn orphan_check<'tcx>(
|
|||
ty
|
||||
};
|
||||
|
||||
Ok(ty)
|
||||
Ok::<_, !>(ty)
|
||||
};
|
||||
|
||||
let Ok(result) = traits::orphan_check_trait_ref::<!>(
|
||||
let result = traits::orphan_check_trait_ref(
|
||||
&infcx,
|
||||
trait_ref,
|
||||
traits::InCrate::Local { mode },
|
||||
lazily_normalize_ty,
|
||||
) else {
|
||||
unreachable!()
|
||||
};
|
||||
)
|
||||
.into_ok();
|
||||
|
||||
// (2) Try to map the remaining inference vars back to generic params.
|
||||
result.map_err(|err| match err {
|
||||
|
|
@ -369,7 +368,7 @@ fn emit_orphan_check_error<'tcx>(
|
|||
tcx: TyCtxt<'tcx>,
|
||||
trait_ref: ty::TraitRef<'tcx>,
|
||||
impl_def_id: LocalDefId,
|
||||
err: traits::OrphanCheckErr<'tcx, FxIndexSet<DefId>>,
|
||||
err: traits::OrphanCheckErr<TyCtxt<'tcx>, FxIndexSet<DefId>>,
|
||||
) -> ErrorGuaranteed {
|
||||
match err {
|
||||
traits::OrphanCheckErr::NonLocalInputType(tys) => {
|
||||
|
|
@ -482,7 +481,7 @@ fn emit_orphan_check_error<'tcx>(
|
|||
|
||||
fn lint_uncovered_ty_params<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
UncoveredTyParams { uncovered, local_ty }: UncoveredTyParams<'tcx, FxIndexSet<DefId>>,
|
||||
UncoveredTyParams { uncovered, local_ty }: UncoveredTyParams<TyCtxt<'tcx>, FxIndexSet<DefId>>,
|
||||
impl_def_id: LocalDefId,
|
||||
) {
|
||||
let hir_id = tcx.local_def_id_to_hir_id(impl_def_id);
|
||||
|
|
|
|||
|
|
@ -1201,6 +1201,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
|
|||
|
||||
let is_marker = tcx.has_attr(def_id, sym::marker);
|
||||
let rustc_coinductive = tcx.has_attr(def_id, sym::rustc_coinductive);
|
||||
let is_fundamental = tcx.has_attr(def_id, sym::fundamental);
|
||||
|
||||
// FIXME: We could probably do way better attribute validation here.
|
||||
let mut skip_array_during_method_dispatch = false;
|
||||
|
|
@ -1352,6 +1353,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
|
|||
has_auto_impl: is_auto,
|
||||
is_marker,
|
||||
is_coinductive: rustc_coinductive || is_auto,
|
||||
is_fundamental,
|
||||
skip_array_during_method_dispatch,
|
||||
skip_boxed_slice_during_method_dispatch,
|
||||
specialization_kind,
|
||||
|
|
|
|||
|
|
@ -49,6 +49,7 @@ use rustc_span::edit_distance::find_best_match_for_name;
|
|||
use rustc_span::symbol::{kw, Ident, Symbol};
|
||||
use rustc_span::{sym, Span, DUMMY_SP};
|
||||
use rustc_target::spec::abi;
|
||||
use rustc_trait_selection::infer::InferCtxtExt;
|
||||
use rustc_trait_selection::traits::wf::object_region_bounds;
|
||||
use rustc_trait_selection::traits::{self, ObligationCtxt};
|
||||
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ This API is completely unstable and subject to change.
|
|||
#![feature(rustdoc_internals)]
|
||||
#![feature(slice_partition_dedup)]
|
||||
#![feature(try_blocks)]
|
||||
#![feature(unwrap_infallible)]
|
||||
// tidy-alphabetical-end
|
||||
|
||||
#[macro_use]
|
||||
|
|
|
|||
|
|
@ -138,6 +138,11 @@ hir_typeck_option_result_asref = use `{$def_path}::as_ref` to convert `{$expecte
|
|||
hir_typeck_option_result_cloned = use `{$def_path}::cloned` to clone the value inside the `{$def_path}`
|
||||
hir_typeck_option_result_copied = use `{$def_path}::copied` to copy the value inside the `{$def_path}`
|
||||
|
||||
hir_typeck_ptr_cast_add_auto_to_object = adding {$traits_len ->
|
||||
[1] an auto trait {$traits}
|
||||
*[other] auto traits {$traits}
|
||||
} to a trait object in a pointer cast may cause UB later on
|
||||
|
||||
hir_typeck_remove_semi_for_coerce = you might have meant to return the `match` expression
|
||||
hir_typeck_remove_semi_for_coerce_expr = this could be implicitly returned but it is a statement, not a tail expression
|
||||
hir_typeck_remove_semi_for_coerce_ret = the `match` arms can conform to this return type
|
||||
|
|
|
|||
|
|
@ -32,9 +32,9 @@ use super::FnCtxt;
|
|||
|
||||
use crate::errors;
|
||||
use crate::type_error_struct;
|
||||
use hir::ExprKind;
|
||||
use rustc_data_structures::fx::FxHashSet;
|
||||
use rustc_errors::{codes::*, Applicability, Diag, ErrorGuaranteed};
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::{self as hir, ExprKind};
|
||||
use rustc_macros::{TypeFoldable, TypeVisitable};
|
||||
use rustc_middle::bug;
|
||||
use rustc_middle::mir::Mutability;
|
||||
|
|
@ -44,7 +44,7 @@ use rustc_middle::ty::error::TypeError;
|
|||
use rustc_middle::ty::TyCtxt;
|
||||
use rustc_middle::ty::{self, Ty, TypeAndMut, TypeVisitableExt, VariantDef};
|
||||
use rustc_session::lint;
|
||||
use rustc_span::def_id::{DefId, LOCAL_CRATE};
|
||||
use rustc_span::def_id::LOCAL_CRATE;
|
||||
use rustc_span::symbol::sym;
|
||||
use rustc_span::Span;
|
||||
use rustc_span::DUMMY_SP;
|
||||
|
|
@ -73,7 +73,7 @@ enum PointerKind<'tcx> {
|
|||
/// No metadata attached, ie pointer to sized type or foreign type
|
||||
Thin,
|
||||
/// A trait object
|
||||
VTable(Option<DefId>),
|
||||
VTable(&'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>),
|
||||
/// Slice
|
||||
Length,
|
||||
/// The unsize info of this projection or opaque type
|
||||
|
|
@ -101,7 +101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
|
||||
Ok(match *t.kind() {
|
||||
ty::Slice(_) | ty::Str => Some(PointerKind::Length),
|
||||
ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())),
|
||||
ty::Dynamic(tty, _, ty::Dyn) => Some(PointerKind::VTable(tty)),
|
||||
ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() {
|
||||
None => Some(PointerKind::Thin),
|
||||
Some(f) => {
|
||||
|
|
@ -755,7 +755,7 @@ impl<'a, 'tcx> CastCheck<'tcx> {
|
|||
Err(CastError::IllegalCast)
|
||||
}
|
||||
|
||||
// ptr -> *
|
||||
// ptr -> ptr
|
||||
(Ptr(m_e), Ptr(m_c)) => self.check_ptr_ptr_cast(fcx, m_e, m_c), // ptr-ptr-cast
|
||||
|
||||
// ptr-addr-cast
|
||||
|
|
@ -799,40 +799,126 @@ impl<'a, 'tcx> CastCheck<'tcx> {
|
|||
fn check_ptr_ptr_cast(
|
||||
&self,
|
||||
fcx: &FnCtxt<'a, 'tcx>,
|
||||
m_expr: ty::TypeAndMut<'tcx>,
|
||||
m_cast: ty::TypeAndMut<'tcx>,
|
||||
m_src: ty::TypeAndMut<'tcx>,
|
||||
m_dst: ty::TypeAndMut<'tcx>,
|
||||
) -> Result<CastKind, CastError> {
|
||||
debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast);
|
||||
debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}");
|
||||
// ptr-ptr cast. vtables must match.
|
||||
|
||||
let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?;
|
||||
let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?;
|
||||
let src_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_src.ty, self.span)?);
|
||||
let dst_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_dst.ty, self.span)?);
|
||||
|
||||
let Some(cast_kind) = cast_kind else {
|
||||
match (src_kind, dst_kind) {
|
||||
// We can't cast if target pointer kind is unknown
|
||||
return Err(CastError::UnknownCastPtrKind);
|
||||
};
|
||||
(_, None) => Err(CastError::UnknownCastPtrKind),
|
||||
// Cast to thin pointer is OK
|
||||
(_, Some(PointerKind::Thin)) => Ok(CastKind::PtrPtrCast),
|
||||
|
||||
// Cast to thin pointer is OK
|
||||
if cast_kind == PointerKind::Thin {
|
||||
return Ok(CastKind::PtrPtrCast);
|
||||
}
|
||||
|
||||
let Some(expr_kind) = expr_kind else {
|
||||
// We can't cast to fat pointer if source pointer kind is unknown
|
||||
return Err(CastError::UnknownExprPtrKind);
|
||||
};
|
||||
(None, _) => Err(CastError::UnknownExprPtrKind),
|
||||
|
||||
// thin -> fat? report invalid cast (don't complain about vtable kinds)
|
||||
if expr_kind == PointerKind::Thin {
|
||||
return Err(CastError::SizedUnsizedCast);
|
||||
}
|
||||
// thin -> fat? report invalid cast (don't complain about vtable kinds)
|
||||
(Some(PointerKind::Thin), _) => Err(CastError::SizedUnsizedCast),
|
||||
|
||||
// vtable kinds must match
|
||||
if fcx.tcx.erase_regions(cast_kind) == fcx.tcx.erase_regions(expr_kind) {
|
||||
Ok(CastKind::PtrPtrCast)
|
||||
} else {
|
||||
Err(CastError::DifferingKinds)
|
||||
// trait object -> trait object? need to do additional checks
|
||||
(Some(PointerKind::VTable(src_tty)), Some(PointerKind::VTable(dst_tty))) => {
|
||||
match (src_tty.principal(), dst_tty.principal()) {
|
||||
// A<dyn Src<...> + SrcAuto> -> B<dyn Dst<...> + DstAuto>. need to make sure
|
||||
// - `Src` and `Dst` traits are the same
|
||||
// - traits have the same generic arguments
|
||||
// - `SrcAuto` is a superset of `DstAuto`
|
||||
(Some(src_principal), Some(dst_principal)) => {
|
||||
let tcx = fcx.tcx;
|
||||
|
||||
// Check that the traits are actually the same.
|
||||
// The `dyn Src = dyn Dst` check below would suffice,
|
||||
// but this may produce a better diagnostic.
|
||||
//
|
||||
// Note that trait upcasting goes through a different mechanism (`coerce_unsized`)
|
||||
// and is unaffected by this check.
|
||||
if src_principal.def_id() != dst_principal.def_id() {
|
||||
return Err(CastError::DifferingKinds);
|
||||
}
|
||||
|
||||
// We need to reconstruct trait object types.
|
||||
// `m_src` and `m_dst` won't work for us here because they will potentially
|
||||
// contain wrappers, which we do not care about.
|
||||
//
|
||||
// e.g. we want to allow `dyn T -> (dyn T,)`, etc.
|
||||
//
|
||||
// We also need to skip auto traits to emit an FCW and not an error.
|
||||
let src_obj = tcx.mk_ty_from_kind(ty::Dynamic(
|
||||
tcx.mk_poly_existential_predicates(
|
||||
&src_tty.without_auto_traits().collect::<Vec<_>>(),
|
||||
),
|
||||
tcx.lifetimes.re_erased,
|
||||
ty::Dyn,
|
||||
));
|
||||
let dst_obj = tcx.mk_ty_from_kind(ty::Dynamic(
|
||||
tcx.mk_poly_existential_predicates(
|
||||
&dst_tty.without_auto_traits().collect::<Vec<_>>(),
|
||||
),
|
||||
tcx.lifetimes.re_erased,
|
||||
ty::Dyn,
|
||||
));
|
||||
|
||||
// `dyn Src = dyn Dst`, this checks for matching traits/generics
|
||||
fcx.demand_eqtype(self.span, src_obj, dst_obj);
|
||||
|
||||
// Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`.
|
||||
// Emit an FCW otherwise.
|
||||
let src_auto: FxHashSet<_> = src_tty
|
||||
.auto_traits()
|
||||
.chain(
|
||||
tcx.supertrait_def_ids(src_principal.def_id())
|
||||
.filter(|def_id| tcx.trait_is_auto(*def_id)),
|
||||
)
|
||||
.collect();
|
||||
|
||||
let added = dst_tty
|
||||
.auto_traits()
|
||||
.filter(|trait_did| !src_auto.contains(trait_did))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !added.is_empty() {
|
||||
tcx.emit_node_span_lint(
|
||||
lint::builtin::PTR_CAST_ADD_AUTO_TO_OBJECT,
|
||||
self.expr.hir_id,
|
||||
self.span,
|
||||
errors::PtrCastAddAutoToObject {
|
||||
traits_len: added.len(),
|
||||
traits: {
|
||||
let mut traits: Vec<_> = added
|
||||
.into_iter()
|
||||
.map(|trait_did| tcx.def_path_str(trait_did))
|
||||
.collect();
|
||||
|
||||
traits.sort();
|
||||
traits.into()
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Ok(CastKind::PtrPtrCast)
|
||||
}
|
||||
|
||||
// dyn Auto -> dyn Auto'? ok.
|
||||
(None, None) => Ok(CastKind::PtrPtrCast),
|
||||
|
||||
// dyn Trait -> dyn Auto? should be ok, but we used to not allow it.
|
||||
// FIXME: allow this
|
||||
(Some(_), None) => Err(CastError::DifferingKinds),
|
||||
|
||||
// dyn Auto -> dyn Trait? not ok.
|
||||
(None, Some(_)) => Err(CastError::DifferingKinds),
|
||||
}
|
||||
}
|
||||
|
||||
// fat -> fat? metadata kinds must match
|
||||
(Some(src_kind), Some(dst_kind)) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast),
|
||||
|
||||
(_, _) => Err(CastError::DifferingKinds),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -424,9 +424,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
if let Some(trait_def_id) = trait_def_id {
|
||||
let found_kind = match closure_kind {
|
||||
hir::ClosureKind::Closure => self.tcx.fn_trait_kind_from_def_id(trait_def_id),
|
||||
hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
|
||||
self.tcx.async_fn_trait_kind_from_def_id(trait_def_id)
|
||||
}
|
||||
hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => self
|
||||
.tcx
|
||||
.async_fn_trait_kind_from_def_id(trait_def_id)
|
||||
.or_else(|| self.tcx.fn_trait_kind_from_def_id(trait_def_id)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
|
|
@ -470,14 +471,37 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
// for closures and async closures, respectively.
|
||||
match closure_kind {
|
||||
hir::ClosureKind::Closure
|
||||
if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() => {}
|
||||
if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() =>
|
||||
{
|
||||
self.extract_sig_from_projection(cause_span, projection)
|
||||
}
|
||||
hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
|
||||
if self.tcx.async_fn_trait_kind_from_def_id(trait_def_id).is_some() => {}
|
||||
_ => return None,
|
||||
if self.tcx.async_fn_trait_kind_from_def_id(trait_def_id).is_some() =>
|
||||
{
|
||||
self.extract_sig_from_projection(cause_span, projection)
|
||||
}
|
||||
// It's possible we've passed the closure to a (somewhat out-of-fashion)
|
||||
// `F: FnOnce() -> Fut, Fut: Future<Output = T>` style bound. Let's still
|
||||
// guide inference here, since it's beneficial for the user.
|
||||
hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async)
|
||||
if self.tcx.fn_trait_kind_from_def_id(trait_def_id).is_some() =>
|
||||
{
|
||||
self.extract_sig_from_projection_and_future_bound(cause_span, projection)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args
|
||||
/// and return type to infer a [`ty::PolyFnSig`] for the closure.
|
||||
fn extract_sig_from_projection(
|
||||
&self,
|
||||
cause_span: Option<Span>,
|
||||
projection: ty::PolyProjectionPredicate<'tcx>,
|
||||
) -> Option<ExpectedSig<'tcx>> {
|
||||
let projection = self.resolve_vars_if_possible(projection);
|
||||
|
||||
let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
|
||||
let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
|
||||
debug!(?arg_param_ty);
|
||||
|
||||
let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
|
||||
|
|
@ -486,7 +510,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
|
||||
// Since this is a return parameter type it is safe to unwrap.
|
||||
let ret_param_ty = projection.skip_binder().term.expect_type();
|
||||
let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
|
||||
debug!(?ret_param_ty);
|
||||
|
||||
let sig = projection.rebind(self.tcx.mk_fn_sig(
|
||||
|
|
@ -500,6 +523,69 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
Some(ExpectedSig { cause_span, sig })
|
||||
}
|
||||
|
||||
/// When an async closure is passed to a function that has a "two-part" `Fn`
|
||||
/// and `Future` trait bound, like:
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::future::Future;
|
||||
///
|
||||
/// fn not_exactly_an_async_closure<F, Fut>(_f: F)
|
||||
/// where
|
||||
/// F: FnOnce(String, u32) -> Fut,
|
||||
/// Fut: Future<Output = i32>,
|
||||
/// {}
|
||||
/// ```
|
||||
///
|
||||
/// The we want to be able to extract the signature to guide inference in the async
|
||||
/// closure. We will have two projection predicates registered in this case. First,
|
||||
/// we identify the `FnOnce<Args, Output = ?Fut>` bound, and if the output type is
|
||||
/// an inference variable `?Fut`, we check if that is bounded by a `Future<Output = Ty>`
|
||||
/// projection.
|
||||
fn extract_sig_from_projection_and_future_bound(
|
||||
&self,
|
||||
cause_span: Option<Span>,
|
||||
projection: ty::PolyProjectionPredicate<'tcx>,
|
||||
) -> Option<ExpectedSig<'tcx>> {
|
||||
let projection = self.resolve_vars_if_possible(projection);
|
||||
|
||||
let arg_param_ty = projection.skip_binder().projection_term.args.type_at(1);
|
||||
debug!(?arg_param_ty);
|
||||
|
||||
let ty::Tuple(input_tys) = *arg_param_ty.kind() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
// If the return type is a type variable, look for bounds on it.
|
||||
// We could theoretically support other kinds of return types here,
|
||||
// but none of them would be useful, since async closures return
|
||||
// concrete anonymous future types, and their futures are not coerced
|
||||
// into any other type within the body of the async closure.
|
||||
let ty::Infer(ty::TyVar(return_vid)) = *projection.skip_binder().term.expect_type().kind()
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
|
||||
// FIXME: We may want to elaborate here, though I assume this will be exceedingly rare.
|
||||
for bound in self.obligations_for_self_ty(return_vid) {
|
||||
if let Some(ret_projection) = bound.predicate.as_projection_clause()
|
||||
&& let Some(ret_projection) = ret_projection.no_bound_vars()
|
||||
&& self.tcx.is_lang_item(ret_projection.def_id(), LangItem::FutureOutput)
|
||||
{
|
||||
let sig = projection.rebind(self.tcx.mk_fn_sig(
|
||||
input_tys,
|
||||
ret_projection.term.expect_type(),
|
||||
false,
|
||||
hir::Safety::Safe,
|
||||
Abi::Rust,
|
||||
));
|
||||
|
||||
return Some(ExpectedSig { cause_span, sig });
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn sig_of_closure(
|
||||
&self,
|
||||
expr_def_id: LocalDefId,
|
||||
|
|
|
|||
|
|
@ -1752,10 +1752,8 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
|
|||
fcx.probe(|_| {
|
||||
let ocx = ObligationCtxt::new(fcx);
|
||||
ocx.register_obligations(
|
||||
fcx.tcx
|
||||
.item_super_predicates(rpit_def_id)
|
||||
.instantiate_identity_iter()
|
||||
.filter_map(|clause| {
|
||||
fcx.tcx.item_super_predicates(rpit_def_id).iter_identity().filter_map(
|
||||
|clause| {
|
||||
let predicate = clause
|
||||
.kind()
|
||||
.map_bound(|clause| match clause {
|
||||
|
|
@ -1776,7 +1774,8 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
|
|||
fcx.param_env,
|
||||
predicate,
|
||||
))
|
||||
}),
|
||||
},
|
||||
),
|
||||
);
|
||||
ocx.select_where_possible().is_empty()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths;
|
|||
use rustc_middle::ty::{self, AssocItem, Ty, TypeFoldable, TypeVisitableExt};
|
||||
use rustc_span::symbol::sym;
|
||||
use rustc_span::{Span, DUMMY_SP};
|
||||
use rustc_trait_selection::infer::InferCtxtExt;
|
||||
use rustc_trait_selection::traits::ObligationCause;
|
||||
|
||||
use super::method::probe;
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ use std::borrow::Cow;
|
|||
|
||||
use crate::fluent_generated as fluent;
|
||||
use rustc_errors::{
|
||||
codes::*, Applicability, Diag, DiagArgValue, EmissionGuarantee, IntoDiagArg, MultiSpan,
|
||||
SubdiagMessageOp, Subdiagnostic,
|
||||
codes::*, Applicability, Diag, DiagArgValue, DiagSymbolList, EmissionGuarantee, IntoDiagArg,
|
||||
MultiSpan, SubdiagMessageOp, Subdiagnostic,
|
||||
};
|
||||
use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic};
|
||||
use rustc_middle::ty::{self, Ty};
|
||||
|
|
@ -253,6 +253,13 @@ pub struct LossyProvenanceInt2Ptr<'tcx> {
|
|||
pub sugg: LossyProvenanceInt2PtrSuggestion,
|
||||
}
|
||||
|
||||
#[derive(LintDiagnostic)]
|
||||
#[diag(hir_typeck_ptr_cast_add_auto_to_object)]
|
||||
pub struct PtrCastAddAutoToObject {
|
||||
pub traits_len: usize,
|
||||
pub traits: DiagSymbolList<String>,
|
||||
}
|
||||
|
||||
#[derive(Subdiagnostic)]
|
||||
#[multipart_suggestion(hir_typeck_suggestion, applicability = "has-placeholders")]
|
||||
pub struct LossyProvenanceInt2PtrSuggestion {
|
||||
|
|
|
|||
|
|
@ -734,7 +734,9 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx
|
|||
// struct; however, when EUV is run during typeck, it
|
||||
// may not. This will generate an error earlier in typeck,
|
||||
// so we can just ignore it.
|
||||
span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
|
||||
if self.cx.tainted_by_errors().is_ok() {
|
||||
span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ use rustc_middle::{bug, span_bug};
|
|||
use rustc_session::Session;
|
||||
use rustc_span::symbol::{kw, Ident};
|
||||
use rustc_span::{sym, BytePos, Span, DUMMY_SP};
|
||||
use rustc_trait_selection::infer::InferCtxtExt;
|
||||
use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};
|
||||
|
||||
use std::iter;
|
||||
|
|
|
|||
|
|
@ -2582,7 +2582,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
|||
}
|
||||
}
|
||||
(hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, expr), _, &ty::Ref(_, checked, _))
|
||||
if self.can_sub(self.param_env, checked, expected) =>
|
||||
if self.can_eq(self.param_env, checked, expected) =>
|
||||
{
|
||||
let make_sugg = |start: Span, end: BytePos| {
|
||||
// skip `(` for tuples such as `(c) = (&123)`.
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ use rustc_span::edit_distance::{
|
|||
};
|
||||
use rustc_span::symbol::sym;
|
||||
use rustc_span::{symbol::Ident, Span, Symbol, DUMMY_SP};
|
||||
use rustc_trait_selection::infer::InferCtxtExt as _;
|
||||
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
|
||||
use rustc_trait_selection::traits::query::method_autoderef::MethodAutoderefBadTy;
|
||||
use rustc_trait_selection::traits::query::method_autoderef::{
|
||||
|
|
@ -857,7 +858,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
|
|||
let args = self.fresh_args_for_item(self.span, method.def_id);
|
||||
let fty = self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args);
|
||||
let fty = self.instantiate_binder_with_fresh_vars(self.span, infer::FnCall, fty);
|
||||
self.can_sub(self.param_env, fty.output(), expected)
|
||||
self.can_eq(self.param_env, fty.output(), expected)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ use rustc_span::source_map::Spanned;
|
|||
use rustc_span::symbol::{kw, sym, Ident};
|
||||
use rustc_span::{BytePos, Span, DUMMY_SP};
|
||||
use rustc_target::abi::FieldIdx;
|
||||
use rustc_trait_selection::infer::InferCtxtExt;
|
||||
use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
|
||||
use ty::VariantDef;
|
||||
|
||||
|
|
|
|||
|
|
@ -151,6 +151,10 @@ impl<'tcx> InferCtxtLike for InferCtxt<'tcx> {
|
|||
.eq_structurally_relating_aliases_no_trace(lhs, rhs)
|
||||
}
|
||||
|
||||
fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
|
||||
self.shallow_resolve(ty)
|
||||
}
|
||||
|
||||
fn resolve_vars_if_possible<T>(&self, value: T) -> T
|
||||
where
|
||||
T: TypeFoldable<TyCtxt<'tcx>>,
|
||||
|
|
|
|||
|
|
@ -820,7 +820,7 @@ fn foo(&self) -> Self::T { String::new() }
|
|||
tcx.defaultness(item.id.owner_id)
|
||||
{
|
||||
let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
|
||||
if self.infcx.can_eq(param_env, assoc_ty, found) {
|
||||
if self.infcx.can_eq_shallow(param_env, assoc_ty, found) {
|
||||
diag.span_label(
|
||||
item.span,
|
||||
"associated type defaults can't be assumed inside the \
|
||||
|
|
@ -843,7 +843,7 @@ fn foo(&self) -> Self::T { String::new() }
|
|||
let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity();
|
||||
if let hir::Defaultness::Default { has_value: true } =
|
||||
tcx.defaultness(item.id.owner_id)
|
||||
&& self.infcx.can_eq(param_env, assoc_ty, found)
|
||||
&& self.infcx.can_eq_shallow(param_env, assoc_ty, found)
|
||||
{
|
||||
diag.span_label(
|
||||
item.span,
|
||||
|
|
|
|||
|
|
@ -768,19 +768,9 @@ impl<'tcx> InferCtxt<'tcx> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
pub fn can_sub<T>(&self, param_env: ty::ParamEnv<'tcx>, expected: T, actual: T) -> bool
|
||||
where
|
||||
T: at::ToTrace<'tcx>,
|
||||
{
|
||||
let origin = &ObligationCause::dummy();
|
||||
self.probe(|_| {
|
||||
// We're only answering whether there could be a subtyping relation, and with
|
||||
// opaque types, "there could be one", via registering a hidden type.
|
||||
self.at(origin, param_env).sub(DefineOpaqueTypes::Yes, expected, actual).is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn can_eq<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool
|
||||
// FIXME(-Znext-solver): Get rid of this method, it's never correct. Either that,
|
||||
// or we need to process the obligations.
|
||||
pub fn can_eq_shallow<T>(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> bool
|
||||
where
|
||||
T: at::ToTrace<'tcx>,
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
use smallvec::smallvec;
|
||||
|
||||
use crate::traits::{self, Obligation, ObligationCauseCode, PredicateObligation};
|
||||
use rustc_data_structures::fx::FxHashSet;
|
||||
use rustc_middle::ty::ToPolyTraitRef;
|
||||
use rustc_middle::ty::{self, Ty, TyCtxt, Upcast};
|
||||
use rustc_middle::ty::{self, TyCtxt};
|
||||
use rustc_span::symbol::Ident;
|
||||
use rustc_span::Span;
|
||||
use rustc_type_ir::outlives::{push_outlives_components, Component};
|
||||
pub use rustc_type_ir::elaborate::*;
|
||||
|
||||
pub fn anonymize_predicate<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
|
|
@ -64,50 +62,9 @@ impl<'tcx> Extend<ty::Predicate<'tcx>> for PredicateSet<'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// `Elaboration` iterator
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// "Elaboration" is the process of identifying all the predicates that
|
||||
/// are implied by a source predicate. Currently, this basically means
|
||||
/// walking the "supertraits" and other similar assumptions. For example,
|
||||
/// if we know that `T: Ord`, the elaborator would deduce that `T: PartialOrd`
|
||||
/// holds as well. Similarly, if we have `trait Foo: 'static`, and we know that
|
||||
/// `T: Foo`, then we know that `T: 'static`.
|
||||
pub struct Elaborator<'tcx, O> {
|
||||
stack: Vec<O>,
|
||||
visited: PredicateSet<'tcx>,
|
||||
mode: Filter,
|
||||
}
|
||||
|
||||
enum Filter {
|
||||
All,
|
||||
OnlySelf,
|
||||
}
|
||||
|
||||
/// Describes how to elaborate an obligation into a sub-obligation.
|
||||
///
|
||||
/// For [`Obligation`], a sub-obligation is combined with the current obligation's
|
||||
/// param-env and cause code. For [`ty::Predicate`], none of this is needed, since
|
||||
/// there is no param-env or cause code to copy over.
|
||||
pub trait Elaboratable<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx>;
|
||||
|
||||
// Makes a new `Self` but with a different clause that comes from elaboration.
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self;
|
||||
|
||||
// Makes a new `Self` but with a different clause and a different cause
|
||||
// code (if `Self` has one, such as [`PredicateObligation`]).
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
span: Span,
|
||||
parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
index: usize,
|
||||
) -> Self;
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<'tcx> for PredicateObligation<'tcx> {
|
||||
/// param-env and cause code.
|
||||
impl<'tcx> Elaboratable<TyCtxt<'tcx>> for PredicateObligation<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.predicate
|
||||
}
|
||||
|
|
@ -145,270 +102,6 @@ impl<'tcx> Elaboratable<'tcx> for PredicateObligation<'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<'tcx> for ty::Predicate<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
*self
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
clause.as_predicate()
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
clause.as_predicate()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<'tcx> for (ty::Predicate<'tcx>, Span) {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
(clause.as_predicate(), self.1)
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
(clause.as_predicate(), self.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<'tcx> for (ty::Clause<'tcx>, Span) {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.0.as_predicate()
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
(clause, self.1)
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
(clause, self.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<'tcx> for ty::Clause<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.as_predicate()
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
clause
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
clause
|
||||
}
|
||||
}
|
||||
|
||||
pub fn elaborate<'tcx, O: Elaboratable<'tcx>>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
obligations: impl IntoIterator<Item = O>,
|
||||
) -> Elaborator<'tcx, O> {
|
||||
let mut elaborator =
|
||||
Elaborator { stack: Vec::new(), visited: PredicateSet::new(tcx), mode: Filter::All };
|
||||
elaborator.extend_deduped(obligations);
|
||||
elaborator
|
||||
}
|
||||
|
||||
impl<'tcx, O: Elaboratable<'tcx>> Elaborator<'tcx, O> {
|
||||
fn extend_deduped(&mut self, obligations: impl IntoIterator<Item = O>) {
|
||||
// Only keep those bounds that we haven't already seen.
|
||||
// This is necessary to prevent infinite recursion in some
|
||||
// cases. One common case is when people define
|
||||
// `trait Sized: Sized { }` rather than `trait Sized { }`.
|
||||
// let visited = &mut self.visited;
|
||||
self.stack.extend(obligations.into_iter().filter(|o| self.visited.insert(o.predicate())));
|
||||
}
|
||||
|
||||
/// Filter to only the supertraits of trait predicates, i.e. only the predicates
|
||||
/// that have `Self` as their self type, instead of all implied predicates.
|
||||
pub fn filter_only_self(mut self) -> Self {
|
||||
self.mode = Filter::OnlySelf;
|
||||
self
|
||||
}
|
||||
|
||||
fn elaborate(&mut self, elaboratable: &O) {
|
||||
let tcx = self.visited.tcx;
|
||||
|
||||
// We only elaborate clauses.
|
||||
let Some(clause) = elaboratable.predicate().as_clause() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let bound_clause = clause.kind();
|
||||
match bound_clause.skip_binder() {
|
||||
ty::ClauseKind::Trait(data) => {
|
||||
// Negative trait bounds do not imply any supertrait bounds
|
||||
if data.polarity != ty::PredicatePolarity::Positive {
|
||||
return;
|
||||
}
|
||||
// Get predicates implied by the trait, or only super predicates if we only care about self predicates.
|
||||
let predicates = match self.mode {
|
||||
Filter::All => tcx.explicit_implied_predicates_of(data.def_id()),
|
||||
Filter::OnlySelf => tcx.explicit_super_predicates_of(data.def_id()),
|
||||
};
|
||||
|
||||
let obligations =
|
||||
predicates.predicates.iter().enumerate().map(|(index, &(clause, span))| {
|
||||
elaboratable.child_with_derived_cause(
|
||||
clause.instantiate_supertrait(tcx, bound_clause.rebind(data.trait_ref)),
|
||||
span,
|
||||
bound_clause.rebind(data),
|
||||
index,
|
||||
)
|
||||
});
|
||||
debug!(?data, ?obligations, "super_predicates");
|
||||
self.extend_deduped(obligations);
|
||||
}
|
||||
ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty_max, r_min)) => {
|
||||
// We know that `T: 'a` for some type `T`. We can
|
||||
// often elaborate this. For example, if we know that
|
||||
// `[U]: 'a`, that implies that `U: 'a`. Similarly, if
|
||||
// we know `&'a U: 'b`, then we know that `'a: 'b` and
|
||||
// `U: 'b`.
|
||||
//
|
||||
// We can basically ignore bound regions here. So for
|
||||
// example `for<'c> Foo<'a,'c>: 'b` can be elaborated to
|
||||
// `'a: 'b`.
|
||||
|
||||
// Ignore `for<'a> T: 'a` -- we might in the future
|
||||
// consider this as evidence that `T: 'static`, but
|
||||
// I'm a bit wary of such constructions and so for now
|
||||
// I want to be conservative. --nmatsakis
|
||||
if r_min.is_bound() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut components = smallvec![];
|
||||
push_outlives_components(tcx, ty_max, &mut components);
|
||||
self.extend_deduped(
|
||||
components
|
||||
.into_iter()
|
||||
.filter_map(|component| match component {
|
||||
Component::Region(r) => {
|
||||
if r.is_bound() {
|
||||
None
|
||||
} else {
|
||||
Some(ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(
|
||||
r, r_min,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
Component::Param(p) => {
|
||||
let ty = Ty::new_param(tcx, p.index, p.name);
|
||||
Some(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, r_min)))
|
||||
}
|
||||
|
||||
Component::Placeholder(p) => {
|
||||
let ty = Ty::new_placeholder(tcx, p);
|
||||
Some(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, r_min)))
|
||||
}
|
||||
|
||||
Component::UnresolvedInferenceVariable(_) => None,
|
||||
|
||||
Component::Alias(alias_ty) => {
|
||||
// We might end up here if we have `Foo<<Bar as Baz>::Assoc>: 'a`.
|
||||
// With this, we can deduce that `<Bar as Baz>::Assoc: 'a`.
|
||||
Some(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(
|
||||
alias_ty.to_ty(tcx),
|
||||
r_min,
|
||||
)))
|
||||
}
|
||||
|
||||
Component::EscapingAlias(_) => {
|
||||
// We might be able to do more here, but we don't
|
||||
// want to deal with escaping vars right now.
|
||||
None
|
||||
}
|
||||
})
|
||||
.map(|clause| elaboratable.child(bound_clause.rebind(clause).upcast(tcx))),
|
||||
);
|
||||
}
|
||||
ty::ClauseKind::RegionOutlives(..) => {
|
||||
// Nothing to elaborate from `'a: 'b`.
|
||||
}
|
||||
ty::ClauseKind::WellFormed(..) => {
|
||||
// Currently, we do not elaborate WF predicates,
|
||||
// although we easily could.
|
||||
}
|
||||
ty::ClauseKind::Projection(..) => {
|
||||
// Nothing to elaborate in a projection predicate.
|
||||
}
|
||||
ty::ClauseKind::ConstEvaluatable(..) => {
|
||||
// Currently, we do not elaborate const-evaluatable
|
||||
// predicates.
|
||||
}
|
||||
ty::ClauseKind::ConstArgHasType(..) => {
|
||||
// Nothing to elaborate
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx, O: Elaboratable<'tcx>> Iterator for Elaborator<'tcx, O> {
|
||||
type Item = O;
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
(self.stack.len(), None)
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
// Extract next item from top-most stack frame, if any.
|
||||
if let Some(obligation) = self.stack.pop() {
|
||||
self.elaborate(&obligation);
|
||||
Some(obligation)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Supertrait iterator
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
pub fn supertraits<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
trait_ref: ty::PolyTraitRef<'tcx>,
|
||||
) -> FilterToTraits<Elaborator<'tcx, ty::Clause<'tcx>>> {
|
||||
elaborate(tcx, [trait_ref.upcast(tcx)]).filter_only_self().filter_to_traits()
|
||||
}
|
||||
|
||||
pub fn transitive_bounds<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
trait_refs: impl Iterator<Item = ty::PolyTraitRef<'tcx>>,
|
||||
) -> FilterToTraits<Elaborator<'tcx, ty::Clause<'tcx>>> {
|
||||
elaborate(tcx, trait_refs.map(|trait_ref| trait_ref.upcast(tcx)))
|
||||
.filter_only_self()
|
||||
.filter_to_traits()
|
||||
}
|
||||
|
||||
/// A specialized variant of `elaborate` that only elaborates trait references that may
|
||||
/// define the given associated item with the name `assoc_name`. It uses the
|
||||
/// `explicit_supertraits_containing_assoc_item` query to avoid enumerating super-predicates that
|
||||
|
|
@ -443,37 +136,3 @@ pub fn transitive_bounds_that_define_assoc_item<'tcx>(
|
|||
None
|
||||
})
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
// Other
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
impl<'tcx> Elaborator<'tcx, ty::Clause<'tcx>> {
|
||||
fn filter_to_traits(self) -> FilterToTraits<Self> {
|
||||
FilterToTraits { base_iterator: self }
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter around an iterator of predicates that makes it yield up
|
||||
/// just trait references.
|
||||
pub struct FilterToTraits<I> {
|
||||
base_iterator: I,
|
||||
}
|
||||
|
||||
impl<'tcx, I: Iterator<Item = ty::Clause<'tcx>>> Iterator for FilterToTraits<I> {
|
||||
type Item = ty::PolyTraitRef<'tcx>;
|
||||
|
||||
fn next(&mut self) -> Option<ty::PolyTraitRef<'tcx>> {
|
||||
while let Some(pred) = self.base_iterator.next() {
|
||||
if let Some(data) = pred.as_trait_clause() {
|
||||
return Some(data.map_bound(|t| t.trait_ref));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn size_hint(&self) -> (usize, Option<usize>) {
|
||||
let (_, upper) = self.base_iterator.size_hint();
|
||||
(0, upper)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,9 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound {
|
|||
// For every projection predicate in the opaque type's explicit bounds,
|
||||
// check that the type that we're assigning actually satisfies the bounds
|
||||
// of the associated type.
|
||||
for (pred, pred_span) in
|
||||
cx.tcx.explicit_item_bounds(def_id).instantiate_identity_iter_copied()
|
||||
{
|
||||
for (pred, pred_span) in cx.tcx.explicit_item_bounds(def_id).iter_identity_copied() {
|
||||
infcx.enter_forall(pred.kind(), |predicate| {
|
||||
let ty::ClauseKind::Projection(proj) = predicate else {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -298,9 +298,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults {
|
|||
ty::Alias(ty::Opaque | ty::Projection, ty::AliasTy { def_id: def, .. }) => {
|
||||
elaborate(
|
||||
cx.tcx,
|
||||
cx.tcx
|
||||
.explicit_item_super_predicates(def)
|
||||
.instantiate_identity_iter_copied(),
|
||||
cx.tcx.explicit_item_super_predicates(def).iter_identity_copied(),
|
||||
)
|
||||
// We only care about self bounds for the impl-trait
|
||||
.filter_only_self()
|
||||
|
|
|
|||
|
|
@ -80,6 +80,7 @@ declare_lint_pass! {
|
|||
PRIVATE_BOUNDS,
|
||||
PRIVATE_INTERFACES,
|
||||
PROC_MACRO_DERIVE_RESOLUTION_FALLBACK,
|
||||
PTR_CAST_ADD_AUTO_TO_OBJECT,
|
||||
PUB_USE_OF_PRIVATE_EXTERN_CRATE,
|
||||
REDUNDANT_LIFETIMES,
|
||||
REFINING_IMPL_TRAIT_INTERNAL,
|
||||
|
|
@ -4189,6 +4190,7 @@ declare_lint! {
|
|||
reason: FutureIncompatibilityReason::FutureReleaseSemanticsChange,
|
||||
reference: "issue #123748 <https://github.com/rust-lang/rust/issues/123748>",
|
||||
};
|
||||
@edition Edition2024 => Deny;
|
||||
report_in_external_macro
|
||||
}
|
||||
|
||||
|
|
@ -4937,6 +4939,58 @@ declare_lint! {
|
|||
};
|
||||
}
|
||||
|
||||
declare_lint! {
|
||||
/// The `ptr_cast_add_auto_to_object` lint detects casts of raw pointers to trait
|
||||
/// objects, which add auto traits.
|
||||
///
|
||||
/// ### Example
|
||||
///
|
||||
/// ```rust,edition2021,compile_fail
|
||||
/// let ptr: *const dyn core::any::Any = &();
|
||||
/// _ = ptr as *const dyn core::any::Any + Send;
|
||||
/// ```
|
||||
///
|
||||
/// {{produces}}
|
||||
///
|
||||
/// ### Explanation
|
||||
///
|
||||
/// Adding an auto trait can make the vtable invalid, potentially causing
|
||||
/// UB in safe code afterwards. For example:
|
||||
///
|
||||
/// ```ignore (causes a warning)
|
||||
/// #![feature(arbitrary_self_types)]
|
||||
///
|
||||
/// trait Trait {
|
||||
/// fn f(self: *const Self)
|
||||
/// where
|
||||
/// Self: Send;
|
||||
/// }
|
||||
///
|
||||
/// impl Trait for *const () {
|
||||
/// fn f(self: *const Self) {
|
||||
/// unreachable!()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// fn main() {
|
||||
/// let unsend: *const () = &();
|
||||
/// let unsend: *const dyn Trait = &unsend;
|
||||
/// let send_bad: *const (dyn Trait + Send) = unsend as _;
|
||||
/// send_bad.f(); // this crashes, since vtable for `*const ()` does not have an entry for `f`
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Generally you must ensure that vtable is right for the pointer's type,
|
||||
/// before passing the pointer to safe code.
|
||||
pub PTR_CAST_ADD_AUTO_TO_OBJECT,
|
||||
Warn,
|
||||
"detects `as` casts from pointers to `dyn Trait` to pointers to `dyn Trait + Auto`",
|
||||
@future_incompatible = FutureIncompatibleInfo {
|
||||
reason: FutureIncompatibilityReason::FutureReleaseErrorReportInDeps,
|
||||
reference: "issue #127323 <https://github.com/rust-lang/rust/issues/127323>",
|
||||
};
|
||||
}
|
||||
|
||||
declare_lint! {
|
||||
/// The `out_of_scope_macro_calls` lint detects `macro_rules` called when they are not in scope,
|
||||
/// above their definition, which may happen in key-value attributes.
|
||||
|
|
|
|||
|
|
@ -31,9 +31,18 @@ pub struct Map<'hir> {
|
|||
|
||||
/// An iterator that walks up the ancestor tree of a given `HirId`.
|
||||
/// Constructed using `tcx.hir().parent_iter(hir_id)`.
|
||||
pub struct ParentHirIterator<'hir> {
|
||||
struct ParentHirIterator<'hir> {
|
||||
current_id: HirId,
|
||||
map: Map<'hir>,
|
||||
// Cache the current value of `hir_owner_nodes` to avoid repeatedly calling the same query for
|
||||
// the same owner, which will uselessly record many times the same query dependency.
|
||||
current_owner_nodes: Option<&'hir OwnerNodes<'hir>>,
|
||||
}
|
||||
|
||||
impl<'hir> ParentHirIterator<'hir> {
|
||||
fn new(map: Map<'hir>, current_id: HirId) -> ParentHirIterator<'hir> {
|
||||
ParentHirIterator { current_id, map, current_owner_nodes: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'hir> Iterator for ParentHirIterator<'hir> {
|
||||
|
|
@ -44,13 +53,22 @@ impl<'hir> Iterator for ParentHirIterator<'hir> {
|
|||
return None;
|
||||
}
|
||||
|
||||
// There are nodes that do not have entries, so we need to skip them.
|
||||
let parent_id = self.map.tcx.parent_hir_id(self.current_id);
|
||||
let HirId { owner, local_id } = self.current_id;
|
||||
|
||||
if parent_id == self.current_id {
|
||||
self.current_id = CRATE_HIR_ID;
|
||||
return None;
|
||||
}
|
||||
let parent_id = if local_id == ItemLocalId::ZERO {
|
||||
// We go from an owner to its parent, so clear the cache.
|
||||
self.current_owner_nodes = None;
|
||||
self.map.tcx.hir_owner_parent(owner)
|
||||
} else {
|
||||
let owner_nodes =
|
||||
self.current_owner_nodes.get_or_insert_with(|| self.map.tcx.hir_owner_nodes(owner));
|
||||
let parent_local_id = owner_nodes.nodes[local_id].parent;
|
||||
// HIR indexing should have checked that.
|
||||
debug_assert_ne!(parent_local_id, local_id);
|
||||
HirId { owner, local_id: parent_local_id }
|
||||
};
|
||||
|
||||
debug_assert_ne!(parent_id, self.current_id);
|
||||
|
||||
self.current_id = parent_id;
|
||||
return Some(parent_id);
|
||||
|
|
@ -479,7 +497,7 @@ impl<'hir> Map<'hir> {
|
|||
/// until the crate root is reached. Prefer this over your own loop using `parent_id`.
|
||||
#[inline]
|
||||
pub fn parent_id_iter(self, current_id: HirId) -> impl Iterator<Item = HirId> + 'hir {
|
||||
ParentHirIterator { current_id, map: self }
|
||||
ParentHirIterator::new(self, current_id)
|
||||
}
|
||||
|
||||
/// Returns an iterator for the nodes in the ancestor tree of the `current_id`
|
||||
|
|
|
|||
|
|
@ -854,6 +854,16 @@ impl<'tcx> TerminatorKind<'tcx> {
|
|||
}
|
||||
write!(fmt, ")")
|
||||
}
|
||||
TailCall { func, args, .. } => {
|
||||
write!(fmt, "tailcall {func:?}(")?;
|
||||
for (index, arg) in args.iter().enumerate() {
|
||||
if index > 0 {
|
||||
write!(fmt, ", ")?;
|
||||
}
|
||||
write!(fmt, "{:?}", arg)?;
|
||||
}
|
||||
write!(fmt, ")")
|
||||
}
|
||||
Assert { cond, expected, msg, .. } => {
|
||||
write!(fmt, "assert(")?;
|
||||
if !expected {
|
||||
|
|
@ -921,7 +931,12 @@ impl<'tcx> TerminatorKind<'tcx> {
|
|||
pub fn fmt_successor_labels(&self) -> Vec<Cow<'static, str>> {
|
||||
use self::TerminatorKind::*;
|
||||
match *self {
|
||||
Return | UnwindResume | UnwindTerminate(_) | Unreachable | CoroutineDrop => vec![],
|
||||
Return
|
||||
| TailCall { .. }
|
||||
| UnwindResume
|
||||
| UnwindTerminate(_)
|
||||
| Unreachable
|
||||
| CoroutineDrop => vec![],
|
||||
Goto { .. } => vec!["".into()],
|
||||
SwitchInt { ref targets, .. } => targets
|
||||
.values
|
||||
|
|
|
|||
|
|
@ -744,6 +744,36 @@ pub enum TerminatorKind<'tcx> {
|
|||
fn_span: Span,
|
||||
},
|
||||
|
||||
/// Tail call.
|
||||
///
|
||||
/// Roughly speaking this is a chimera of [`Call`] and [`Return`], with some caveats.
|
||||
/// Semantically tail calls consists of two actions:
|
||||
/// - pop of the current stack frame
|
||||
/// - a call to the `func`, with the return address of the **current** caller
|
||||
/// - so that a `return` inside `func` returns to the caller of the caller
|
||||
/// of the function that is currently being executed
|
||||
///
|
||||
/// Note that in difference with [`Call`] this is missing
|
||||
/// - `destination` (because it's always the return place)
|
||||
/// - `target` (because it's always taken from the current stack frame)
|
||||
/// - `unwind` (because it's always taken from the current stack frame)
|
||||
///
|
||||
/// [`Call`]: TerminatorKind::Call
|
||||
/// [`Return`]: TerminatorKind::Return
|
||||
TailCall {
|
||||
/// The function that’s being called.
|
||||
func: Operand<'tcx>,
|
||||
/// Arguments the function is called with.
|
||||
/// These are owned by the callee, which is free to modify them.
|
||||
/// This allows the memory occupied by "by-value" arguments to be
|
||||
/// reused across function calls without duplicating the contents.
|
||||
args: Box<[Spanned<Operand<'tcx>>]>,
|
||||
// FIXME(explicit_tail_calls): should we have the span for `become`? is this span accurate? do we need it?
|
||||
/// This `Span` is the span of the function, without the dot and receiver
|
||||
/// (e.g. `foo(a, b)` in `x.foo(a, b)`
|
||||
fn_span: Span,
|
||||
},
|
||||
|
||||
/// Evaluates the operand, which must have type `bool`. If it is not equal to `expected`,
|
||||
/// initiates a panic. Initiating a panic corresponds to a `Call` terminator with some
|
||||
/// unspecified constant as the function to call, all the operands stored in the `AssertMessage`
|
||||
|
|
@ -870,6 +900,7 @@ impl TerminatorKind<'_> {
|
|||
TerminatorKind::Unreachable => "Unreachable",
|
||||
TerminatorKind::Drop { .. } => "Drop",
|
||||
TerminatorKind::Call { .. } => "Call",
|
||||
TerminatorKind::TailCall { .. } => "TailCall",
|
||||
TerminatorKind::Assert { .. } => "Assert",
|
||||
TerminatorKind::Yield { .. } => "Yield",
|
||||
TerminatorKind::CoroutineDrop => "CoroutineDrop",
|
||||
|
|
|
|||
|
|
@ -439,6 +439,7 @@ mod helper {
|
|||
| CoroutineDrop
|
||||
| Return
|
||||
| Unreachable
|
||||
| TailCall { .. }
|
||||
| Call { target: None, unwind: _, .. } => (&[]).into_iter().copied().chain(None),
|
||||
InlineAsm { ref targets, unwind: UnwindAction::Cleanup(u), .. } => {
|
||||
targets.iter().copied().chain(Some(u))
|
||||
|
|
@ -479,6 +480,7 @@ mod helper {
|
|||
| CoroutineDrop
|
||||
| Return
|
||||
| Unreachable
|
||||
| TailCall { .. }
|
||||
| Call { target: None, unwind: _, .. } => (&mut []).into_iter().chain(None),
|
||||
InlineAsm { ref mut targets, unwind: UnwindAction::Cleanup(ref mut u), .. } => {
|
||||
targets.iter_mut().chain(Some(u))
|
||||
|
|
@ -501,6 +503,7 @@ impl<'tcx> TerminatorKind<'tcx> {
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::CoroutineDrop
|
||||
| TerminatorKind::Yield { .. }
|
||||
|
|
@ -521,6 +524,7 @@ impl<'tcx> TerminatorKind<'tcx> {
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::CoroutineDrop
|
||||
| TerminatorKind::Yield { .. }
|
||||
|
|
@ -606,9 +610,12 @@ impl<'tcx> TerminatorKind<'tcx> {
|
|||
pub fn edges(&self) -> TerminatorEdges<'_, 'tcx> {
|
||||
use TerminatorKind::*;
|
||||
match *self {
|
||||
Return | UnwindResume | UnwindTerminate(_) | CoroutineDrop | Unreachable => {
|
||||
TerminatorEdges::None
|
||||
}
|
||||
Return
|
||||
| TailCall { .. }
|
||||
| UnwindResume
|
||||
| UnwindTerminate(_)
|
||||
| CoroutineDrop
|
||||
| Unreachable => TerminatorEdges::None,
|
||||
|
||||
Goto { target } => TerminatorEdges::Single(target),
|
||||
|
||||
|
|
|
|||
|
|
@ -540,6 +540,17 @@ macro_rules! make_mir_visitor {
|
|||
);
|
||||
}
|
||||
|
||||
TerminatorKind::TailCall {
|
||||
func,
|
||||
args,
|
||||
fn_span: _,
|
||||
} => {
|
||||
self.visit_operand(func, location);
|
||||
for arg in args {
|
||||
self.visit_operand(&$($mutability)? arg.node, location);
|
||||
}
|
||||
},
|
||||
|
||||
TerminatorKind::Assert {
|
||||
cond,
|
||||
expected: _,
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ pub mod select;
|
|||
pub mod solve;
|
||||
pub mod specialization_graph;
|
||||
mod structural_impls;
|
||||
pub mod util;
|
||||
|
||||
use crate::mir::ConstraintCategory;
|
||||
use crate::ty::abstract_const::NotConstEvaluatable;
|
||||
|
|
|
|||
|
|
@ -1,62 +0,0 @@
|
|||
use rustc_data_structures::fx::FxHashSet;
|
||||
|
||||
use crate::ty::{Clause, PolyTraitRef, ToPolyTraitRef, TyCtxt, Upcast};
|
||||
|
||||
/// Given a [`PolyTraitRef`], get the [`Clause`]s implied by the trait's definition.
|
||||
///
|
||||
/// This only exists in `rustc_middle` because the more powerful elaborator depends on
|
||||
/// `rustc_infer` for elaborating outlives bounds -- this should only be used for pretty
|
||||
/// printing.
|
||||
pub fn super_predicates_for_pretty_printing<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
trait_ref: PolyTraitRef<'tcx>,
|
||||
) -> impl Iterator<Item = Clause<'tcx>> {
|
||||
let clause = trait_ref.upcast(tcx);
|
||||
Elaborator { tcx, visited: FxHashSet::from_iter([clause]), stack: vec![clause] }
|
||||
}
|
||||
|
||||
/// Like [`super_predicates_for_pretty_printing`], except it only returns traits and filters out
|
||||
/// all other [`Clause`]s.
|
||||
pub fn supertraits_for_pretty_printing<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
trait_ref: PolyTraitRef<'tcx>,
|
||||
) -> impl Iterator<Item = PolyTraitRef<'tcx>> {
|
||||
super_predicates_for_pretty_printing(tcx, trait_ref).filter_map(|clause| {
|
||||
clause.as_trait_clause().map(|trait_clause| trait_clause.to_poly_trait_ref())
|
||||
})
|
||||
}
|
||||
|
||||
struct Elaborator<'tcx> {
|
||||
tcx: TyCtxt<'tcx>,
|
||||
visited: FxHashSet<Clause<'tcx>>,
|
||||
stack: Vec<Clause<'tcx>>,
|
||||
}
|
||||
|
||||
impl<'tcx> Elaborator<'tcx> {
|
||||
fn elaborate(&mut self, trait_ref: PolyTraitRef<'tcx>) {
|
||||
let super_predicates =
|
||||
self.tcx.explicit_super_predicates_of(trait_ref.def_id()).predicates.iter().filter_map(
|
||||
|&(pred, _)| {
|
||||
let clause = pred.instantiate_supertrait(self.tcx, trait_ref);
|
||||
self.visited.insert(clause).then_some(clause)
|
||||
},
|
||||
);
|
||||
|
||||
self.stack.extend(super_predicates);
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Iterator for Elaborator<'tcx> {
|
||||
type Item = Clause<'tcx>;
|
||||
|
||||
fn next(&mut self) -> Option<Clause<'tcx>> {
|
||||
if let Some(clause) = self.stack.pop() {
|
||||
if let Some(trait_clause) = clause.as_trait_clause() {
|
||||
self.elaborate(trait_clause.to_poly_trait_ref());
|
||||
}
|
||||
Some(clause)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -229,6 +229,10 @@ impl<'tcx> rustc_type_ir::inherent::AdtDef<TyCtxt<'tcx>> for AdtDef<'tcx> {
|
|||
fn sized_constraint(self, tcx: TyCtxt<'tcx>) -> Option<ty::EarlyBinder<'tcx, Ty<'tcx>>> {
|
||||
self.sized_constraint(tcx)
|
||||
}
|
||||
|
||||
fn is_fundamental(self) -> bool {
|
||||
self.is_fundamental()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable, TyEncodable, TyDecodable)]
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ use crate::ty::{GenericArg, GenericArgs, GenericArgsRef};
|
|||
use rustc_ast::{self as ast, attr};
|
||||
use rustc_data_structures::defer;
|
||||
use rustc_data_structures::fingerprint::Fingerprint;
|
||||
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
|
||||
use rustc_data_structures::fx::FxHashMap;
|
||||
use rustc_data_structures::intern::Interned;
|
||||
use rustc_data_structures::profiling::SelfProfilerRef;
|
||||
use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
|
||||
|
|
@ -347,12 +347,16 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
|
|||
fn explicit_super_predicates_of(
|
||||
self,
|
||||
def_id: DefId,
|
||||
) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = ty::Clause<'tcx>>> {
|
||||
) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
|
||||
ty::EarlyBinder::bind(self.explicit_super_predicates_of(def_id).instantiate_identity(self))
|
||||
}
|
||||
|
||||
fn explicit_implied_predicates_of(
|
||||
self,
|
||||
def_id: DefId,
|
||||
) -> ty::EarlyBinder<'tcx, impl IntoIterator<Item = (ty::Clause<'tcx>, Span)>> {
|
||||
ty::EarlyBinder::bind(
|
||||
self.explicit_super_predicates_of(def_id)
|
||||
.instantiate_identity(self)
|
||||
.predicates
|
||||
.into_iter(),
|
||||
self.explicit_implied_predicates_of(def_id).instantiate_identity(self),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
@ -524,12 +528,12 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
|
|||
self.is_object_safe(trait_def_id)
|
||||
}
|
||||
|
||||
fn trait_may_be_implemented_via_object(self, trait_def_id: DefId) -> bool {
|
||||
self.trait_def(trait_def_id).implement_via_object
|
||||
fn trait_is_fundamental(self, def_id: DefId) -> bool {
|
||||
self.trait_def(def_id).is_fundamental
|
||||
}
|
||||
|
||||
fn supertrait_def_ids(self, trait_def_id: DefId) -> impl IntoIterator<Item = DefId> {
|
||||
self.supertrait_def_ids(trait_def_id)
|
||||
fn trait_may_be_implemented_via_object(self, trait_def_id: DefId) -> bool {
|
||||
self.trait_def(trait_def_id).implement_via_object
|
||||
}
|
||||
|
||||
fn delay_bug(self, msg: impl ToString) -> ErrorGuaranteed {
|
||||
|
|
@ -569,6 +573,13 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
|
|||
) -> Ty<'tcx> {
|
||||
placeholder.find_const_ty_from_env(param_env)
|
||||
}
|
||||
|
||||
fn anonymize_bound_vars<T: TypeFoldable<TyCtxt<'tcx>>>(
|
||||
self,
|
||||
binder: ty::Binder<'tcx, T>,
|
||||
) -> ty::Binder<'tcx, T> {
|
||||
self.anonymize_bound_vars(binder)
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! bidirectional_lang_item_map {
|
||||
|
|
@ -635,6 +646,10 @@ bidirectional_lang_item_map! {
|
|||
}
|
||||
|
||||
impl<'tcx> rustc_type_ir::inherent::DefId<TyCtxt<'tcx>> for DefId {
|
||||
fn is_local(self) -> bool {
|
||||
self.is_local()
|
||||
}
|
||||
|
||||
fn as_local(self) -> Option<LocalDefId> {
|
||||
self.as_local()
|
||||
}
|
||||
|
|
@ -2484,25 +2499,7 @@ impl<'tcx> TyCtxt<'tcx> {
|
|||
/// to identify which traits may define a given associated type to help avoid cycle errors,
|
||||
/// and to make size estimates for vtable layout computation.
|
||||
pub fn supertrait_def_ids(self, trait_def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
|
||||
let mut set = FxHashSet::default();
|
||||
let mut stack = vec![trait_def_id];
|
||||
|
||||
set.insert(trait_def_id);
|
||||
|
||||
iter::from_fn(move || -> Option<DefId> {
|
||||
let trait_did = stack.pop()?;
|
||||
let generic_predicates = self.explicit_super_predicates_of(trait_did);
|
||||
|
||||
for (predicate, _) in generic_predicates.predicates {
|
||||
if let ty::ClauseKind::Trait(data) = predicate.kind().skip_binder() {
|
||||
if set.insert(data.def_id()) {
|
||||
stack.push(data.def_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(trait_did)
|
||||
})
|
||||
rustc_type_ir::elaborate::supertrait_def_ids(self, trait_def_id)
|
||||
}
|
||||
|
||||
/// Given a closure signature, returns an equivalent fn signature. Detuples
|
||||
|
|
|
|||
84
compiler/rustc_middle/src/ty/elaborate_impl.rs
Normal file
84
compiler/rustc_middle/src/ty/elaborate_impl.rs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
use rustc_span::Span;
|
||||
use rustc_type_ir::elaborate::Elaboratable;
|
||||
|
||||
use crate::ty::{self, TyCtxt};
|
||||
|
||||
impl<'tcx> Elaboratable<TyCtxt<'tcx>> for ty::Clause<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.as_predicate()
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
clause
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
clause
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<TyCtxt<'tcx>> for ty::Predicate<'tcx> {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
*self
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
clause.as_predicate()
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
clause.as_predicate()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<TyCtxt<'tcx>> for (ty::Predicate<'tcx>, Span) {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
(clause.as_predicate(), self.1)
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
(clause.as_predicate(), self.1)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> Elaboratable<TyCtxt<'tcx>> for (ty::Clause<'tcx>, Span) {
|
||||
fn predicate(&self) -> ty::Predicate<'tcx> {
|
||||
self.0.as_predicate()
|
||||
}
|
||||
|
||||
fn child(&self, clause: ty::Clause<'tcx>) -> Self {
|
||||
(clause, self.1)
|
||||
}
|
||||
|
||||
fn child_with_derived_cause(
|
||||
&self,
|
||||
clause: ty::Clause<'tcx>,
|
||||
_span: Span,
|
||||
_parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
|
||||
_index: usize,
|
||||
) -> Self {
|
||||
(clause, self.1)
|
||||
}
|
||||
}
|
||||
|
|
@ -394,7 +394,7 @@ impl<'tcx> GenericPredicates<'tcx> {
|
|||
}
|
||||
|
||||
pub fn instantiate_own_identity(&self) -> impl Iterator<Item = (Clause<'tcx>, Span)> {
|
||||
EarlyBinder::bind(self.predicates).instantiate_identity_iter_copied()
|
||||
EarlyBinder::bind(self.predicates).iter_identity_copied()
|
||||
}
|
||||
|
||||
#[instrument(level = "debug", skip(self, tcx))]
|
||||
|
|
|
|||
|
|
@ -148,6 +148,7 @@ mod closure;
|
|||
mod consts;
|
||||
mod context;
|
||||
mod diagnostics;
|
||||
mod elaborate_impl;
|
||||
mod erase_regions;
|
||||
mod generic_args;
|
||||
mod generics;
|
||||
|
|
|
|||
|
|
@ -46,6 +46,10 @@ pub struct Predicate<'tcx>(
|
|||
);
|
||||
|
||||
impl<'tcx> rustc_type_ir::inherent::Predicate<TyCtxt<'tcx>> for Predicate<'tcx> {
|
||||
fn as_clause(self) -> Option<ty::Clause<'tcx>> {
|
||||
self.as_clause()
|
||||
}
|
||||
|
||||
fn is_coinductive(self, interner: TyCtxt<'tcx>) -> bool {
|
||||
self.is_coinductive(interner)
|
||||
}
|
||||
|
|
@ -173,7 +177,11 @@ pub struct Clause<'tcx>(
|
|||
pub(super) Interned<'tcx, WithCachedTypeInfo<ty::Binder<'tcx, PredicateKind<'tcx>>>>,
|
||||
);
|
||||
|
||||
impl<'tcx> rustc_type_ir::inherent::Clause<TyCtxt<'tcx>> for Clause<'tcx> {}
|
||||
impl<'tcx> rustc_type_ir::inherent::Clause<TyCtxt<'tcx>> for Clause<'tcx> {
|
||||
fn instantiate_supertrait(self, tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) -> Self {
|
||||
self.instantiate_supertrait(tcx, trait_ref)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'tcx> rustc_type_ir::inherent::IntoKind for Clause<'tcx> {
|
||||
type Kind = ty::Binder<'tcx, ClauseKind<'tcx>>;
|
||||
|
|
@ -341,6 +349,14 @@ impl<'tcx> ty::List<ty::PolyExistentialPredicate<'tcx>> {
|
|||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn without_auto_traits(
|
||||
&self,
|
||||
) -> impl Iterator<Item = ty::PolyExistentialPredicate<'tcx>> + '_ {
|
||||
self.iter().filter(|predicate| {
|
||||
!matches!(predicate.as_ref().skip_binder(), ExistentialPredicate::AutoTrait(_))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type PolyTraitRef<'tcx> = ty::Binder<'tcx, TraitRef<'tcx>>;
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
use crate::mir::interpret::{AllocRange, GlobalAlloc, Pointer, Provenance, Scalar};
|
||||
use crate::query::IntoQueryParam;
|
||||
use crate::query::Providers;
|
||||
use crate::traits::util::{super_predicates_for_pretty_printing, supertraits_for_pretty_printing};
|
||||
use crate::ty::GenericArgKind;
|
||||
use crate::ty::{
|
||||
ConstInt, Expr, ParamConst, ScalarInt, Term, TermKind, TypeFoldable, TypeSuperFoldable,
|
||||
|
|
@ -23,6 +22,7 @@ use rustc_span::symbol::{kw, Ident, Symbol};
|
|||
use rustc_span::FileNameDisplayPreference;
|
||||
use rustc_target::abi::Size;
|
||||
use rustc_target::spec::abi::Abi;
|
||||
use rustc_type_ir::{elaborate, Upcast as _};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use std::cell::Cell;
|
||||
|
|
@ -1255,14 +1255,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
|
|||
entry.has_fn_once = true;
|
||||
return;
|
||||
} else if self.tcx().is_lang_item(trait_def_id, LangItem::FnMut) {
|
||||
let super_trait_ref = supertraits_for_pretty_printing(self.tcx(), trait_ref)
|
||||
let super_trait_ref = elaborate::supertraits(self.tcx(), trait_ref)
|
||||
.find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
|
||||
.unwrap();
|
||||
|
||||
fn_traits.entry(super_trait_ref).or_default().fn_mut_trait_ref = Some(trait_ref);
|
||||
return;
|
||||
} else if self.tcx().is_lang_item(trait_def_id, LangItem::Fn) {
|
||||
let super_trait_ref = supertraits_for_pretty_printing(self.tcx(), trait_ref)
|
||||
let super_trait_ref = elaborate::supertraits(self.tcx(), trait_ref)
|
||||
.find(|super_trait_ref| super_trait_ref.def_id() == fn_once_trait)
|
||||
.unwrap();
|
||||
|
||||
|
|
@ -1343,10 +1343,11 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write {
|
|||
let bound_principal_with_self = bound_principal
|
||||
.with_self_ty(cx.tcx(), cx.tcx().types.trait_object_dummy_self);
|
||||
|
||||
let super_projections: Vec<_> =
|
||||
super_predicates_for_pretty_printing(cx.tcx(), bound_principal_with_self)
|
||||
.filter_map(|clause| clause.as_projection_clause())
|
||||
.collect();
|
||||
let clause: ty::Clause<'tcx> = bound_principal_with_self.upcast(cx.tcx());
|
||||
let super_projections: Vec<_> = elaborate::elaborate(cx.tcx(), [clause])
|
||||
.filter_only_self()
|
||||
.filter_map(|clause| clause.as_projection_clause())
|
||||
.collect();
|
||||
|
||||
let mut projections: Vec<_> = predicates
|
||||
.projection_bounds()
|
||||
|
|
|
|||
|
|
@ -811,6 +811,14 @@ impl<'tcx> rustc_type_ir::inherent::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
|
|||
Ty::new_var(tcx, vid)
|
||||
}
|
||||
|
||||
fn new_param(tcx: TyCtxt<'tcx>, param: ty::ParamTy) -> Self {
|
||||
Ty::new_param(tcx, param.index, param.name)
|
||||
}
|
||||
|
||||
fn new_placeholder(tcx: TyCtxt<'tcx>, placeholder: ty::PlaceholderType) -> Self {
|
||||
Ty::new_placeholder(tcx, placeholder)
|
||||
}
|
||||
|
||||
fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self {
|
||||
Ty::new_bound(interner, debruijn, var)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ pub struct TraitDef {
|
|||
/// and thus `impl`s of it are allowed to overlap.
|
||||
pub is_marker: bool,
|
||||
|
||||
/// If `true`, then this trait has to `#[rustc_coinductive]` attribute or
|
||||
/// If `true`, then this trait has the `#[rustc_coinductive]` attribute or
|
||||
/// is an auto trait. This indicates that trait solver cycles involving an
|
||||
/// `X: ThisTrait` goal are accepted.
|
||||
///
|
||||
|
|
@ -40,6 +40,11 @@ pub struct TraitDef {
|
|||
/// also have already switched to the new trait solver.
|
||||
pub is_coinductive: bool,
|
||||
|
||||
/// If `true`, then this trait has the `#[fundamental]` attribute. This
|
||||
/// affects how conherence computes whether a trait may have trait implementations
|
||||
/// added in the future.
|
||||
pub is_fundamental: bool,
|
||||
|
||||
/// If `true`, then this trait has the `#[rustc_skip_during_method_dispatch(array)]`
|
||||
/// attribute, indicating that editions before 2021 should not consider this trait
|
||||
/// during method dispatch if the receiver is an array.
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@ use crate::build::scope::BreakableTarget;
|
|||
use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder};
|
||||
use rustc_middle::middle::region;
|
||||
use rustc_middle::mir::*;
|
||||
use rustc_middle::span_bug;
|
||||
use rustc_middle::thir::*;
|
||||
use rustc_span::source_map::Spanned;
|
||||
use tracing::debug;
|
||||
|
||||
impl<'a, 'tcx> Builder<'a, 'tcx> {
|
||||
|
|
@ -91,9 +93,42 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
|
|||
ExprKind::Return { value } => {
|
||||
this.break_scope(block, value, BreakableTarget::Return, source_info)
|
||||
}
|
||||
// FIXME(explicit_tail_calls): properly lower tail calls here
|
||||
ExprKind::Become { value } => {
|
||||
this.break_scope(block, Some(value), BreakableTarget::Return, source_info)
|
||||
let v = &this.thir[value];
|
||||
let ExprKind::Scope { value, lint_level, region_scope } = v.kind else {
|
||||
span_bug!(v.span, "`thir_check_tail_calls` should have disallowed this {v:?}")
|
||||
};
|
||||
|
||||
let v = &this.thir[value];
|
||||
let ExprKind::Call { ref args, fun, fn_span, .. } = v.kind else {
|
||||
span_bug!(v.span, "`thir_check_tail_calls` should have disallowed this {v:?}")
|
||||
};
|
||||
|
||||
this.in_scope((region_scope, source_info), lint_level, |this| {
|
||||
let fun = unpack!(block = this.as_local_operand(block, fun));
|
||||
let args: Box<[_]> = args
|
||||
.into_iter()
|
||||
.copied()
|
||||
.map(|arg| Spanned {
|
||||
node: unpack!(block = this.as_local_call_operand(block, arg)),
|
||||
span: this.thir.exprs[arg].span,
|
||||
})
|
||||
.collect();
|
||||
|
||||
this.record_operands_moved(&args);
|
||||
|
||||
debug!("expr_into_dest: fn_span={:?}", fn_span);
|
||||
|
||||
unpack!(block = this.break_for_tail_call(block, &args, source_info));
|
||||
|
||||
this.cfg.terminate(
|
||||
block,
|
||||
source_info,
|
||||
TerminatorKind::TailCall { func: fun, args, fn_span },
|
||||
);
|
||||
|
||||
this.cfg.start_new_block().unit()
|
||||
})
|
||||
}
|
||||
_ => {
|
||||
assert!(
|
||||
|
|
|
|||
|
|
@ -745,6 +745,91 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
|
|||
self.cfg.terminate(block, source_info, TerminatorKind::UnwindResume);
|
||||
}
|
||||
|
||||
/// Sets up the drops for explict tail calls.
|
||||
///
|
||||
/// Unlike other kinds of early exits, tail calls do not go through the drop tree.
|
||||
/// Instead, all scheduled drops are immediately added to the CFG.
|
||||
pub(crate) fn break_for_tail_call(
|
||||
&mut self,
|
||||
mut block: BasicBlock,
|
||||
args: &[Spanned<Operand<'tcx>>],
|
||||
source_info: SourceInfo,
|
||||
) -> BlockAnd<()> {
|
||||
let arg_drops: Vec<_> = args
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|arg| match &arg.node {
|
||||
Operand::Copy(_) => bug!("copy op in tail call args"),
|
||||
Operand::Move(place) => {
|
||||
let local =
|
||||
place.as_local().unwrap_or_else(|| bug!("projection in tail call args"));
|
||||
|
||||
Some(DropData { source_info, local, kind: DropKind::Value })
|
||||
}
|
||||
Operand::Constant(_) => None,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut unwind_to = self.diverge_cleanup_target(
|
||||
self.scopes.scopes.iter().rev().nth(1).unwrap().region_scope,
|
||||
DUMMY_SP,
|
||||
);
|
||||
let unwind_drops = &mut self.scopes.unwind_drops;
|
||||
|
||||
// the innermost scope contains only the destructors for the tail call arguments
|
||||
// we only want to drop these in case of a panic, so we skip it
|
||||
for scope in self.scopes.scopes[1..].iter().rev().skip(1) {
|
||||
// FIXME(explicit_tail_calls) code duplication with `build_scope_drops`
|
||||
for drop_data in scope.drops.iter().rev() {
|
||||
let source_info = drop_data.source_info;
|
||||
let local = drop_data.local;
|
||||
|
||||
match drop_data.kind {
|
||||
DropKind::Value => {
|
||||
// `unwind_to` should drop the value that we're about to
|
||||
// schedule. If dropping this value panics, then we continue
|
||||
// with the *next* value on the unwind path.
|
||||
debug_assert_eq!(unwind_drops.drops[unwind_to].data.local, drop_data.local);
|
||||
debug_assert_eq!(unwind_drops.drops[unwind_to].data.kind, drop_data.kind);
|
||||
unwind_to = unwind_drops.drops[unwind_to].next;
|
||||
|
||||
let mut unwind_entry_point = unwind_to;
|
||||
|
||||
// the tail call arguments must be dropped if any of these drops panic
|
||||
for drop in arg_drops.iter().copied() {
|
||||
unwind_entry_point = unwind_drops.add_drop(drop, unwind_entry_point);
|
||||
}
|
||||
|
||||
unwind_drops.add_entry_point(block, unwind_entry_point);
|
||||
|
||||
let next = self.cfg.start_new_block();
|
||||
self.cfg.terminate(
|
||||
block,
|
||||
source_info,
|
||||
TerminatorKind::Drop {
|
||||
place: local.into(),
|
||||
target: next,
|
||||
unwind: UnwindAction::Continue,
|
||||
replace: false,
|
||||
},
|
||||
);
|
||||
block = next;
|
||||
}
|
||||
DropKind::Storage => {
|
||||
// Only temps and vars need their storage dead.
|
||||
assert!(local.index() > self.arg_count);
|
||||
self.cfg.push(
|
||||
block,
|
||||
Statement { source_info, kind: StatementKind::StorageDead(local) },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
block.unit()
|
||||
}
|
||||
|
||||
fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock {
|
||||
// If we are emitting a `drop` statement, we need to have the cached
|
||||
// diverge cleanup pads ready in case that drop panics.
|
||||
|
|
@ -1523,6 +1608,7 @@ impl<'tcx> DropTreeBuilder<'tcx> for Unwind {
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::Yield { .. }
|
||||
| TerminatorKind::CoroutineDrop
|
||||
|
|
|
|||
|
|
@ -217,12 +217,28 @@ impl<'mir, 'tcx, C: TerminatorClassifier<'tcx>> TriColorVisitor<BasicBlocks<'tcx
|
|||
| TerminatorKind::FalseUnwind { .. }
|
||||
| TerminatorKind::Goto { .. }
|
||||
| TerminatorKind::SwitchInt { .. } => ControlFlow::Continue(()),
|
||||
|
||||
// Note that tail call terminator technically returns to the caller,
|
||||
// but for purposes of this lint it makes sense to count it as possibly recursive,
|
||||
// since it's still a call.
|
||||
//
|
||||
// If this'll be repurposed for something else, this might need to be changed.
|
||||
TerminatorKind::TailCall { .. } => ControlFlow::Continue(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn node_settled(&mut self, bb: BasicBlock) -> ControlFlow<Self::BreakVal> {
|
||||
// When we examine a node for the last time, remember it if it is a recursive call.
|
||||
let terminator = self.body[bb].terminator();
|
||||
|
||||
// FIXME(explicit_tail_calls): highlight tail calls as "recursive call site"
|
||||
//
|
||||
// We don't want to lint functions that recurse only through tail calls
|
||||
// (such as `fn g() { become () }`), so just adding `| TailCall { ... }`
|
||||
// here won't work.
|
||||
//
|
||||
// But at the same time we would like to highlight both calls in a function like
|
||||
// `fn f() { if false { become f() } else { f() } }`, so we need to figure something out.
|
||||
if self.classifier.is_recursive_terminator(self.tcx, self.body, terminator) {
|
||||
self.reachable_recursive_calls.push(terminator.source_info.span);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -145,6 +145,7 @@ where
|
|||
| TerminatorKind::InlineAsm { .. }
|
||||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::SwitchInt { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::Yield { .. } => {}
|
||||
|
|
|
|||
|
|
@ -288,6 +288,7 @@ impl<'tcx> crate::GenKillAnalysis<'tcx> for MaybeRequiresStorage<'_, 'tcx> {
|
|||
| TerminatorKind::Goto { .. }
|
||||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::SwitchInt { .. }
|
||||
| TerminatorKind::Unreachable => {}
|
||||
}
|
||||
|
|
@ -325,6 +326,7 @@ impl<'tcx> crate::GenKillAnalysis<'tcx> for MaybeRequiresStorage<'_, 'tcx> {
|
|||
| TerminatorKind::Goto { .. }
|
||||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::SwitchInt { .. }
|
||||
| TerminatorKind::Unreachable => {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -489,6 +489,12 @@ impl<'b, 'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> Gatherer<'b, 'a, 'tcx, F> {
|
|||
self.gather_init(destination.as_ref(), InitKind::NonPanicPathOnly);
|
||||
}
|
||||
}
|
||||
TerminatorKind::TailCall { ref func, ref args, .. } => {
|
||||
self.gather_operand(func);
|
||||
for arg in args {
|
||||
self.gather_operand(&arg.node);
|
||||
}
|
||||
}
|
||||
TerminatorKind::InlineAsm {
|
||||
template: _,
|
||||
ref operands,
|
||||
|
|
|
|||
|
|
@ -269,6 +269,9 @@ pub trait ValueAnalysis<'tcx> {
|
|||
TerminatorKind::SwitchInt { discr, targets } => {
|
||||
return self.handle_switch_int(discr, targets, state);
|
||||
}
|
||||
TerminatorKind::TailCall { .. } => {
|
||||
// FIXME(explicit_tail_calls): determine if we need to do something here (probably not)
|
||||
}
|
||||
TerminatorKind::Goto { .. }
|
||||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
|
|
|
|||
|
|
@ -1367,6 +1367,10 @@ fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
|
|||
| TerminatorKind::Call { .. }
|
||||
| TerminatorKind::InlineAsm { .. }
|
||||
| TerminatorKind::Assert { .. } => return true,
|
||||
|
||||
TerminatorKind::TailCall { .. } => {
|
||||
unreachable!("tail calls can't be present in generators")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -1916,6 +1920,7 @@ impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::Drop { .. }
|
||||
| TerminatorKind::Assert { .. }
|
||||
|
|
|
|||
|
|
@ -40,7 +40,9 @@ impl<'b, 'tcx> CostChecker<'b, 'tcx> {
|
|||
fn is_call_like(bbd: &BasicBlockData<'_>) -> bool {
|
||||
use TerminatorKind::*;
|
||||
match bbd.terminator().kind {
|
||||
Call { .. } | Drop { .. } | Assert { .. } | InlineAsm { .. } => true,
|
||||
Call { .. } | TailCall { .. } | Drop { .. } | Assert { .. } | InlineAsm { .. } => {
|
||||
true
|
||||
}
|
||||
|
||||
Goto { .. }
|
||||
| SwitchInt { .. }
|
||||
|
|
@ -137,6 +139,9 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> {
|
|||
self.penalty += LANDINGPAD_PENALTY;
|
||||
}
|
||||
}
|
||||
TerminatorKind::TailCall { .. } => {
|
||||
self.penalty += CALL_PENALTY;
|
||||
}
|
||||
TerminatorKind::SwitchInt { discr, targets } => {
|
||||
if discr.constant().is_some() {
|
||||
// Not only will this become a `Goto`, but likely other
|
||||
|
|
|
|||
|
|
@ -358,9 +358,12 @@ fn bcb_filtered_successors<'a, 'tcx>(terminator: &'a Terminator<'tcx>) -> Covera
|
|||
}
|
||||
|
||||
// These terminators have no coverage-relevant successors.
|
||||
CoroutineDrop | Return | Unreachable | UnwindResume | UnwindTerminate(_) => {
|
||||
CoverageSuccessors::NotChainable(&[])
|
||||
}
|
||||
CoroutineDrop
|
||||
| Return
|
||||
| TailCall { .. }
|
||||
| Unreachable
|
||||
| UnwindResume
|
||||
| UnwindTerminate(_) => CoverageSuccessors::NotChainable(&[]),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -8,6 +8,10 @@ mod spans;
|
|||
mod tests;
|
||||
mod unexpand;
|
||||
|
||||
use rustc_hir as hir;
|
||||
use rustc_hir::intravisit::{walk_expr, Visitor};
|
||||
use rustc_middle::hir::map::Map;
|
||||
use rustc_middle::hir::nested_filter;
|
||||
use rustc_middle::mir::coverage::{
|
||||
CodeRegion, CoverageKind, DecisionInfo, FunctionCoverageInfo, Mapping, MappingKind,
|
||||
};
|
||||
|
|
@ -465,6 +469,9 @@ struct ExtractedHirInfo {
|
|||
/// Must have the same context and filename as the body span.
|
||||
fn_sig_span_extended: Option<Span>,
|
||||
body_span: Span,
|
||||
/// "Holes" are regions within the body span that should not be included in
|
||||
/// coverage spans for this function (e.g. closures and nested items).
|
||||
hole_spans: Vec<Span>,
|
||||
}
|
||||
|
||||
fn extract_hir_info<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ExtractedHirInfo {
|
||||
|
|
@ -480,7 +487,7 @@ fn extract_hir_info<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ExtractedHir
|
|||
|
||||
let mut body_span = hir_body.value.span;
|
||||
|
||||
use rustc_hir::{Closure, Expr, ExprKind, Node};
|
||||
use hir::{Closure, Expr, ExprKind, Node};
|
||||
// Unexpand a closure's body span back to the context of its declaration.
|
||||
// This helps with closure bodies that consist of just a single bang-macro,
|
||||
// and also with closure bodies produced by async desugaring.
|
||||
|
|
@ -507,11 +514,78 @@ fn extract_hir_info<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ExtractedHir
|
|||
|
||||
let function_source_hash = hash_mir_source(tcx, hir_body);
|
||||
|
||||
ExtractedHirInfo { function_source_hash, is_async_fn, fn_sig_span_extended, body_span }
|
||||
let hole_spans = extract_hole_spans_from_hir(tcx, body_span, hir_body);
|
||||
|
||||
ExtractedHirInfo {
|
||||
function_source_hash,
|
||||
is_async_fn,
|
||||
fn_sig_span_extended,
|
||||
body_span,
|
||||
hole_spans,
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_mir_source<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx rustc_hir::Body<'tcx>) -> u64 {
|
||||
fn hash_mir_source<'tcx>(tcx: TyCtxt<'tcx>, hir_body: &'tcx hir::Body<'tcx>) -> u64 {
|
||||
// FIXME(cjgillot) Stop hashing HIR manually here.
|
||||
let owner = hir_body.id().hir_id.owner;
|
||||
tcx.hir_owner_nodes(owner).opt_hash_including_bodies.unwrap().to_smaller_hash().as_u64()
|
||||
}
|
||||
|
||||
fn extract_hole_spans_from_hir<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
body_span: Span, // Usually `hir_body.value.span`, but not always
|
||||
hir_body: &hir::Body<'tcx>,
|
||||
) -> Vec<Span> {
|
||||
struct HolesVisitor<'hir, F> {
|
||||
hir: Map<'hir>,
|
||||
visit_hole_span: F,
|
||||
}
|
||||
|
||||
impl<'hir, F: FnMut(Span)> Visitor<'hir> for HolesVisitor<'hir, F> {
|
||||
/// - We need `NestedFilter::INTRA = true` so that `visit_item` will be called.
|
||||
/// - Bodies of nested items don't actually get visited, because of the
|
||||
/// `visit_item` override.
|
||||
/// - For nested bodies that are not part of an item, we do want to visit any
|
||||
/// items contained within them.
|
||||
type NestedFilter = nested_filter::All;
|
||||
|
||||
fn nested_visit_map(&mut self) -> Self::Map {
|
||||
self.hir
|
||||
}
|
||||
|
||||
fn visit_item(&mut self, item: &'hir hir::Item<'hir>) {
|
||||
(self.visit_hole_span)(item.span);
|
||||
// Having visited this item, we don't care about its children,
|
||||
// so don't call `walk_item`.
|
||||
}
|
||||
|
||||
// We override `visit_expr` instead of the more specific expression
|
||||
// visitors, so that we have direct access to the expression span.
|
||||
fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
|
||||
match expr.kind {
|
||||
hir::ExprKind::Closure(_) | hir::ExprKind::ConstBlock(_) => {
|
||||
(self.visit_hole_span)(expr.span);
|
||||
// Having visited this expression, we don't care about its
|
||||
// children, so don't call `walk_expr`.
|
||||
}
|
||||
|
||||
// For other expressions, recursively visit as normal.
|
||||
_ => walk_expr(self, expr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut hole_spans = vec![];
|
||||
let mut visitor = HolesVisitor {
|
||||
hir: tcx.hir(),
|
||||
visit_hole_span: |hole_span| {
|
||||
// Discard any holes that aren't directly visible within the body span.
|
||||
if body_span.contains(hole_span) && body_span.eq_ctxt(hole_span) {
|
||||
hole_spans.push(hole_span);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
visitor.visit_body(hir_body);
|
||||
hole_spans
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use rustc_span::Span;
|
|||
use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph};
|
||||
use crate::coverage::mappings;
|
||||
use crate::coverage::spans::from_mir::{
|
||||
extract_covspans_and_holes_from_mir, ExtractedCovspans, Hole, SpanFromMir,
|
||||
extract_covspans_from_mir, ExtractedCovspans, Hole, SpanFromMir,
|
||||
};
|
||||
use crate::coverage::ExtractedHirInfo;
|
||||
|
||||
|
|
@ -20,8 +20,8 @@ pub(super) fn extract_refined_covspans(
|
|||
basic_coverage_blocks: &CoverageGraph,
|
||||
code_mappings: &mut impl Extend<mappings::CodeMapping>,
|
||||
) {
|
||||
let ExtractedCovspans { mut covspans, mut holes } =
|
||||
extract_covspans_and_holes_from_mir(mir_body, hir_info, basic_coverage_blocks);
|
||||
let ExtractedCovspans { mut covspans } =
|
||||
extract_covspans_from_mir(mir_body, hir_info, basic_coverage_blocks);
|
||||
|
||||
// First, perform the passes that need macro information.
|
||||
covspans.sort_by(|a, b| basic_coverage_blocks.cmp_in_dominator_order(a.bcb, b.bcb));
|
||||
|
|
@ -45,6 +45,7 @@ pub(super) fn extract_refined_covspans(
|
|||
covspans.dedup_by(|b, a| a.span.source_equal(b.span));
|
||||
|
||||
// Sort the holes, and merge overlapping/adjacent holes.
|
||||
let mut holes = hir_info.hole_spans.iter().map(|&span| Hole { span }).collect::<Vec<_>>();
|
||||
holes.sort_by(|a, b| compare_spans(a.span, b.span));
|
||||
holes.dedup_by(|b, a| a.merge_if_overlapping_or_adjacent(b));
|
||||
|
||||
|
|
|
|||
|
|
@ -1,8 +1,7 @@
|
|||
use rustc_middle::bug;
|
||||
use rustc_middle::mir::coverage::CoverageKind;
|
||||
use rustc_middle::mir::{
|
||||
self, AggregateKind, FakeReadCause, Rvalue, Statement, StatementKind, Terminator,
|
||||
TerminatorKind,
|
||||
self, FakeReadCause, Statement, StatementKind, Terminator, TerminatorKind,
|
||||
};
|
||||
use rustc_span::{Span, Symbol};
|
||||
|
||||
|
|
@ -15,13 +14,12 @@ use crate::coverage::ExtractedHirInfo;
|
|||
|
||||
pub(crate) struct ExtractedCovspans {
|
||||
pub(crate) covspans: Vec<SpanFromMir>,
|
||||
pub(crate) holes: Vec<Hole>,
|
||||
}
|
||||
|
||||
/// Traverses the MIR body to produce an initial collection of coverage-relevant
|
||||
/// spans, each associated with a node in the coverage graph (BCB) and possibly
|
||||
/// other metadata.
|
||||
pub(crate) fn extract_covspans_and_holes_from_mir(
|
||||
pub(crate) fn extract_covspans_from_mir(
|
||||
mir_body: &mir::Body<'_>,
|
||||
hir_info: &ExtractedHirInfo,
|
||||
basic_coverage_blocks: &CoverageGraph,
|
||||
|
|
@ -29,21 +27,13 @@ pub(crate) fn extract_covspans_and_holes_from_mir(
|
|||
let &ExtractedHirInfo { body_span, .. } = hir_info;
|
||||
|
||||
let mut covspans = vec![];
|
||||
let mut holes = vec![];
|
||||
|
||||
for (bcb, bcb_data) in basic_coverage_blocks.iter_enumerated() {
|
||||
bcb_to_initial_coverage_spans(
|
||||
mir_body,
|
||||
body_span,
|
||||
bcb,
|
||||
bcb_data,
|
||||
&mut covspans,
|
||||
&mut holes,
|
||||
);
|
||||
bcb_to_initial_coverage_spans(mir_body, body_span, bcb, bcb_data, &mut covspans);
|
||||
}
|
||||
|
||||
// Only add the signature span if we found at least one span in the body.
|
||||
if !covspans.is_empty() || !holes.is_empty() {
|
||||
if !covspans.is_empty() {
|
||||
// If there is no usable signature span, add a fake one (before refinement)
|
||||
// to avoid an ugly gap between the body start and the first real span.
|
||||
// FIXME: Find a more principled way to solve this problem.
|
||||
|
|
@ -51,7 +41,7 @@ pub(crate) fn extract_covspans_and_holes_from_mir(
|
|||
covspans.push(SpanFromMir::for_fn_sig(fn_sig_span));
|
||||
}
|
||||
|
||||
ExtractedCovspans { covspans, holes }
|
||||
ExtractedCovspans { covspans }
|
||||
}
|
||||
|
||||
// Generate a set of coverage spans from the filtered set of `Statement`s and `Terminator`s of
|
||||
|
|
@ -65,7 +55,6 @@ fn bcb_to_initial_coverage_spans<'a, 'tcx>(
|
|||
bcb: BasicCoverageBlock,
|
||||
bcb_data: &'a BasicCoverageBlockData,
|
||||
initial_covspans: &mut Vec<SpanFromMir>,
|
||||
holes: &mut Vec<Hole>,
|
||||
) {
|
||||
for &bb in &bcb_data.basic_blocks {
|
||||
let data = &mir_body[bb];
|
||||
|
|
@ -81,13 +70,7 @@ fn bcb_to_initial_coverage_spans<'a, 'tcx>(
|
|||
let expn_span = filtered_statement_span(statement)?;
|
||||
let (span, visible_macro) = unexpand(expn_span)?;
|
||||
|
||||
// A statement that looks like the assignment of a closure expression
|
||||
// is treated as a "hole" span, to be carved out of other spans.
|
||||
if is_closure_like(statement) {
|
||||
holes.push(Hole { span });
|
||||
} else {
|
||||
initial_covspans.push(SpanFromMir::new(span, visible_macro, bcb));
|
||||
}
|
||||
initial_covspans.push(SpanFromMir::new(span, visible_macro, bcb));
|
||||
Some(())
|
||||
};
|
||||
for statement in data.statements.iter() {
|
||||
|
|
@ -105,18 +88,6 @@ fn bcb_to_initial_coverage_spans<'a, 'tcx>(
|
|||
}
|
||||
}
|
||||
|
||||
fn is_closure_like(statement: &Statement<'_>) -> bool {
|
||||
match statement.kind {
|
||||
StatementKind::Assign(box (_, Rvalue::Aggregate(box ref agg_kind, _))) => match agg_kind {
|
||||
AggregateKind::Closure(_, _)
|
||||
| AggregateKind::Coroutine(_, _)
|
||||
| AggregateKind::CoroutineClosure(..) => true,
|
||||
_ => false,
|
||||
},
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// If the MIR `Statement` has a span contributive to computing coverage spans,
|
||||
/// return it; otherwise return `None`.
|
||||
fn filtered_statement_span(statement: &Statement<'_>) -> Option<Span> {
|
||||
|
|
@ -193,7 +164,8 @@ fn filtered_terminator_span(terminator: &Terminator<'_>) -> Option<Span> {
|
|||
| TerminatorKind::Goto { .. } => None,
|
||||
|
||||
// Call `func` operand can have a more specific span when part of a chain of calls
|
||||
| TerminatorKind::Call { ref func, .. } => {
|
||||
TerminatorKind::Call { ref func, .. }
|
||||
| TerminatorKind::TailCall { ref func, .. } => {
|
||||
let mut span = terminator.source_info.span;
|
||||
if let mir::Operand::Constant(box constant) = func {
|
||||
if constant.span.lo() > span.lo() {
|
||||
|
|
|
|||
|
|
@ -628,6 +628,12 @@ impl WriteInfo {
|
|||
self.add_operand(&arg.node);
|
||||
}
|
||||
}
|
||||
TerminatorKind::TailCall { func, args, .. } => {
|
||||
self.add_operand(func);
|
||||
for arg in args {
|
||||
self.add_operand(&arg.node);
|
||||
}
|
||||
}
|
||||
TerminatorKind::InlineAsm { operands, .. } => {
|
||||
for asm_operand in operands {
|
||||
match asm_operand {
|
||||
|
|
|
|||
|
|
@ -1391,11 +1391,15 @@ fn op_to_prop_const<'tcx>(
|
|||
let (prov, offset) = pointer.into_parts();
|
||||
let alloc_id = prov.alloc_id();
|
||||
intern_const_alloc_for_constprop(ecx, alloc_id).ok()?;
|
||||
if matches!(ecx.tcx.global_alloc(alloc_id), GlobalAlloc::Memory(_)) {
|
||||
// `alloc_id` may point to a static. Codegen will choke on an `Indirect` with anything
|
||||
// by `GlobalAlloc::Memory`, so do fall through to copying if needed.
|
||||
// FIXME: find a way to treat this more uniformly
|
||||
// (probably by fixing codegen)
|
||||
|
||||
// `alloc_id` may point to a static. Codegen will choke on an `Indirect` with anything
|
||||
// by `GlobalAlloc::Memory`, so do fall through to copying if needed.
|
||||
// FIXME: find a way to treat this more uniformly (probably by fixing codegen)
|
||||
if let GlobalAlloc::Memory(alloc) = ecx.tcx.global_alloc(alloc_id)
|
||||
// Transmuting a constant is just an offset in the allocation. If the alignment of the
|
||||
// allocation is not enough, fallback to copying into a properly aligned value.
|
||||
&& alloc.inner().align >= op.layout.align.abi
|
||||
{
|
||||
return Some(ConstValue::Indirect { alloc_id, offset });
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -383,6 +383,8 @@ impl<'tcx> Inliner<'tcx> {
|
|||
) -> Option<CallSite<'tcx>> {
|
||||
// Only consider direct calls to functions
|
||||
let terminator = bb_data.terminator();
|
||||
|
||||
// FIXME(explicit_tail_calls): figure out if we can inline tail calls
|
||||
if let TerminatorKind::Call { ref func, fn_span, .. } = terminator.kind {
|
||||
let func_ty = func.ty(caller_body, self.tcx);
|
||||
if let ty::FnDef(def_id, args) = *func_ty.kind() {
|
||||
|
|
@ -550,6 +552,9 @@ impl<'tcx> Inliner<'tcx> {
|
|||
// inline-asm is detected. LLVM will still possibly do an inline later on
|
||||
// if the no-attribute function ends up with the same instruction set anyway.
|
||||
return Err("Cannot move inline-asm across instruction sets");
|
||||
} else if let TerminatorKind::TailCall { .. } = term.kind {
|
||||
// FIXME(explicit_tail_calls): figure out how exactly functions containing tail calls can be inlined (and if they even should)
|
||||
return Err("can't inline functions with tail calls");
|
||||
} else {
|
||||
work_list.extend(term.successors())
|
||||
}
|
||||
|
|
@ -1038,6 +1043,10 @@ impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
|
|||
*target = self.map_block(*target);
|
||||
*unwind = self.map_unwind(*unwind);
|
||||
}
|
||||
TerminatorKind::TailCall { .. } => {
|
||||
// check_mir_body forbids tail calls
|
||||
unreachable!()
|
||||
}
|
||||
TerminatorKind::Call { ref mut target, ref mut unwind, .. } => {
|
||||
if let Some(ref mut tgt) = *target {
|
||||
*tgt = self.map_block(*tgt);
|
||||
|
|
|
|||
|
|
@ -596,6 +596,7 @@ impl<'tcx, 'a> TOFinder<'tcx, 'a> {
|
|||
TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::CoroutineDrop => bug!("{term:?} has no terminators"),
|
||||
// Disallowed during optimizations.
|
||||
|
|
|
|||
|
|
@ -799,6 +799,7 @@ impl<'tcx> Visitor<'tcx> for ConstPropagator<'_, 'tcx> {
|
|||
| TerminatorKind::UnwindResume
|
||||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Return
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::Drop { .. }
|
||||
| TerminatorKind::Yield { .. }
|
||||
|
|
|
|||
|
|
@ -38,7 +38,7 @@ impl<'tcx> Visitor<'tcx> for MentionedItemsVisitor<'_, 'tcx> {
|
|||
self.super_terminator(terminator, location);
|
||||
let span = || self.body.source_info(location).span;
|
||||
match &terminator.kind {
|
||||
mir::TerminatorKind::Call { func, .. } => {
|
||||
mir::TerminatorKind::Call { func, .. } | mir::TerminatorKind::TailCall { func, .. } => {
|
||||
let callee_ty = func.ty(self.body, self.tcx);
|
||||
self.mentioned_items
|
||||
.push(Spanned { node: MentionedItem::Fn(callee_ty), span: span() });
|
||||
|
|
|
|||
|
|
@ -75,6 +75,7 @@ impl RemoveNoopLandingPads {
|
|||
| TerminatorKind::UnwindTerminate(_)
|
||||
| TerminatorKind::Unreachable
|
||||
| TerminatorKind::Call { .. }
|
||||
| TerminatorKind::TailCall { .. }
|
||||
| TerminatorKind::Assert { .. }
|
||||
| TerminatorKind::Drop { .. }
|
||||
| TerminatorKind::InlineAsm { .. } => false,
|
||||
|
|
|
|||
|
|
@ -400,40 +400,44 @@ impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
|
|||
self.check_edge(location, *target, EdgeKind::Normal);
|
||||
self.check_unwind_edge(location, *unwind);
|
||||
}
|
||||
TerminatorKind::Call { args, destination, target, unwind, .. } => {
|
||||
if let Some(target) = target {
|
||||
self.check_edge(location, *target, EdgeKind::Normal);
|
||||
}
|
||||
self.check_unwind_edge(location, *unwind);
|
||||
TerminatorKind::Call { args, .. } | TerminatorKind::TailCall { args, .. } => {
|
||||
// FIXME(explicit_tail_calls): refactor this & add tail-call specific checks
|
||||
if let TerminatorKind::Call { target, unwind, destination, .. } = terminator.kind {
|
||||
if let Some(target) = target {
|
||||
self.check_edge(location, target, EdgeKind::Normal);
|
||||
}
|
||||
self.check_unwind_edge(location, unwind);
|
||||
|
||||
// The code generation assumes that there are no critical call edges. The assumption
|
||||
// is used to simplify inserting code that should be executed along the return edge
|
||||
// from the call. FIXME(tmiasko): Since this is a strictly code generation concern,
|
||||
// the code generation should be responsible for handling it.
|
||||
if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Optimized)
|
||||
&& self.is_critical_call_edge(*target, *unwind)
|
||||
{
|
||||
self.fail(
|
||||
location,
|
||||
format!(
|
||||
"encountered critical edge in `Call` terminator {:?}",
|
||||
terminator.kind,
|
||||
),
|
||||
);
|
||||
// The code generation assumes that there are no critical call edges. The assumption
|
||||
// is used to simplify inserting code that should be executed along the return edge
|
||||
// from the call. FIXME(tmiasko): Since this is a strictly code generation concern,
|
||||
// the code generation should be responsible for handling it.
|
||||
if self.mir_phase >= MirPhase::Runtime(RuntimePhase::Optimized)
|
||||
&& self.is_critical_call_edge(target, unwind)
|
||||
{
|
||||
self.fail(
|
||||
location,
|
||||
format!(
|
||||
"encountered critical edge in `Call` terminator {:?}",
|
||||
terminator.kind,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// The call destination place and Operand::Move place used as an argument might be
|
||||
// passed by a reference to the callee. Consequently they cannot be packed.
|
||||
if is_within_packed(self.tcx, &self.body.local_decls, destination).is_some() {
|
||||
// This is bad! The callee will expect the memory to be aligned.
|
||||
self.fail(
|
||||
location,
|
||||
format!(
|
||||
"encountered packed place in `Call` terminator destination: {:?}",
|
||||
terminator.kind,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The call destination place and Operand::Move place used as an argument might be
|
||||
// passed by a reference to the callee. Consequently they cannot be packed.
|
||||
if is_within_packed(self.tcx, &self.body.local_decls, *destination).is_some() {
|
||||
// This is bad! The callee will expect the memory to be aligned.
|
||||
self.fail(
|
||||
location,
|
||||
format!(
|
||||
"encountered packed place in `Call` terminator destination: {:?}",
|
||||
terminator.kind,
|
||||
),
|
||||
);
|
||||
}
|
||||
for arg in args {
|
||||
if let Operand::Move(place) = &arg.node {
|
||||
if is_within_packed(self.tcx, &self.body.local_decls, *place).is_some() {
|
||||
|
|
@ -1498,15 +1502,22 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
|
|||
}
|
||||
}
|
||||
}
|
||||
TerminatorKind::Call { func, .. } => {
|
||||
TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => {
|
||||
let func_ty = func.ty(&self.body.local_decls, self.tcx);
|
||||
match func_ty.kind() {
|
||||
ty::FnPtr(..) | ty::FnDef(..) => {}
|
||||
_ => self.fail(
|
||||
location,
|
||||
format!("encountered non-callable type {func_ty} in `Call` terminator"),
|
||||
format!(
|
||||
"encountered non-callable type {func_ty} in `{}` terminator",
|
||||
terminator.kind.name()
|
||||
),
|
||||
),
|
||||
}
|
||||
|
||||
if let TerminatorKind::TailCall { .. } = terminator.kind {
|
||||
// FIXME(explicit_tail_calls): implement tail-call specific checks here (such as signature matching, forbidding closures, etc)
|
||||
}
|
||||
}
|
||||
TerminatorKind::Assert { cond, .. } => {
|
||||
let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
|
||||
|
|
|
|||
|
|
@ -755,7 +755,8 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> {
|
|||
};
|
||||
|
||||
match terminator.kind {
|
||||
mir::TerminatorKind::Call { ref func, ref args, ref fn_span, .. } => {
|
||||
mir::TerminatorKind::Call { ref func, ref args, ref fn_span, .. }
|
||||
| mir::TerminatorKind::TailCall { ref func, ref args, ref fn_span } => {
|
||||
let callee_ty = func.ty(self.body, tcx);
|
||||
// *Before* monomorphizing, record that we already handled this mention.
|
||||
self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty));
|
||||
|
|
|
|||
469
compiler/rustc_next_trait_solver/src/coherence.rs
Normal file
469
compiler/rustc_next_trait_solver/src/coherence.rs
Normal file
|
|
@ -0,0 +1,469 @@
|
|||
use std::fmt::Debug;
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
use rustc_type_ir::inherent::*;
|
||||
use rustc_type_ir::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor};
|
||||
use rustc_type_ir::{self as ty, InferCtxtLike, Interner};
|
||||
use tracing::instrument;
|
||||
|
||||
/// Whether we do the orphan check relative to this crate or to some remote crate.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum InCrate {
|
||||
Local { mode: OrphanCheckMode },
|
||||
Remote,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum OrphanCheckMode {
|
||||
/// Proper orphan check.
|
||||
Proper,
|
||||
/// Improper orphan check for backward compatibility.
|
||||
///
|
||||
/// In this mode, type params inside projections are considered to be covered
|
||||
/// even if the projection may normalize to a type that doesn't actually cover
|
||||
/// them. This is unsound. See also [#124559] and [#99554].
|
||||
///
|
||||
/// [#124559]: https://github.com/rust-lang/rust/issues/124559
|
||||
/// [#99554]: https://github.com/rust-lang/rust/issues/99554
|
||||
Compat,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum Conflict {
|
||||
Upstream,
|
||||
Downstream,
|
||||
}
|
||||
|
||||
/// Returns whether all impls which would apply to the `trait_ref`
|
||||
/// e.g. `Ty: Trait<Arg>` are already known in the local crate.
|
||||
///
|
||||
/// This both checks whether any downstream or sibling crates could
|
||||
/// implement it and whether an upstream crate can add this impl
|
||||
/// without breaking backwards compatibility.
|
||||
#[instrument(level = "debug", skip(infcx, lazily_normalize_ty), ret)]
|
||||
pub fn trait_ref_is_knowable<Infcx, I, E>(
|
||||
infcx: &Infcx,
|
||||
trait_ref: ty::TraitRef<I>,
|
||||
mut lazily_normalize_ty: impl FnMut(I::Ty) -> Result<I::Ty, E>,
|
||||
) -> Result<Result<(), Conflict>, E>
|
||||
where
|
||||
Infcx: InferCtxtLike<Interner = I>,
|
||||
I: Interner,
|
||||
E: Debug,
|
||||
{
|
||||
if orphan_check_trait_ref(infcx, trait_ref, InCrate::Remote, &mut lazily_normalize_ty)?.is_ok()
|
||||
{
|
||||
// A downstream or cousin crate is allowed to implement some
|
||||
// generic parameters of this trait-ref.
|
||||
return Ok(Err(Conflict::Downstream));
|
||||
}
|
||||
|
||||
if trait_ref_is_local_or_fundamental(infcx.cx(), trait_ref) {
|
||||
// This is a local or fundamental trait, so future-compatibility
|
||||
// is no concern. We know that downstream/cousin crates are not
|
||||
// allowed to implement a generic parameter of this trait ref,
|
||||
// which means impls could only come from dependencies of this
|
||||
// crate, which we already know about.
|
||||
return Ok(Ok(()));
|
||||
}
|
||||
|
||||
// This is a remote non-fundamental trait, so if another crate
|
||||
// can be the "final owner" of the generic parameters of this trait-ref,
|
||||
// they are allowed to implement it future-compatibly.
|
||||
//
|
||||
// However, if we are a final owner, then nobody else can be,
|
||||
// and if we are an intermediate owner, then we don't care
|
||||
// about future-compatibility, which means that we're OK if
|
||||
// we are an owner.
|
||||
if orphan_check_trait_ref(
|
||||
infcx,
|
||||
trait_ref,
|
||||
InCrate::Local { mode: OrphanCheckMode::Proper },
|
||||
&mut lazily_normalize_ty,
|
||||
)?
|
||||
.is_ok()
|
||||
{
|
||||
Ok(Ok(()))
|
||||
} else {
|
||||
Ok(Err(Conflict::Upstream))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn trait_ref_is_local_or_fundamental<I: Interner>(tcx: I, trait_ref: ty::TraitRef<I>) -> bool {
|
||||
trait_ref.def_id.is_local() || tcx.trait_is_fundamental(trait_ref.def_id)
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
pub enum IsFirstInputType {
|
||||
No,
|
||||
Yes,
|
||||
}
|
||||
|
||||
impl From<bool> for IsFirstInputType {
|
||||
fn from(b: bool) -> IsFirstInputType {
|
||||
match b {
|
||||
false => IsFirstInputType::No,
|
||||
true => IsFirstInputType::Yes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug(bound = "T: Debug"))]
|
||||
pub enum OrphanCheckErr<I: Interner, T> {
|
||||
NonLocalInputType(Vec<(I::Ty, IsFirstInputType)>),
|
||||
UncoveredTyParams(UncoveredTyParams<I, T>),
|
||||
}
|
||||
|
||||
#[derive(derivative::Derivative)]
|
||||
#[derivative(Debug(bound = "T: Debug"))]
|
||||
pub struct UncoveredTyParams<I: Interner, T> {
|
||||
pub uncovered: T,
|
||||
pub local_ty: Option<I::Ty>,
|
||||
}
|
||||
|
||||
/// Checks whether a trait-ref is potentially implementable by a crate.
|
||||
///
|
||||
/// The current rule is that a trait-ref orphan checks in a crate C:
|
||||
///
|
||||
/// 1. Order the parameters in the trait-ref in generic parameters order
|
||||
/// - Self first, others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
|
||||
/// 2. Of these type parameters, there is at least one type parameter
|
||||
/// in which, walking the type as a tree, you can reach a type local
|
||||
/// to C where all types in-between are fundamental types. Call the
|
||||
/// first such parameter the "local key parameter".
|
||||
/// - e.g., `Box<LocalType>` is OK, because you can visit LocalType
|
||||
/// going through `Box`, which is fundamental.
|
||||
/// - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
|
||||
/// the same reason.
|
||||
/// - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
|
||||
/// not local), `Vec<LocalType>` is bad, because `Vec<->` is between
|
||||
/// the local type and the type parameter.
|
||||
/// 3. Before this local type, no generic type parameter of the impl must
|
||||
/// be reachable through fundamental types.
|
||||
/// - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
|
||||
/// - while `impl<T> Trait<LocalType> for Box<T>` results in an error, as `T` is
|
||||
/// reachable through the fundamental type `Box`.
|
||||
/// 4. Every type in the local key parameter not known in C, going
|
||||
/// through the parameter's type tree, must appear only as a subtree of
|
||||
/// a type local to C, with only fundamental types between the type
|
||||
/// local to C and the local key parameter.
|
||||
/// - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
|
||||
/// is bad, because the only local type with `T` as a subtree is
|
||||
/// `LocalType<T>`, and `Vec<->` is between it and the type parameter.
|
||||
/// - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
|
||||
/// the second occurrence of `T` is not a subtree of *any* local type.
|
||||
/// - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
|
||||
/// `LocalType<Vec<T>>`, which is local and has no types between it and
|
||||
/// the type parameter.
|
||||
///
|
||||
/// The orphan rules actually serve several different purposes:
|
||||
///
|
||||
/// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
|
||||
/// every type local to one crate is unknown in the other) can't implement
|
||||
/// the same trait-ref. This follows because it can be seen that no such
|
||||
/// type can orphan-check in 2 such crates.
|
||||
///
|
||||
/// To check that a local impl follows the orphan rules, we check it in
|
||||
/// InCrate::Local mode, using type parameters for the "generic" types.
|
||||
///
|
||||
/// In InCrate::Local mode the orphan check succeeds if the current crate
|
||||
/// is definitely allowed to implement the given trait (no false positives).
|
||||
///
|
||||
/// 2. They ground negative reasoning for coherence. If a user wants to
|
||||
/// write both a conditional blanket impl and a specific impl, we need to
|
||||
/// make sure they do not overlap. For example, if we write
|
||||
/// ```ignore (illustrative)
|
||||
/// impl<T> IntoIterator for Vec<T>
|
||||
/// impl<T: Iterator> IntoIterator for T
|
||||
/// ```
|
||||
/// We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
|
||||
/// We can observe that this holds in the current crate, but we need to make
|
||||
/// sure this will also hold in all unknown crates (both "independent" crates,
|
||||
/// which we need for link-safety, and also child crates, because we don't want
|
||||
/// child crates to get error for impl conflicts in a *dependency*).
|
||||
///
|
||||
/// For that, we only allow negative reasoning if, for every assignment to the
|
||||
/// inference variables, every unknown crate would get an orphan error if they
|
||||
/// try to implement this trait-ref. To check for this, we use InCrate::Remote
|
||||
/// mode. That is sound because we already know all the impls from known crates.
|
||||
///
|
||||
/// In InCrate::Remote mode the orphan check succeeds if a foreign crate
|
||||
/// *could* implement the given trait (no false negatives).
|
||||
///
|
||||
/// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
|
||||
/// add "non-blanket" impls without breaking negative reasoning in dependent
|
||||
/// crates. This is the "rebalancing coherence" (RFC 1023) restriction.
|
||||
///
|
||||
/// For that, we only allow a crate to perform negative reasoning on
|
||||
/// non-local-non-`#[fundamental]` if there's a local key parameter as per (2).
|
||||
///
|
||||
/// Because we never perform negative reasoning generically (coherence does
|
||||
/// not involve type parameters), this can be interpreted as doing the full
|
||||
/// orphan check (using InCrate::Local mode), instantiating non-local known
|
||||
/// types for all inference variables.
|
||||
///
|
||||
/// This allows for crates to future-compatibly add impls as long as they
|
||||
/// can't apply to types with a key parameter in a child crate - applying
|
||||
/// the rules, this basically means that every type parameter in the impl
|
||||
/// must appear behind a non-fundamental type (because this is not a
|
||||
/// type-system requirement, crate owners might also go for "semantic
|
||||
/// future-compatibility" involving things such as sealed traits, but
|
||||
/// the above requirement is sufficient, and is necessary in "open world"
|
||||
/// cases).
|
||||
///
|
||||
/// Note that this function is never called for types that have both type
|
||||
/// parameters and inference variables.
|
||||
#[instrument(level = "trace", skip(infcx, lazily_normalize_ty), ret)]
|
||||
pub fn orphan_check_trait_ref<Infcx, I, E: Debug>(
|
||||
infcx: &Infcx,
|
||||
trait_ref: ty::TraitRef<I>,
|
||||
in_crate: InCrate,
|
||||
lazily_normalize_ty: impl FnMut(I::Ty) -> Result<I::Ty, E>,
|
||||
) -> Result<Result<(), OrphanCheckErr<I, I::Ty>>, E>
|
||||
where
|
||||
Infcx: InferCtxtLike<Interner = I>,
|
||||
I: Interner,
|
||||
E: Debug,
|
||||
{
|
||||
if trait_ref.has_param() {
|
||||
panic!("orphan check only expects inference variables: {trait_ref:?}");
|
||||
}
|
||||
|
||||
let mut checker = OrphanChecker::new(infcx, in_crate, lazily_normalize_ty);
|
||||
Ok(match trait_ref.visit_with(&mut checker) {
|
||||
ControlFlow::Continue(()) => Err(OrphanCheckErr::NonLocalInputType(checker.non_local_tys)),
|
||||
ControlFlow::Break(residual) => match residual {
|
||||
OrphanCheckEarlyExit::NormalizationFailure(err) => return Err(err),
|
||||
OrphanCheckEarlyExit::UncoveredTyParam(ty) => {
|
||||
// Does there exist some local type after the `ParamTy`.
|
||||
checker.search_first_local_ty = true;
|
||||
let local_ty = match trait_ref.visit_with(&mut checker) {
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(local_ty)) => Some(local_ty),
|
||||
_ => None,
|
||||
};
|
||||
Err(OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
|
||||
uncovered: ty,
|
||||
local_ty,
|
||||
}))
|
||||
}
|
||||
OrphanCheckEarlyExit::LocalTy(_) => Ok(()),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
struct OrphanChecker<'a, Infcx, I: Interner, F> {
|
||||
infcx: &'a Infcx,
|
||||
in_crate: InCrate,
|
||||
in_self_ty: bool,
|
||||
lazily_normalize_ty: F,
|
||||
/// Ignore orphan check failures and exclusively search for the first local type.
|
||||
search_first_local_ty: bool,
|
||||
non_local_tys: Vec<(I::Ty, IsFirstInputType)>,
|
||||
}
|
||||
|
||||
impl<'a, Infcx, I, F, E> OrphanChecker<'a, Infcx, I, F>
|
||||
where
|
||||
Infcx: InferCtxtLike<Interner = I>,
|
||||
I: Interner,
|
||||
F: FnOnce(I::Ty) -> Result<I::Ty, E>,
|
||||
{
|
||||
fn new(infcx: &'a Infcx, in_crate: InCrate, lazily_normalize_ty: F) -> Self {
|
||||
OrphanChecker {
|
||||
infcx,
|
||||
in_crate,
|
||||
in_self_ty: true,
|
||||
lazily_normalize_ty,
|
||||
search_first_local_ty: false,
|
||||
non_local_tys: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn found_non_local_ty(&mut self, t: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
|
||||
self.non_local_tys.push((t, self.in_self_ty.into()));
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn found_uncovered_ty_param(&mut self, ty: I::Ty) -> ControlFlow<OrphanCheckEarlyExit<I, E>> {
|
||||
if self.search_first_local_ty {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::UncoveredTyParam(ty))
|
||||
}
|
||||
|
||||
fn def_id_is_local(&mut self, def_id: I::DefId) -> bool {
|
||||
match self.in_crate {
|
||||
InCrate::Local { .. } => def_id.is_local(),
|
||||
InCrate::Remote => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum OrphanCheckEarlyExit<I: Interner, E> {
|
||||
NormalizationFailure(E),
|
||||
UncoveredTyParam(I::Ty),
|
||||
LocalTy(I::Ty),
|
||||
}
|
||||
|
||||
impl<'a, Infcx, I, F, E> TypeVisitor<I> for OrphanChecker<'a, Infcx, I, F>
|
||||
where
|
||||
Infcx: InferCtxtLike<Interner = I>,
|
||||
I: Interner,
|
||||
F: FnMut(I::Ty) -> Result<I::Ty, E>,
|
||||
{
|
||||
type Result = ControlFlow<OrphanCheckEarlyExit<I, E>>;
|
||||
|
||||
fn visit_region(&mut self, _r: I::Region) -> Self::Result {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn visit_ty(&mut self, ty: I::Ty) -> Self::Result {
|
||||
let ty = self.infcx.shallow_resolve(ty);
|
||||
let ty = match (self.lazily_normalize_ty)(ty) {
|
||||
Ok(norm_ty) if norm_ty.is_ty_var() => ty,
|
||||
Ok(norm_ty) => norm_ty,
|
||||
Err(err) => return ControlFlow::Break(OrphanCheckEarlyExit::NormalizationFailure(err)),
|
||||
};
|
||||
|
||||
let result = match ty.kind() {
|
||||
ty::Bool
|
||||
| ty::Char
|
||||
| ty::Int(..)
|
||||
| ty::Uint(..)
|
||||
| ty::Float(..)
|
||||
| ty::Str
|
||||
| ty::FnDef(..)
|
||||
| ty::Pat(..)
|
||||
| ty::FnPtr(_)
|
||||
| ty::Array(..)
|
||||
| ty::Slice(..)
|
||||
| ty::RawPtr(..)
|
||||
| ty::Never
|
||||
| ty::Tuple(..) => self.found_non_local_ty(ty),
|
||||
|
||||
ty::Param(..) => panic!("unexpected ty param"),
|
||||
|
||||
ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => {
|
||||
match self.in_crate {
|
||||
InCrate::Local { .. } => self.found_uncovered_ty_param(ty),
|
||||
// The inference variable might be unified with a local
|
||||
// type in that remote crate.
|
||||
InCrate::Remote => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
||||
}
|
||||
}
|
||||
|
||||
// A rigid alias may normalize to anything.
|
||||
// * If it references an infer var, placeholder or bound ty, it may
|
||||
// normalize to that, so we have to treat it as an uncovered ty param.
|
||||
// * Otherwise it may normalize to any non-type-generic type
|
||||
// be it local or non-local.
|
||||
ty::Alias(kind, _) => {
|
||||
if ty.has_type_flags(
|
||||
ty::TypeFlags::HAS_TY_PLACEHOLDER
|
||||
| ty::TypeFlags::HAS_TY_BOUND
|
||||
| ty::TypeFlags::HAS_TY_INFER,
|
||||
) {
|
||||
match self.in_crate {
|
||||
InCrate::Local { mode } => match kind {
|
||||
ty::Projection => {
|
||||
if let OrphanCheckMode::Compat = mode {
|
||||
ControlFlow::Continue(())
|
||||
} else {
|
||||
self.found_uncovered_ty_param(ty)
|
||||
}
|
||||
}
|
||||
_ => self.found_uncovered_ty_param(ty),
|
||||
},
|
||||
InCrate::Remote => {
|
||||
// The inference variable might be unified with a local
|
||||
// type in that remote crate.
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Regarding *opaque types* specifically, we choose to treat them as non-local,
|
||||
// even those that appear within the same crate. This seems somewhat surprising
|
||||
// at first, but makes sense when you consider that opaque types are supposed
|
||||
// to hide the underlying type *within the same crate*. When an opaque type is
|
||||
// used from outside the module where it is declared, it should be impossible to
|
||||
// observe anything about it other than the traits that it implements.
|
||||
//
|
||||
// The alternative would be to look at the underlying type to determine whether
|
||||
// or not the opaque type itself should be considered local.
|
||||
//
|
||||
// However, this could make it a breaking change to switch the underlying hidden
|
||||
// type from a local type to a remote type. This would violate the rule that
|
||||
// opaque types should be completely opaque apart from the traits that they
|
||||
// implement, so we don't use this behavior.
|
||||
// Addendum: Moreover, revealing the underlying type is likely to cause cycle
|
||||
// errors as we rely on coherence / the specialization graph during typeck.
|
||||
|
||||
self.found_non_local_ty(ty)
|
||||
}
|
||||
}
|
||||
|
||||
// For fundamental types, we just look inside of them.
|
||||
ty::Ref(_, ty, _) => ty.visit_with(self),
|
||||
ty::Adt(def, args) => {
|
||||
if self.def_id_is_local(def.def_id()) {
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
||||
} else if def.is_fundamental() {
|
||||
args.visit_with(self)
|
||||
} else {
|
||||
self.found_non_local_ty(ty)
|
||||
}
|
||||
}
|
||||
ty::Foreign(def_id) => {
|
||||
if self.def_id_is_local(def_id) {
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
||||
} else {
|
||||
self.found_non_local_ty(ty)
|
||||
}
|
||||
}
|
||||
ty::Dynamic(tt, ..) => {
|
||||
let principal = tt.principal().map(|p| p.def_id());
|
||||
if principal.is_some_and(|p| self.def_id_is_local(p)) {
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
||||
} else {
|
||||
self.found_non_local_ty(ty)
|
||||
}
|
||||
}
|
||||
ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
||||
ty::Closure(did, ..) | ty::CoroutineClosure(did, ..) | ty::Coroutine(did, ..) => {
|
||||
if self.def_id_is_local(did) {
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
||||
} else {
|
||||
self.found_non_local_ty(ty)
|
||||
}
|
||||
}
|
||||
// This should only be created when checking whether we have to check whether some
|
||||
// auto trait impl applies. There will never be multiple impls, so we can just
|
||||
// act as if it were a local type here.
|
||||
ty::CoroutineWitness(..) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
||||
};
|
||||
// A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
|
||||
// the first type we visit is always the self type.
|
||||
self.in_self_ty = false;
|
||||
result
|
||||
}
|
||||
|
||||
/// All possible values for a constant parameter already exist
|
||||
/// in the crate defining the trait, so they are always non-local[^1].
|
||||
///
|
||||
/// Because there's no way to have an impl where the first local
|
||||
/// generic argument is a constant, we also don't have to fail
|
||||
/// the orphan check when encountering a parameter or a generic constant.
|
||||
///
|
||||
/// This means that we can completely ignore constants during the orphan check.
|
||||
///
|
||||
/// See `tests/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
|
||||
///
|
||||
/// [^1]: This might not hold for function pointers or trait objects in the future.
|
||||
/// As these should be quite rare as const arguments and especially rare as impl
|
||||
/// parameters, allowing uncovered const parameters in impls seems more useful
|
||||
/// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
|
||||
fn visit_const(&mut self, _c: I::Const) -> Self::Result {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
}
|
||||
|
|
@ -1,4 +1,3 @@
|
|||
use std::fmt::Debug;
|
||||
use std::ops::Deref;
|
||||
|
||||
use rustc_type_ir::fold::TypeFoldable;
|
||||
|
|
@ -32,12 +31,6 @@ pub trait SolverDelegate:
|
|||
// FIXME: Uplift the leak check into this crate.
|
||||
fn leak_check(&self, max_input_universe: ty::UniverseIndex) -> Result<(), NoSolution>;
|
||||
|
||||
// FIXME: This is only here because elaboration lives in `rustc_infer`!
|
||||
fn elaborate_supertraits(
|
||||
cx: Self::Interner,
|
||||
trait_ref: ty::Binder<Self::Interner, ty::TraitRef<Self::Interner>>,
|
||||
) -> impl Iterator<Item = ty::Binder<Self::Interner, ty::TraitRef<Self::Interner>>>;
|
||||
|
||||
fn try_const_eval_resolve(
|
||||
&self,
|
||||
param_env: <Self::Interner as Interner>::ParamEnv,
|
||||
|
|
@ -99,14 +92,6 @@ pub trait SolverDelegate:
|
|||
|
||||
fn reset_opaque_types(&self);
|
||||
|
||||
fn trait_ref_is_knowable<E: Debug>(
|
||||
&self,
|
||||
trait_ref: ty::TraitRef<Self::Interner>,
|
||||
lazily_normalize_ty: impl FnMut(
|
||||
<Self::Interner as Interner>::Ty,
|
||||
) -> Result<<Self::Interner as Interner>::Ty, E>,
|
||||
) -> Result<bool, E>;
|
||||
|
||||
fn fetch_eligible_assoc_item(
|
||||
&self,
|
||||
param_env: <Self::Interner as Interner>::ParamEnv,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
//! So if you got to this crate from the old solver, it's totally normal.
|
||||
|
||||
pub mod canonicalizer;
|
||||
pub mod coherence;
|
||||
pub mod delegate;
|
||||
pub mod relate;
|
||||
pub mod resolve;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
pub(super) mod structural_traits;
|
||||
|
||||
use rustc_type_ir::elaborate;
|
||||
use rustc_type_ir::fold::TypeFoldable;
|
||||
use rustc_type_ir::inherent::*;
|
||||
use rustc_type_ir::lang_items::TraitSolverLangItem;
|
||||
|
|
@ -667,7 +668,7 @@ where
|
|||
// a projection goal.
|
||||
if let Some(principal) = bounds.principal() {
|
||||
let principal_trait_ref = principal.with_self_ty(cx, self_ty);
|
||||
for (idx, assumption) in D::elaborate_supertraits(cx, principal_trait_ref).enumerate() {
|
||||
for (idx, assumption) in elaborate::supertraits(cx, principal_trait_ref).enumerate() {
|
||||
candidates.extend(G::probe_and_consider_object_bound_candidate(
|
||||
self,
|
||||
CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)),
|
||||
|
|
|
|||
|
|
@ -669,7 +669,9 @@ where
|
|||
let cx = ecx.cx();
|
||||
let mut requirements = vec![];
|
||||
requirements.extend(
|
||||
cx.explicit_super_predicates_of(trait_ref.def_id).iter_instantiated(cx, trait_ref.args),
|
||||
cx.explicit_super_predicates_of(trait_ref.def_id)
|
||||
.iter_instantiated(cx, trait_ref.args)
|
||||
.map(|(pred, _)| pred),
|
||||
);
|
||||
|
||||
// FIXME(associated_const_equality): Also add associated consts to
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ use rustc_type_ir::{self as ty, CanonicalVarValues, InferCtxtLike, Interner};
|
|||
use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic};
|
||||
use tracing::{instrument, trace};
|
||||
|
||||
use crate::coherence;
|
||||
use crate::delegate::SolverDelegate;
|
||||
use crate::solve::inspect::{self, ProofTreeBuilder};
|
||||
use crate::solve::search_graph::SearchGraph;
|
||||
|
|
@ -906,7 +907,8 @@ where
|
|||
) -> Result<bool, NoSolution> {
|
||||
let delegate = self.delegate;
|
||||
let lazily_normalize_ty = |ty| self.structurally_normalize_ty(param_env, ty);
|
||||
delegate.trait_ref_is_knowable(trait_ref, lazily_normalize_ty)
|
||||
coherence::trait_ref_is_knowable(&**delegate, trait_ref, lazily_normalize_ty)
|
||||
.map(|is_knowable| is_knowable.is_ok())
|
||||
}
|
||||
|
||||
pub(super) fn fetch_eligible_assoc_item(
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ use rustc_type_ir::fast_reject::{DeepRejectCtxt, TreatParams};
|
|||
use rustc_type_ir::inherent::*;
|
||||
use rustc_type_ir::lang_items::TraitSolverLangItem;
|
||||
use rustc_type_ir::visit::TypeVisitableExt as _;
|
||||
use rustc_type_ir::{self as ty, Interner, TraitPredicate, Upcast as _};
|
||||
use rustc_type_ir::{self as ty, elaborate, Interner, TraitPredicate, Upcast as _};
|
||||
use tracing::{instrument, trace};
|
||||
|
||||
use crate::delegate::SolverDelegate;
|
||||
|
|
@ -787,7 +787,7 @@ where
|
|||
));
|
||||
} else if let Some(a_principal) = a_data.principal() {
|
||||
for new_a_principal in
|
||||
D::elaborate_supertraits(self.cx(), a_principal.with_self_ty(cx, a_ty)).skip(1)
|
||||
elaborate::supertraits(self.cx(), a_principal.with_self_ty(cx, a_ty)).skip(1)
|
||||
{
|
||||
responses.extend(self.consider_builtin_upcast_to_principal(
|
||||
goal,
|
||||
|
|
@ -862,8 +862,7 @@ where
|
|||
.auto_traits()
|
||||
.into_iter()
|
||||
.chain(a_data.principal_def_id().into_iter().flat_map(|principal_def_id| {
|
||||
self.cx()
|
||||
.supertrait_def_ids(principal_def_id)
|
||||
elaborate::supertrait_def_ids(self.cx(), principal_def_id)
|
||||
.into_iter()
|
||||
.filter(|def_id| self.cx().trait_is_auto(*def_id))
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -282,7 +282,7 @@ impl<'a> Parser<'a> {
|
|||
pub fn parse_inner_attributes(&mut self) -> PResult<'a, ast::AttrVec> {
|
||||
let mut attrs = ast::AttrVec::new();
|
||||
loop {
|
||||
let start_pos: u32 = self.num_bump_calls.try_into().unwrap();
|
||||
let start_pos = self.num_bump_calls;
|
||||
// Only try to parse if it is an inner attribute (has `!`).
|
||||
let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
|
||||
Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
|
||||
|
|
@ -303,7 +303,7 @@ impl<'a> Parser<'a> {
|
|||
None
|
||||
};
|
||||
if let Some(attr) = attr {
|
||||
let end_pos: u32 = self.num_bump_calls.try_into().unwrap();
|
||||
let end_pos = self.num_bump_calls;
|
||||
// If we are currently capturing tokens, mark the location of this inner attribute.
|
||||
// If capturing ends up creating a `LazyAttrTokenStream`, we will include
|
||||
// this replace range with it, removing the inner attribute from the final
|
||||
|
|
@ -313,7 +313,7 @@ impl<'a> Parser<'a> {
|
|||
// corresponding macro).
|
||||
let range = start_pos..end_pos;
|
||||
if let Capturing::Yes = self.capture_state.capturing {
|
||||
self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
|
||||
self.capture_state.inner_attr_ranges.insert(attr.id, (range, None));
|
||||
}
|
||||
attrs.push(attr);
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use super::{Capturing, FlatToken, ForceCollect, Parser, ReplaceRange, TokenCursor, TrailingToken};
|
||||
use rustc_ast::token::{self, Delimiter, Token, TokenKind};
|
||||
use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, AttributesData, DelimSpacing};
|
||||
use rustc_ast::tokenstream::{AttrTokenStream, AttrTokenTree, AttrsTarget, DelimSpacing};
|
||||
use rustc_ast::tokenstream::{DelimSpan, LazyAttrTokenStream, Spacing, ToAttrTokenStream};
|
||||
use rustc_ast::{self as ast};
|
||||
use rustc_ast::{AttrVec, Attribute, HasAttrs, HasTokens};
|
||||
|
|
@ -8,7 +8,6 @@ use rustc_errors::PResult;
|
|||
use rustc_session::parse::ParseSess;
|
||||
use rustc_span::{sym, Span, DUMMY_SP};
|
||||
|
||||
use std::ops::Range;
|
||||
use std::{iter, mem};
|
||||
|
||||
/// A wrapper type to ensure that the parser handles outer attributes correctly.
|
||||
|
|
@ -88,7 +87,6 @@ fn has_cfg_or_cfg_attr(attrs: &[Attribute]) -> bool {
|
|||
//
|
||||
// This also makes `Parser` very cheap to clone, since
|
||||
// there is no intermediate collection buffer to clone.
|
||||
#[derive(Clone)]
|
||||
struct LazyAttrTokenStreamImpl {
|
||||
start_token: (Token, Spacing),
|
||||
cursor_snapshot: TokenCursor,
|
||||
|
|
@ -146,24 +144,23 @@ impl ToAttrTokenStream for LazyAttrTokenStreamImpl {
|
|||
// start position, we ensure that any replace range which encloses
|
||||
// another replace range will capture the *replaced* tokens for the inner
|
||||
// range, not the original tokens.
|
||||
for (range, new_tokens) in replace_ranges.into_iter().rev() {
|
||||
for (range, target) in replace_ranges.into_iter().rev() {
|
||||
assert!(!range.is_empty(), "Cannot replace an empty range: {range:?}");
|
||||
// Replace ranges are only allowed to decrease the number of tokens.
|
||||
assert!(
|
||||
range.len() >= new_tokens.len(),
|
||||
"Range {range:?} has greater len than {new_tokens:?}"
|
||||
);
|
||||
|
||||
// Replace any removed tokens with `FlatToken::Empty`.
|
||||
// This keeps the total length of `tokens` constant throughout the
|
||||
// replacement process, allowing us to use all of the `ReplaceRanges` entries
|
||||
// without adjusting indices.
|
||||
let filler = iter::repeat((FlatToken::Empty, Spacing::Alone))
|
||||
.take(range.len() - new_tokens.len());
|
||||
|
||||
// Replace the tokens in range with zero or one `FlatToken::AttrsTarget`s, plus
|
||||
// enough `FlatToken::Empty`s to fill up the rest of the range. This keeps the
|
||||
// total length of `tokens` constant throughout the replacement process, allowing
|
||||
// us to use all of the `ReplaceRanges` entries without adjusting indices.
|
||||
let target_len = target.is_some() as usize;
|
||||
tokens.splice(
|
||||
(range.start as usize)..(range.end as usize),
|
||||
new_tokens.into_iter().chain(filler),
|
||||
target
|
||||
.into_iter()
|
||||
.map(|target| (FlatToken::AttrsTarget(target), Spacing::Alone))
|
||||
.chain(
|
||||
iter::repeat((FlatToken::Empty, Spacing::Alone))
|
||||
.take(range.len() - target_len),
|
||||
),
|
||||
);
|
||||
}
|
||||
make_attr_token_stream(tokens.into_iter(), self.break_last_token)
|
||||
|
|
@ -316,7 +313,7 @@ impl<'a> Parser<'a> {
|
|||
.iter()
|
||||
.cloned()
|
||||
.chain(inner_attr_replace_ranges.iter().cloned())
|
||||
.map(|(range, tokens)| ((range.start - start_pos)..(range.end - start_pos), tokens))
|
||||
.map(|(range, data)| ((range.start - start_pos)..(range.end - start_pos), data))
|
||||
.collect()
|
||||
};
|
||||
|
||||
|
|
@ -346,18 +343,14 @@ impl<'a> Parser<'a> {
|
|||
&& matches!(self.capture_state.capturing, Capturing::Yes)
|
||||
&& has_cfg_or_cfg_attr(final_attrs)
|
||||
{
|
||||
let attr_data = AttributesData { attrs: final_attrs.iter().cloned().collect(), tokens };
|
||||
|
||||
// Replace the entire AST node that we just parsed, including attributes,
|
||||
// with a `FlatToken::AttrTarget`. If this AST node is inside an item
|
||||
// that has `#[derive]`, then this will allow us to cfg-expand this
|
||||
// AST node.
|
||||
let start_pos = if has_outer_attrs { attrs.start_pos } else { start_pos };
|
||||
let new_tokens = vec![(FlatToken::AttrTarget(attr_data), Spacing::Alone)];
|
||||
|
||||
assert!(!self.break_last_token, "Should not have unglued last token with cfg attr");
|
||||
let range: Range<u32> = (start_pos.try_into().unwrap())..(end_pos.try_into().unwrap());
|
||||
self.capture_state.replace_ranges.push((range, new_tokens));
|
||||
|
||||
// Replace the entire AST node that we just parsed, including attributes, with
|
||||
// `target`. If this AST node is inside an item that has `#[derive]`, then this will
|
||||
// allow us to cfg-expand this AST node.
|
||||
let start_pos = if has_outer_attrs { attrs.start_pos } else { start_pos };
|
||||
let target = AttrsTarget { attrs: final_attrs.iter().cloned().collect(), tokens };
|
||||
self.capture_state.replace_ranges.push((start_pos..end_pos, Some(target)));
|
||||
self.capture_state.replace_ranges.extend(inner_attr_replace_ranges);
|
||||
}
|
||||
|
||||
|
|
@ -419,11 +412,11 @@ fn make_attr_token_stream(
|
|||
.expect("Bottom token frame is missing!")
|
||||
.inner
|
||||
.push(AttrTokenTree::Token(token, spacing)),
|
||||
FlatToken::AttrTarget(data) => stack
|
||||
FlatToken::AttrsTarget(target) => stack
|
||||
.last_mut()
|
||||
.expect("Bottom token frame is missing!")
|
||||
.inner
|
||||
.push(AttrTokenTree::Attributes(data)),
|
||||
.push(AttrTokenTree::AttrsTarget(target)),
|
||||
FlatToken::Empty => {}
|
||||
}
|
||||
token_and_spacing = iter.next();
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ use path::PathStyle;
|
|||
|
||||
use rustc_ast::ptr::P;
|
||||
use rustc_ast::token::{self, Delimiter, IdentIsRaw, Nonterminal, Token, TokenKind};
|
||||
use rustc_ast::tokenstream::{AttributesData, DelimSpacing, DelimSpan, Spacing};
|
||||
use rustc_ast::tokenstream::{AttrsTarget, DelimSpacing, DelimSpan, Spacing};
|
||||
use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor};
|
||||
use rustc_ast::util::case::Case;
|
||||
use rustc_ast::{
|
||||
|
|
@ -203,13 +203,13 @@ struct ClosureSpans {
|
|||
}
|
||||
|
||||
/// Indicates a range of tokens that should be replaced by
|
||||
/// the tokens in the provided vector. This is used in two
|
||||
/// the tokens in the provided `AttrsTarget`. This is used in two
|
||||
/// places during token collection:
|
||||
///
|
||||
/// 1. During the parsing of an AST node that may have a `#[derive]`
|
||||
/// attribute, we parse a nested AST node that has `#[cfg]` or `#[cfg_attr]`
|
||||
/// In this case, we use a `ReplaceRange` to replace the entire inner AST node
|
||||
/// with `FlatToken::AttrTarget`, allowing us to perform eager cfg-expansion
|
||||
/// with `FlatToken::AttrsTarget`, allowing us to perform eager cfg-expansion
|
||||
/// on an `AttrTokenStream`.
|
||||
///
|
||||
/// 2. When we parse an inner attribute while collecting tokens. We
|
||||
|
|
@ -219,7 +219,7 @@ struct ClosureSpans {
|
|||
/// the first macro inner attribute to invoke a proc-macro).
|
||||
/// When create a `TokenStream`, the inner attributes get inserted
|
||||
/// into the proper place in the token stream.
|
||||
type ReplaceRange = (Range<u32>, Vec<(FlatToken, Spacing)>);
|
||||
type ReplaceRange = (Range<u32>, Option<AttrsTarget>);
|
||||
|
||||
/// Controls how we capture tokens. Capturing can be expensive,
|
||||
/// so we try to avoid performing capturing in cases where
|
||||
|
|
@ -1608,11 +1608,10 @@ enum FlatToken {
|
|||
/// A token - this holds both delimiter (e.g. '{' and '}')
|
||||
/// and non-delimiter tokens
|
||||
Token(Token),
|
||||
/// Holds the `AttributesData` for an AST node. The
|
||||
/// `AttributesData` is inserted directly into the
|
||||
/// constructed `AttrTokenStream` as
|
||||
/// an `AttrTokenTree::Attributes`.
|
||||
AttrTarget(AttributesData),
|
||||
/// Holds the `AttrsTarget` for an AST node. The `AttrsTarget` is inserted
|
||||
/// directly into the constructed `AttrTokenStream` as an
|
||||
/// `AttrTokenTree::AttrsTarget`.
|
||||
AttrsTarget(AttrsTarget),
|
||||
/// A special 'empty' token that is ignored during the conversion
|
||||
/// to an `AttrTokenStream`. This is used to simplify the
|
||||
/// handling of replace ranges.
|
||||
|
|
|
|||
|
|
@ -321,8 +321,14 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
|
|||
// The fields are not expanded yet.
|
||||
return;
|
||||
}
|
||||
let def_ids = fields.iter().map(|field| self.r.local_def_id(field.id).to_def_id());
|
||||
self.r.field_def_ids.insert(def_id, self.r.tcx.arena.alloc_from_iter(def_ids));
|
||||
let fields = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| {
|
||||
field.ident.unwrap_or_else(|| Ident::from_str_and_span(&format!("{i}"), field.span))
|
||||
})
|
||||
.collect();
|
||||
self.r.field_names.insert(def_id, fields);
|
||||
}
|
||||
|
||||
fn insert_field_visibilities_local(&mut self, def_id: DefId, fields: &[ast::FieldDef]) {
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ use rustc_hir::def_id::LocalDefId;
|
|||
use rustc_span::hygiene::LocalExpnId;
|
||||
use rustc_span::symbol::{kw, sym, Symbol};
|
||||
use rustc_span::Span;
|
||||
use std::mem;
|
||||
use tracing::debug;
|
||||
|
||||
pub(crate) fn collect_definitions(
|
||||
|
|
@ -15,8 +16,9 @@ pub(crate) fn collect_definitions(
|
|||
fragment: &AstFragment,
|
||||
expansion: LocalExpnId,
|
||||
) {
|
||||
let (parent_def, impl_trait_context) = resolver.invocation_parents[&expansion];
|
||||
fragment.visit_with(&mut DefCollector { resolver, parent_def, expansion, impl_trait_context });
|
||||
let (parent_def, impl_trait_context, in_attr) = resolver.invocation_parents[&expansion];
|
||||
let mut visitor = DefCollector { resolver, parent_def, expansion, impl_trait_context, in_attr };
|
||||
fragment.visit_with(&mut visitor);
|
||||
}
|
||||
|
||||
/// Creates `DefId`s for nodes in the AST.
|
||||
|
|
@ -24,6 +26,7 @@ struct DefCollector<'a, 'b, 'tcx> {
|
|||
resolver: &'a mut Resolver<'b, 'tcx>,
|
||||
parent_def: LocalDefId,
|
||||
impl_trait_context: ImplTraitContext,
|
||||
in_attr: bool,
|
||||
expansion: LocalExpnId,
|
||||
}
|
||||
|
||||
|
|
@ -53,7 +56,7 @@ impl<'a, 'b, 'tcx> DefCollector<'a, 'b, 'tcx> {
|
|||
}
|
||||
|
||||
fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_def: LocalDefId, f: F) {
|
||||
let orig_parent_def = std::mem::replace(&mut self.parent_def, parent_def);
|
||||
let orig_parent_def = mem::replace(&mut self.parent_def, parent_def);
|
||||
f(self);
|
||||
self.parent_def = orig_parent_def;
|
||||
}
|
||||
|
|
@ -63,7 +66,7 @@ impl<'a, 'b, 'tcx> DefCollector<'a, 'b, 'tcx> {
|
|||
impl_trait_context: ImplTraitContext,
|
||||
f: F,
|
||||
) {
|
||||
let orig_itc = std::mem::replace(&mut self.impl_trait_context, impl_trait_context);
|
||||
let orig_itc = mem::replace(&mut self.impl_trait_context, impl_trait_context);
|
||||
f(self);
|
||||
self.impl_trait_context = orig_itc;
|
||||
}
|
||||
|
|
@ -105,8 +108,10 @@ impl<'a, 'b, 'tcx> DefCollector<'a, 'b, 'tcx> {
|
|||
|
||||
fn visit_macro_invoc(&mut self, id: NodeId) {
|
||||
let id = id.placeholder_to_expn_id();
|
||||
let old_parent =
|
||||
self.resolver.invocation_parents.insert(id, (self.parent_def, self.impl_trait_context));
|
||||
let old_parent = self
|
||||
.resolver
|
||||
.invocation_parents
|
||||
.insert(id, (self.parent_def, self.impl_trait_context, self.in_attr));
|
||||
assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation");
|
||||
}
|
||||
}
|
||||
|
|
@ -413,4 +418,10 @@ impl<'a, 'b, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'b, 'tcx> {
|
|||
visit::walk_crate(self, krate)
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_attribute(&mut self, attr: &'a Attribute) -> Self::Result {
|
||||
let orig_in_attr = mem::replace(&mut self.in_attr, true);
|
||||
visit::walk_attribute(self, attr);
|
||||
self.in_attr = orig_in_attr;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1726,11 +1726,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
|
|||
)) = binding.kind
|
||||
{
|
||||
let def_id = self.tcx.parent(ctor_def_id);
|
||||
return self
|
||||
.field_def_ids(def_id)?
|
||||
.iter()
|
||||
.map(|&field_id| self.def_span(field_id))
|
||||
.reduce(Span::to); // None for `struct Foo()`
|
||||
return self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to); // None for `struct Foo()`
|
||||
}
|
||||
None
|
||||
}
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue