mirror of https://github.com/rust-lang/rust.git
Auto merge of #127476 - jieyouxu:rollup-16wyb0b, r=jieyouxu
Rollup of 10 pull requests Successful merges: - #126841 ([`macro_metavar_expr_concat`] Add support for literals) - #126881 (Make `NEVER_TYPE_FALLBACK_FLOWING_INTO_UNSAFE` a deny-by-default lint in edition 2024) - #126921 (Give VaList its own home) - #127367 (Run alloc sync tests) - #127431 (Use field ident spans directly instead of the full field span in diagnostics on local fields) - #127437 (Uplift trait ref is knowable into `rustc_next_trait_solver`) - #127439 (Uplift elaboration into `rustc_type_ir`) - #127451 (Improve `run-make/output-type-permutations` code and improve `filename_not_in_denylist` API) - #127452 (Fix intrinsic const parameter counting with `effects`) - #127459 (rustdoc-json: add type/trait alias tests) r? `@ghost` `@rustbot` modify labels: rollup
This commit is contained in:
commit
7fdefb804e
|
@ -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,
|
||||
));
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -478,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,
|
||||
|
@ -1205,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);
|
||||
}
|
||||
|
|
|
@ -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,
|
||||
|
|
|
@ -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]
|
||||
|
|
|
@ -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()
|
||||
})
|
||||
|
|
|
@ -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>>,
|
||||
|
|
|
@ -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()
|
||||
|
|
|
@ -4189,6 +4189,7 @@ declare_lint! {
|
|||
reason: FutureIncompatibilityReason::FutureReleaseSemanticsChange,
|
||||
reference: "issue #123748 <https://github.com/rust-lang/rust/issues/123748>",
|
||||
};
|
||||
@edition Edition2024 => Deny;
|
||||
report_in_external_macro
|
||||
}
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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>>;
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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))
|
||||
}))
|
||||
|
|
|
@ -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]) {
|
||||
|
|
|
@ -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
|
||||
}
|
||||
|
|
|
@ -1532,17 +1532,17 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
if !this.has_private_fields(def_id) {
|
||||
// If the fields of the type are private, we shouldn't be suggesting using
|
||||
// the struct literal syntax at all, as that will cause a subsequent error.
|
||||
let field_ids = this.r.field_def_ids(def_id);
|
||||
let (fields, applicability) = match field_ids {
|
||||
Some(field_ids) => {
|
||||
let fields = field_ids.iter().map(|&id| this.r.tcx.item_name(id));
|
||||
|
||||
let fields = this.r.field_idents(def_id);
|
||||
let has_fields = fields.as_ref().is_some_and(|f| !f.is_empty());
|
||||
let (fields, applicability) = match fields {
|
||||
Some(fields) => {
|
||||
let fields = if let Some(old_fields) = old_fields {
|
||||
fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(idx, new)| (new, old_fields.get(idx)))
|
||||
.map(|(new, old)| {
|
||||
let new = new.to_ident_string();
|
||||
let new = new.name.to_ident_string();
|
||||
if let Some(Some(old)) = old
|
||||
&& new != *old
|
||||
{
|
||||
|
@ -1553,17 +1553,17 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
})
|
||||
.collect::<Vec<String>>()
|
||||
} else {
|
||||
fields.map(|f| format!("{f}{tail}")).collect::<Vec<String>>()
|
||||
fields
|
||||
.iter()
|
||||
.map(|f| format!("{f}{tail}"))
|
||||
.collect::<Vec<String>>()
|
||||
};
|
||||
|
||||
(fields.join(", "), applicability)
|
||||
}
|
||||
None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
|
||||
};
|
||||
let pad = match field_ids {
|
||||
Some([]) => "",
|
||||
_ => " ",
|
||||
};
|
||||
let pad = if has_fields { " " } else { "" };
|
||||
err.span_suggestion(
|
||||
span,
|
||||
format!("use struct {descr} syntax instead"),
|
||||
|
@ -1723,12 +1723,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
&args[..],
|
||||
);
|
||||
// Use spans of the tuple struct definition.
|
||||
self.r.field_def_ids(def_id).map(|field_ids| {
|
||||
field_ids
|
||||
.iter()
|
||||
.map(|&field_id| self.r.def_span(field_id))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
self.r
|
||||
.field_idents(def_id)
|
||||
.map(|fields| fields.iter().map(|f| f.span).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
@ -1791,7 +1788,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
(Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_def_id), _) if ns == ValueNS => {
|
||||
let def_id = self.r.tcx.parent(ctor_def_id);
|
||||
err.span_label(self.r.def_span(def_id), format!("`{path_str}` defined here"));
|
||||
let fields = self.r.field_def_ids(def_id).map_or_else(
|
||||
let fields = self.r.field_idents(def_id).map_or_else(
|
||||
|| "/* fields */".to_string(),
|
||||
|field_ids| vec!["_"; field_ids.len()].join(", "),
|
||||
);
|
||||
|
@ -2017,12 +2014,9 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
if let Some(Res::Def(DefKind::Struct | DefKind::Union, did)) =
|
||||
resolution.full_res()
|
||||
{
|
||||
if let Some(field_ids) = self.r.field_def_ids(did) {
|
||||
if let Some(field_id) = field_ids
|
||||
.iter()
|
||||
.find(|&&field_id| ident.name == self.r.tcx.item_name(field_id))
|
||||
{
|
||||
return Some(AssocSuggestion::Field(self.r.def_span(*field_id)));
|
||||
if let Some(fields) = self.r.field_idents(did) {
|
||||
if let Some(field) = fields.iter().find(|id| ident.name == id.name) {
|
||||
return Some(AssocSuggestion::Field(field.span));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2418,7 +2412,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
|
|||
match kind {
|
||||
CtorKind::Const => false,
|
||||
CtorKind::Fn => {
|
||||
!self.r.field_def_ids(def_id).is_some_and(|field_ids| field_ids.is_empty())
|
||||
!self.r.field_idents(def_id).is_some_and(|field_ids| field_ids.is_empty())
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
|
@ -991,7 +991,7 @@ pub struct Resolver<'a, 'tcx> {
|
|||
extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
|
||||
|
||||
/// N.B., this is used only for better diagnostics, not name resolution itself.
|
||||
field_def_ids: LocalDefIdMap<&'tcx [DefId]>,
|
||||
field_names: LocalDefIdMap<Vec<Ident>>,
|
||||
|
||||
/// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
|
||||
/// Used for hints during error reporting.
|
||||
|
@ -1407,7 +1407,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
|
|||
prelude: None,
|
||||
extern_prelude,
|
||||
|
||||
field_def_ids: Default::default(),
|
||||
field_names: Default::default(),
|
||||
field_visibility_spans: FxHashMap::default(),
|
||||
|
||||
determined_imports: Vec::new(),
|
||||
|
@ -2128,10 +2128,18 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
|
|||
}
|
||||
}
|
||||
|
||||
fn field_def_ids(&self, def_id: DefId) -> Option<&'tcx [DefId]> {
|
||||
fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
|
||||
match def_id.as_local() {
|
||||
Some(def_id) => self.field_def_ids.get(&def_id).copied(),
|
||||
None => Some(self.tcx.associated_item_def_ids(def_id)),
|
||||
Some(def_id) => self.field_names.get(&def_id).cloned(),
|
||||
None => Some(
|
||||
self.tcx
|
||||
.associated_item_def_ids(def_id)
|
||||
.iter()
|
||||
.map(|&def_id| {
|
||||
Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -26,6 +26,7 @@
|
|||
#![feature(never_type)]
|
||||
#![feature(rustdoc_internals)]
|
||||
#![feature(type_alias_impl_trait)]
|
||||
#![feature(unwrap_infallible)]
|
||||
#![recursion_limit = "512"] // For rustdoc
|
||||
// tidy-alphabetical-end
|
||||
|
||||
|
|
|
@ -8,14 +8,12 @@ use rustc_infer::infer::canonical::{
|
|||
};
|
||||
use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, TyCtxtInferExt};
|
||||
use rustc_infer::traits::solve::Goal;
|
||||
use rustc_infer::traits::util::supertraits;
|
||||
use rustc_infer::traits::{ObligationCause, Reveal};
|
||||
use rustc_middle::ty::fold::TypeFoldable;
|
||||
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt as _};
|
||||
use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP};
|
||||
use rustc_type_ir::solve::{Certainty, NoSolution, SolverMode};
|
||||
|
||||
use crate::traits::coherence::trait_ref_is_knowable;
|
||||
use crate::traits::specialization_graph;
|
||||
|
||||
#[repr(transparent)]
|
||||
|
@ -82,13 +80,6 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<
|
|||
self.0.leak_check(max_input_universe, None).map_err(|_| NoSolution)
|
||||
}
|
||||
|
||||
fn elaborate_supertraits(
|
||||
interner: TyCtxt<'tcx>,
|
||||
trait_ref: ty::Binder<'tcx, ty::TraitRef<'tcx>>,
|
||||
) -> impl Iterator<Item = ty::Binder<'tcx, ty::TraitRef<'tcx>>> {
|
||||
supertraits(interner, trait_ref)
|
||||
}
|
||||
|
||||
fn try_const_eval_resolve(
|
||||
&self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
|
@ -200,15 +191,6 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate<
|
|||
let _ = self.take_opaque_types();
|
||||
}
|
||||
|
||||
fn trait_ref_is_knowable<E: std::fmt::Debug>(
|
||||
&self,
|
||||
trait_ref: ty::TraitRef<'tcx>,
|
||||
lazily_normalize_ty: impl FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
||||
) -> Result<bool, E> {
|
||||
trait_ref_is_knowable(&self.0, trait_ref, lazily_normalize_ty)
|
||||
.map(|is_knowable| is_knowable.is_ok())
|
||||
}
|
||||
|
||||
fn fetch_eligible_assoc_item(
|
||||
&self,
|
||||
param_env: ty::ParamEnv<'tcx>,
|
||||
|
|
|
@ -25,42 +25,14 @@ use rustc_middle::traits::specialization_graph::OverlapMode;
|
|||
use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
|
||||
use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
|
||||
use rustc_middle::ty::{self, Ty, TyCtxt};
|
||||
pub use rustc_next_trait_solver::coherence::*;
|
||||
use rustc_span::symbol::sym;
|
||||
use rustc_span::{Span, DUMMY_SP};
|
||||
use std::fmt::Debug;
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
use super::error_reporting::suggest_new_overflow_limit;
|
||||
use super::ObligationCtxt;
|
||||
|
||||
/// 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,
|
||||
}
|
||||
|
||||
pub struct OverlapResult<'tcx> {
|
||||
pub impl_header: ty::ImplHeader<'tcx>,
|
||||
pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
|
||||
|
@ -612,426 +584,6 @@ fn try_prove_negated_where_clause<'tcx>(
|
|||
true
|
||||
}
|
||||
|
||||
/// 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<'tcx, E: Debug>(
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
trait_ref: ty::TraitRef<'tcx>,
|
||||
mut lazily_normalize_ty: impl FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
||||
) -> Result<Result<(), Conflict>, E> {
|
||||
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.tcx, 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<'tcx>(
|
||||
tcx: TyCtxt<'tcx>,
|
||||
trait_ref: ty::TraitRef<'tcx>,
|
||||
) -> bool {
|
||||
trait_ref.def_id.is_local() || tcx.has_attr(trait_ref.def_id, sym::fundamental)
|
||||
}
|
||||
|
||||
#[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(Debug)]
|
||||
pub enum OrphanCheckErr<'tcx, T> {
|
||||
NonLocalInputType(Vec<(Ty<'tcx>, IsFirstInputType)>),
|
||||
UncoveredTyParams(UncoveredTyParams<'tcx, T>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UncoveredTyParams<'tcx, T> {
|
||||
pub uncovered: T,
|
||||
pub local_ty: Option<Ty<'tcx>>,
|
||||
}
|
||||
|
||||
/// 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<'tcx, E: Debug>(
|
||||
infcx: &InferCtxt<'tcx>,
|
||||
trait_ref: ty::TraitRef<'tcx>,
|
||||
in_crate: InCrate,
|
||||
lazily_normalize_ty: impl FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
||||
) -> Result<Result<(), OrphanCheckErr<'tcx, Ty<'tcx>>>, E> {
|
||||
if trait_ref.has_param() {
|
||||
bug!("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).break_value() {
|
||||
Some(OrphanCheckEarlyExit::LocalTy(local_ty)) => Some(local_ty),
|
||||
_ => None,
|
||||
};
|
||||
Err(OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
|
||||
uncovered: ty,
|
||||
local_ty,
|
||||
}))
|
||||
}
|
||||
OrphanCheckEarlyExit::LocalTy(_) => Ok(()),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
struct OrphanChecker<'a, 'tcx, F> {
|
||||
infcx: &'a InferCtxt<'tcx>,
|
||||
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<(Ty<'tcx>, IsFirstInputType)>,
|
||||
}
|
||||
|
||||
impl<'a, 'tcx, F, E> OrphanChecker<'a, 'tcx, F>
|
||||
where
|
||||
F: FnOnce(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
||||
{
|
||||
fn new(infcx: &'a InferCtxt<'tcx>, 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: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx, E>> {
|
||||
self.non_local_tys.push((t, self.in_self_ty.into()));
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn found_uncovered_ty_param(
|
||||
&mut self,
|
||||
ty: Ty<'tcx>,
|
||||
) -> ControlFlow<OrphanCheckEarlyExit<'tcx, E>> {
|
||||
if self.search_first_local_ty {
|
||||
return ControlFlow::Continue(());
|
||||
}
|
||||
|
||||
ControlFlow::Break(OrphanCheckEarlyExit::UncoveredTyParam(ty))
|
||||
}
|
||||
|
||||
fn def_id_is_local(&mut self, def_id: DefId) -> bool {
|
||||
match self.in_crate {
|
||||
InCrate::Local { .. } => def_id.is_local(),
|
||||
InCrate::Remote => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum OrphanCheckEarlyExit<'tcx, E> {
|
||||
NormalizationFailure(E),
|
||||
UncoveredTyParam(Ty<'tcx>),
|
||||
LocalTy(Ty<'tcx>),
|
||||
}
|
||||
|
||||
impl<'a, 'tcx, F, E> TypeVisitor<TyCtxt<'tcx>> for OrphanChecker<'a, 'tcx, F>
|
||||
where
|
||||
F: FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
||||
{
|
||||
type Result = ControlFlow<OrphanCheckEarlyExit<'tcx, E>>;
|
||||
|
||||
fn visit_region(&mut self, _r: ty::Region<'tcx>) -> Self::Result {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
|
||||
fn visit_ty(&mut self, ty: Ty<'tcx>) -> 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(..) => bug!("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(())
|
||||
}
|
||||
_ => 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.did()) {
|
||||
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: ty::Const<'tcx>) -> Self::Result {
|
||||
ControlFlow::Continue(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the `intercrate_ambiguity_causes` for the new solver using
|
||||
/// "proof trees".
|
||||
///
|
||||
|
|
|
@ -203,7 +203,7 @@ fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span
|
|||
tcx.associated_items(trait_def_id)
|
||||
.in_definition_order()
|
||||
.filter(|item| item.kind == ty::AssocKind::Type)
|
||||
.flat_map(|item| tcx.explicit_item_bounds(item.def_id).instantiate_identity_iter_copied())
|
||||
.flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied())
|
||||
.filter_map(|c| predicate_references_self(tcx, c))
|
||||
.collect()
|
||||
}
|
||||
|
|
|
@ -1523,7 +1523,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|
|||
// bound regions.
|
||||
let trait_ref = predicate.skip_binder().trait_ref;
|
||||
|
||||
coherence::trait_ref_is_knowable::<!>(self.infcx, trait_ref, |ty| Ok(ty)).unwrap()
|
||||
coherence::trait_ref_is_knowable(self.infcx, trait_ref, |ty| Ok::<_, !>(ty)).into_ok()
|
||||
}
|
||||
|
||||
/// Returns `true` if the global caches can be used.
|
||||
|
|
|
@ -169,10 +169,8 @@ impl<'tcx> OpaqueTypeCollector<'tcx> {
|
|||
// Collect opaque types nested within the associated type bounds of this opaque type.
|
||||
// We use identity args here, because we already know that the opaque type uses
|
||||
// only generic parameters, and thus instantiating would not give us more information.
|
||||
for (pred, span) in self
|
||||
.tcx
|
||||
.explicit_item_bounds(alias_ty.def_id)
|
||||
.instantiate_identity_iter_copied()
|
||||
for (pred, span) in
|
||||
self.tcx.explicit_item_bounds(alias_ty.def_id).iter_identity_copied()
|
||||
{
|
||||
trace!(?pred);
|
||||
self.visit_spanned(span, pred);
|
||||
|
|
|
@ -62,7 +62,7 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>(
|
|||
}
|
||||
}
|
||||
DefKind::OpaqueTy => {
|
||||
for (pred, span) in tcx.explicit_item_bounds(item).instantiate_identity_iter_copied() {
|
||||
for (pred, span) in tcx.explicit_item_bounds(item).iter_identity_copied() {
|
||||
try_visit!(visitor.visit(span, pred));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -448,7 +448,7 @@ where
|
|||
|
||||
/// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
|
||||
/// but on an iterator of `TypeFoldable` values.
|
||||
pub fn instantiate_identity_iter(self) -> Iter::IntoIter {
|
||||
pub fn iter_identity(self) -> Iter::IntoIter {
|
||||
self.value.into_iter()
|
||||
}
|
||||
}
|
||||
|
@ -515,9 +515,7 @@ where
|
|||
|
||||
/// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity),
|
||||
/// but on an iterator of values that deref to a `TypeFoldable`.
|
||||
pub fn instantiate_identity_iter_copied(
|
||||
self,
|
||||
) -> impl Iterator<Item = <Iter::Item as Deref>::Target> {
|
||||
pub fn iter_identity_copied(self) -> impl Iterator<Item = <Iter::Item as Deref>::Target> {
|
||||
self.value.into_iter().map(|v| *v)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,305 @@
|
|||
use std::marker::PhantomData;
|
||||
|
||||
use smallvec::smallvec;
|
||||
|
||||
use crate::data_structures::HashSet;
|
||||
use crate::outlives::{push_outlives_components, Component};
|
||||
use crate::{self as ty, Interner};
|
||||
use crate::{inherent::*, Upcast as _};
|
||||
|
||||
/// "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<I: Interner, O> {
|
||||
cx: I,
|
||||
stack: Vec<O>,
|
||||
visited: HashSet<ty::Binder<I, ty::PredicateKind<I>>>,
|
||||
mode: Filter,
|
||||
}
|
||||
|
||||
enum Filter {
|
||||
All,
|
||||
OnlySelf,
|
||||
}
|
||||
|
||||
/// Describes how to elaborate an obligation into a sub-obligation.
|
||||
pub trait Elaboratable<I: Interner> {
|
||||
fn predicate(&self) -> I::Predicate;
|
||||
|
||||
// Makes a new `Self` but with a different clause that comes from elaboration.
|
||||
fn child(&self, clause: I::Clause) -> 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: I::Clause,
|
||||
span: I::Span,
|
||||
parent_trait_pred: ty::Binder<I, ty::TraitPredicate<I>>,
|
||||
index: usize,
|
||||
) -> Self;
|
||||
}
|
||||
|
||||
pub fn elaborate<I: Interner, O: Elaboratable<I>>(
|
||||
cx: I,
|
||||
obligations: impl IntoIterator<Item = O>,
|
||||
) -> Elaborator<I, O> {
|
||||
let mut elaborator =
|
||||
Elaborator { cx, stack: Vec::new(), visited: HashSet::default(), mode: Filter::All };
|
||||
elaborator.extend_deduped(obligations);
|
||||
elaborator
|
||||
}
|
||||
|
||||
impl<I: Interner, O: Elaboratable<I>> Elaborator<I, 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 { }`.
|
||||
self.stack.extend(
|
||||
obligations.into_iter().filter(|o| {
|
||||
self.visited.insert(self.cx.anonymize_bound_vars(o.predicate().kind()))
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// 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 cx = self.cx;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
let map_to_child_clause =
|
||||
|(index, (clause, span)): (usize, (I::Clause, I::Span))| {
|
||||
elaboratable.child_with_derived_cause(
|
||||
clause.instantiate_supertrait(cx, bound_clause.rebind(data.trait_ref)),
|
||||
span,
|
||||
bound_clause.rebind(data),
|
||||
index,
|
||||
)
|
||||
};
|
||||
|
||||
// Get predicates implied by the trait, or only super predicates if we only care about self predicates.
|
||||
match self.mode {
|
||||
Filter::All => self.extend_deduped(
|
||||
cx.explicit_implied_predicates_of(data.def_id())
|
||||
.iter_identity()
|
||||
.enumerate()
|
||||
.map(map_to_child_clause),
|
||||
),
|
||||
Filter::OnlySelf => self.extend_deduped(
|
||||
cx.explicit_super_predicates_of(data.def_id())
|
||||
.iter_identity()
|
||||
.enumerate()
|
||||
.map(map_to_child_clause),
|
||||
),
|
||||
};
|
||||
}
|
||||
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(cx, ty_max, &mut components);
|
||||
self.extend_deduped(
|
||||
components
|
||||
.into_iter()
|
||||
.filter_map(|component| elaborate_component_to_clause(cx, component, r_min))
|
||||
.map(|clause| elaboratable.child(bound_clause.rebind(clause).upcast(cx))),
|
||||
);
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn elaborate_component_to_clause<I: Interner>(
|
||||
cx: I,
|
||||
component: Component<I>,
|
||||
outlives_region: I::Region,
|
||||
) -> Option<ty::ClauseKind<I>> {
|
||||
match component {
|
||||
Component::Region(r) => {
|
||||
if r.is_bound() {
|
||||
None
|
||||
} else {
|
||||
Some(ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(r, outlives_region)))
|
||||
}
|
||||
}
|
||||
|
||||
Component::Param(p) => {
|
||||
let ty = Ty::new_param(cx, p);
|
||||
Some(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, outlives_region)))
|
||||
}
|
||||
|
||||
Component::Placeholder(p) => {
|
||||
let ty = Ty::new_placeholder(cx, p);
|
||||
Some(ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(ty, outlives_region)))
|
||||
}
|
||||
|
||||
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(cx),
|
||||
outlives_region,
|
||||
)))
|
||||
}
|
||||
|
||||
Component::EscapingAlias(_) => {
|
||||
// We might be able to do more here, but we don't
|
||||
// want to deal with escaping vars right now.
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<I: Interner, O: Elaboratable<I>> Iterator for Elaborator<I, 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
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally)
|
||||
/// does not compute the full elaborated super-predicates but just the set of def-ids. It is used
|
||||
/// 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<I: Interner>(
|
||||
cx: I,
|
||||
trait_def_id: I::DefId,
|
||||
) -> impl Iterator<Item = I::DefId> {
|
||||
let mut set = HashSet::default();
|
||||
let mut stack = vec![trait_def_id];
|
||||
|
||||
set.insert(trait_def_id);
|
||||
|
||||
std::iter::from_fn(move || {
|
||||
let trait_def_id = stack.pop()?;
|
||||
|
||||
for (predicate, _) in cx.explicit_super_predicates_of(trait_def_id).iter_identity() {
|
||||
if let ty::ClauseKind::Trait(data) = predicate.kind().skip_binder() {
|
||||
if set.insert(data.def_id()) {
|
||||
stack.push(data.def_id());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(trait_def_id)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn supertraits<I: Interner>(
|
||||
tcx: I,
|
||||
trait_ref: ty::Binder<I, ty::TraitRef<I>>,
|
||||
) -> FilterToTraits<I, Elaborator<I, I::Clause>> {
|
||||
elaborate(tcx, [trait_ref.upcast(tcx)]).filter_only_self().filter_to_traits()
|
||||
}
|
||||
|
||||
pub fn transitive_bounds<I: Interner>(
|
||||
tcx: I,
|
||||
trait_refs: impl Iterator<Item = ty::Binder<I, ty::TraitRef<I>>>,
|
||||
) -> FilterToTraits<I, Elaborator<I, I::Clause>> {
|
||||
elaborate(tcx, trait_refs.map(|trait_ref| trait_ref.upcast(tcx)))
|
||||
.filter_only_self()
|
||||
.filter_to_traits()
|
||||
}
|
||||
|
||||
impl<I: Interner> Elaborator<I, I::Clause> {
|
||||
fn filter_to_traits(self) -> FilterToTraits<I, Self> {
|
||||
FilterToTraits { _cx: PhantomData, base_iterator: self }
|
||||
}
|
||||
}
|
||||
|
||||
/// A filter around an iterator of predicates that makes it yield up
|
||||
/// just trait references.
|
||||
pub struct FilterToTraits<I: Interner, It: Iterator<Item = I::Clause>> {
|
||||
_cx: PhantomData<I>,
|
||||
base_iterator: It,
|
||||
}
|
||||
|
||||
impl<I: Interner, It: Iterator<Item = I::Clause>> Iterator for FilterToTraits<I, It> {
|
||||
type Item = ty::Binder<I, ty::TraitRef<I>>;
|
||||
|
||||
fn next(&mut self) -> Option<ty::Binder<I, ty::TraitRef<I>>> {
|
||||
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)
|
||||
}
|
||||
}
|
|
@ -3,7 +3,7 @@ use crate::relate::Relate;
|
|||
use crate::solve::{Goal, NoSolution, SolverMode};
|
||||
use crate::{self as ty, Interner};
|
||||
|
||||
pub trait InferCtxtLike {
|
||||
pub trait InferCtxtLike: Sized {
|
||||
type Interner: Interner;
|
||||
fn cx(&self) -> Self::Interner;
|
||||
|
||||
|
@ -73,6 +73,11 @@ pub trait InferCtxtLike {
|
|||
rhs: T,
|
||||
) -> Result<Vec<Goal<Self::Interner, <Self::Interner as Interner>::Predicate>>, NoSolution>;
|
||||
|
||||
fn shallow_resolve(
|
||||
&self,
|
||||
ty: <Self::Interner as Interner>::Ty,
|
||||
) -> <Self::Interner as Interner>::Ty;
|
||||
|
||||
fn resolve_vars_if_possible<T>(&self, value: T) -> T
|
||||
where
|
||||
T: TypeFoldable<Self::Interner>;
|
||||
|
|
|
@ -9,6 +9,7 @@ use std::hash::Hash;
|
|||
use rustc_ast_ir::Mutability;
|
||||
|
||||
use crate::data_structures::HashSet;
|
||||
use crate::elaborate::Elaboratable;
|
||||
use crate::fold::{TypeFoldable, TypeSuperFoldable};
|
||||
use crate::relate::Relate;
|
||||
use crate::solve::{CacheData, CanonicalInput, QueryResult, Reveal};
|
||||
|
@ -40,6 +41,10 @@ pub trait Ty<I: Interner<Ty = Self>>:
|
|||
|
||||
fn new_var(interner: I, var: ty::TyVid) -> Self;
|
||||
|
||||
fn new_param(interner: I, param: I::ParamTy) -> Self;
|
||||
|
||||
fn new_placeholder(interner: I, param: I::PlaceholderTy) -> Self;
|
||||
|
||||
fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: I::BoundTy) -> Self;
|
||||
|
||||
fn new_anon_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self;
|
||||
|
@ -429,6 +434,8 @@ pub trait Predicate<I: Interner<Predicate = Self>>:
|
|||
+ UpcastFrom<I, ty::OutlivesPredicate<I, I::Region>>
|
||||
+ IntoKind<Kind = ty::Binder<I, ty::PredicateKind<I>>>
|
||||
{
|
||||
fn as_clause(self) -> Option<I::Clause>;
|
||||
|
||||
fn is_coinductive(self, interner: I) -> bool;
|
||||
|
||||
// FIXME: Eventually uplift the impl out of rustc and make this defaulted.
|
||||
|
@ -441,35 +448,35 @@ pub trait Clause<I: Interner<Clause = Self>>:
|
|||
+ Hash
|
||||
+ Eq
|
||||
+ TypeFoldable<I>
|
||||
// FIXME: Remove these, uplift the `Upcast` impls.
|
||||
+ UpcastFrom<I, ty::Binder<I, ty::ClauseKind<I>>>
|
||||
+ UpcastFrom<I, ty::TraitRef<I>>
|
||||
+ UpcastFrom<I, ty::Binder<I, ty::TraitRef<I>>>
|
||||
+ UpcastFrom<I, ty::ProjectionPredicate<I>>
|
||||
+ UpcastFrom<I, ty::Binder<I, ty::ProjectionPredicate<I>>>
|
||||
+ IntoKind<Kind = ty::Binder<I, ty::ClauseKind<I>>>
|
||||
+ Elaboratable<I>
|
||||
{
|
||||
fn as_trait_clause(self) -> Option<ty::Binder<I, ty::TraitPredicate<I>>> {
|
||||
self.kind()
|
||||
.map_bound(|clause| {
|
||||
if let ty::ClauseKind::Trait(t) = clause {
|
||||
Some(t)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.map_bound(|clause| if let ty::ClauseKind::Trait(t) = clause { Some(t) } else { None })
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn as_projection_clause(self) -> Option<ty::Binder<I, ty::ProjectionPredicate<I>>> {
|
||||
self.kind()
|
||||
.map_bound(|clause| {
|
||||
if let ty::ClauseKind::Projection(p) = clause {
|
||||
Some(p)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.map_bound(
|
||||
|clause| {
|
||||
if let ty::ClauseKind::Projection(p) = clause { Some(p) } else { None }
|
||||
},
|
||||
)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Performs a instantiation suitable for going from a
|
||||
/// poly-trait-ref to supertraits that must hold if that
|
||||
/// poly-trait-ref holds. This is slightly different from a normal
|
||||
/// instantiation in terms of what happens with bound regions.
|
||||
fn instantiate_supertrait(self, tcx: I, trait_ref: ty::Binder<I, ty::TraitRef<I>>) -> Self;
|
||||
}
|
||||
|
||||
/// Common capabilities of placeholder kinds
|
||||
|
@ -514,6 +521,8 @@ pub trait AdtDef<I: Interner>: Copy + Debug + Hash + Eq {
|
|||
fn all_field_tys(self, interner: I) -> ty::EarlyBinder<I, impl IntoIterator<Item = I::Ty>>;
|
||||
|
||||
fn sized_constraint(self, interner: I) -> Option<ty::EarlyBinder<I, I::Ty>>;
|
||||
|
||||
fn is_fundamental(self) -> bool;
|
||||
}
|
||||
|
||||
pub trait ParamEnv<I: Interner>: Copy + Debug + Hash + Eq + TypeFoldable<I> {
|
||||
|
@ -558,6 +567,8 @@ pub trait EvaluationCache<I: Interner> {
|
|||
}
|
||||
|
||||
pub trait DefId<I: Interner>: Copy + Debug + Hash + Eq + TypeFoldable<I> {
|
||||
fn is_local(self) -> bool;
|
||||
|
||||
fn as_local(self) -> Option<I::LocalDefId>;
|
||||
}
|
||||
|
||||
|
|
|
@ -32,7 +32,7 @@ pub trait Interner:
|
|||
{
|
||||
type DefId: DefId<Self>;
|
||||
type LocalDefId: Copy + Debug + Hash + Eq + Into<Self::DefId> + TypeFoldable<Self>;
|
||||
type Span: Copy + Debug + Hash + Eq;
|
||||
type Span: Copy + Debug + Hash + Eq + TypeFoldable<Self>;
|
||||
|
||||
type GenericArgs: GenericArgs<Self>;
|
||||
type GenericArgsSlice: Copy + Debug + Hash + Eq + SliceLike<Item = Self::GenericArg>;
|
||||
|
@ -213,7 +213,12 @@ pub trait Interner:
|
|||
fn explicit_super_predicates_of(
|
||||
self,
|
||||
def_id: Self::DefId,
|
||||
) -> ty::EarlyBinder<Self, impl IntoIterator<Item = Self::Clause>>;
|
||||
) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
|
||||
|
||||
fn explicit_implied_predicates_of(
|
||||
self,
|
||||
def_id: Self::DefId,
|
||||
) -> ty::EarlyBinder<Self, impl IntoIterator<Item = (Self::Clause, Self::Span)>>;
|
||||
|
||||
fn has_target_features(self, def_id: Self::DefId) -> bool;
|
||||
|
||||
|
@ -246,10 +251,9 @@ pub trait Interner:
|
|||
|
||||
fn trait_is_object_safe(self, trait_def_id: Self::DefId) -> bool;
|
||||
|
||||
fn trait_may_be_implemented_via_object(self, trait_def_id: Self::DefId) -> bool;
|
||||
fn trait_is_fundamental(self, def_id: Self::DefId) -> bool;
|
||||
|
||||
fn supertrait_def_ids(self, trait_def_id: Self::DefId)
|
||||
-> impl IntoIterator<Item = Self::DefId>;
|
||||
fn trait_may_be_implemented_via_object(self, trait_def_id: Self::DefId) -> bool;
|
||||
|
||||
fn delay_bug(self, msg: impl ToString) -> Self::ErrorGuaranteed;
|
||||
|
||||
|
@ -268,6 +272,11 @@ pub trait Interner:
|
|||
param_env: Self::ParamEnv,
|
||||
placeholder: Self::PlaceholderConst,
|
||||
) -> Self::Ty;
|
||||
|
||||
fn anonymize_bound_vars<T: TypeFoldable<Self>>(
|
||||
self,
|
||||
binder: ty::Binder<Self, T>,
|
||||
) -> ty::Binder<Self, T>;
|
||||
}
|
||||
|
||||
/// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter`
|
||||
|
|
|
@ -20,6 +20,7 @@ pub mod visit;
|
|||
#[cfg(feature = "nightly")]
|
||||
pub mod codec;
|
||||
pub mod data_structures;
|
||||
pub mod elaborate;
|
||||
pub mod error;
|
||||
pub mod fast_reject;
|
||||
pub mod fold;
|
||||
|
|
|
@ -197,11 +197,7 @@ macro_rules! acquire {
|
|||
///
|
||||
/// Sharing some immutable data between threads:
|
||||
///
|
||||
// Note that we **do not** run these tests here. The windows builders get super
|
||||
// unhappy if a thread outlives the main thread and then exits at the same time
|
||||
// (something deadlocks) so we just avoid this entirely by not running these
|
||||
// tests.
|
||||
/// ```no_run
|
||||
/// ```
|
||||
/// use std::sync::Arc;
|
||||
/// use std::thread;
|
||||
///
|
||||
|
@ -220,7 +216,7 @@ macro_rules! acquire {
|
|||
///
|
||||
/// [`AtomicUsize`]: core::sync::atomic::AtomicUsize "sync::atomic::AtomicUsize"
|
||||
///
|
||||
/// ```no_run
|
||||
/// ```
|
||||
/// use std::sync::Arc;
|
||||
/// use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
/// use std::thread;
|
||||
|
|
|
@ -10,8 +10,6 @@
|
|||
#![allow(non_camel_case_types)]
|
||||
|
||||
use crate::fmt;
|
||||
use crate::marker::PhantomData;
|
||||
use crate::ops::{Deref, DerefMut};
|
||||
|
||||
#[doc(no_inline)]
|
||||
#[stable(feature = "core_c_str", since = "1.64.0")]
|
||||
|
@ -28,6 +26,20 @@ pub use self::c_str::CStr;
|
|||
#[unstable(feature = "c_str_module", issue = "112134")]
|
||||
pub mod c_str;
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
issue = "44930",
|
||||
reason = "the `c_variadic` feature has not been properly tested on all supported platforms"
|
||||
)]
|
||||
pub use self::va_list::{VaList, VaListImpl};
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
issue = "44930",
|
||||
reason = "the `c_variadic` feature has not been properly tested on all supported platforms"
|
||||
)]
|
||||
pub mod va_list;
|
||||
|
||||
macro_rules! type_alias {
|
||||
{
|
||||
$Docfile:tt, $Alias:ident = $Real:ty;
|
||||
|
@ -205,404 +217,6 @@ impl fmt::Debug for c_void {
|
|||
}
|
||||
}
|
||||
|
||||
/// Basic implementation of a `va_list`.
|
||||
// The name is WIP, using `VaListImpl` for now.
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
ptr: *mut c_void,
|
||||
|
||||
// Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
|
||||
// the region of the function it's defined in
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> fmt::Debug for VaListImpl<'f> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "va_list* {:p}", self.ptr)
|
||||
}
|
||||
}
|
||||
|
||||
/// AArch64 ABI implementation of a `va_list`. See the
|
||||
/// [AArch64 Procedure Call Standard] for more details.
|
||||
///
|
||||
/// [AArch64 Procedure Call Standard]:
|
||||
/// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
|
||||
#[cfg(all(
|
||||
target_arch = "aarch64",
|
||||
not(target_vendor = "apple"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
stack: *mut c_void,
|
||||
gr_top: *mut c_void,
|
||||
vr_top: *mut c_void,
|
||||
gr_offs: i32,
|
||||
vr_offs: i32,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// PowerPC ABI implementation of a `va_list`.
|
||||
#[cfg(all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gpr: u8,
|
||||
fpr: u8,
|
||||
reserved: u16,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// s390x ABI implementation of a `va_list`.
|
||||
#[cfg(target_arch = "s390x")]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gpr: i64,
|
||||
fpr: i64,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// x86_64 ABI implementation of a `va_list`.
|
||||
#[cfg(all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gp_offset: i32,
|
||||
fp_offset: i32,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// A wrapper for a `va_list`
|
||||
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435
|
||||
#[derive(Debug)]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
pub struct VaList<'a, 'f: 'a> {
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
inner: VaListImpl<'f>,
|
||||
|
||||
#[cfg(all(
|
||||
any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "powerpc",
|
||||
target_arch = "s390x",
|
||||
target_arch = "x86_64"
|
||||
),
|
||||
any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
|
||||
not(target_family = "wasm"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
inner: &'a mut VaListImpl<'f>,
|
||||
|
||||
_marker: PhantomData<&'a mut VaListImpl<'f>>,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
|
||||
#[inline]
|
||||
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
|
||||
VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "powerpc",
|
||||
target_arch = "s390x",
|
||||
target_arch = "x86_64"
|
||||
),
|
||||
any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
|
||||
not(target_family = "wasm"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
|
||||
#[inline]
|
||||
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
|
||||
VaList { inner: self, _marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
|
||||
type Target = VaListImpl<'f>;
|
||||
|
||||
#[inline]
|
||||
fn deref(&self) -> &VaListImpl<'f> {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
// The VaArgSafe trait needs to be used in public interfaces, however, the trait
|
||||
// itself must not be allowed to be used outside this module. Allowing users to
|
||||
// implement the trait for a new type (thereby allowing the va_arg intrinsic to
|
||||
// be used on a new type) is likely to cause undefined behavior.
|
||||
//
|
||||
// FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
|
||||
// but also ensure it cannot be used elsewhere, the trait needs to be public
|
||||
// within a private module. Once RFC 2145 has been implemented look into
|
||||
// improving this.
|
||||
mod sealed_trait {
|
||||
/// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
pub unsafe trait VaArgSafe {}
|
||||
}
|
||||
|
||||
macro_rules! impl_va_arg_safe {
|
||||
($($t:ty),+) => {
|
||||
$(
|
||||
#[unstable(feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930")]
|
||||
unsafe impl sealed_trait::VaArgSafe for $t {}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
impl_va_arg_safe! {i8, i16, i32, i64, usize}
|
||||
impl_va_arg_safe! {u8, u16, u32, u64, isize}
|
||||
impl_va_arg_safe! {f64}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
unsafe impl<T> sealed_trait::VaArgSafe for *mut T {}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
unsafe impl<T> sealed_trait::VaArgSafe for *const T {}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Advance to the next arg.
|
||||
#[inline]
|
||||
pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
|
||||
// SAFETY: the caller must uphold the safety contract for `va_arg`.
|
||||
unsafe { va_arg(self) }
|
||||
}
|
||||
|
||||
/// Copies the `va_list` at the current location.
|
||||
pub unsafe fn with_copy<F, R>(&self, f: F) -> R
|
||||
where
|
||||
F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
|
||||
{
|
||||
let mut ap = self.clone();
|
||||
let ret = f(ap.as_va_list());
|
||||
// SAFETY: the caller must uphold the safety contract for `va_end`.
|
||||
unsafe {
|
||||
va_end(&mut ap);
|
||||
}
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> Clone for VaListImpl<'f> {
|
||||
#[inline]
|
||||
fn clone(&self) -> Self {
|
||||
let mut dest = crate::mem::MaybeUninit::uninit();
|
||||
// SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
|
||||
unsafe {
|
||||
va_copy(dest.as_mut_ptr(), self);
|
||||
dest.assume_init()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(
|
||||
feature = "c_variadic",
|
||||
reason = "the `c_variadic` feature has not been properly tested on \
|
||||
all supported platforms",
|
||||
issue = "44930"
|
||||
)]
|
||||
impl<'f> Drop for VaListImpl<'f> {
|
||||
fn drop(&mut self) {
|
||||
// FIXME: this should call `va_end`, but there's no clean way to
|
||||
// guarantee that `drop` always gets inlined into its caller,
|
||||
// so the `va_end` would get directly called from the same function as
|
||||
// the corresponding `va_copy`. `man va_end` states that C requires this,
|
||||
// and LLVM basically follows the C semantics, so we need to make sure
|
||||
// that `va_end` is always called from the same function as `va_copy`.
|
||||
// For more details, see https://github.com/rust-lang/rust/pull/59625
|
||||
// and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
|
||||
//
|
||||
// This works for now, since `va_end` is a no-op on all current LLVM targets.
|
||||
}
|
||||
}
|
||||
|
||||
extern "rust-intrinsic" {
|
||||
/// Destroy the arglist `ap` after initialization with `va_start` or
|
||||
/// `va_copy`.
|
||||
#[rustc_nounwind]
|
||||
fn va_end(ap: &mut VaListImpl<'_>);
|
||||
|
||||
/// Copies the current location of arglist `src` to the arglist `dst`.
|
||||
#[rustc_nounwind]
|
||||
fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
|
||||
|
||||
/// Loads an argument of type `T` from the `va_list` `ap` and increment the
|
||||
/// argument `ap` points to.
|
||||
#[rustc_nounwind]
|
||||
fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
|
||||
}
|
||||
|
||||
// Link the MSVC default lib
|
||||
#[cfg(all(windows, target_env = "msvc"))]
|
||||
#[link(
|
||||
|
|
|
@ -0,0 +1,301 @@
|
|||
//! C's "variable arguments"
|
||||
//!
|
||||
//! Better known as "varargs".
|
||||
|
||||
use crate::ffi::c_void;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use crate::fmt;
|
||||
use crate::marker::PhantomData;
|
||||
use crate::ops::{Deref, DerefMut};
|
||||
|
||||
/// Basic implementation of a `va_list`.
|
||||
// The name is WIP, using `VaListImpl` for now.
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
ptr: *mut c_void,
|
||||
|
||||
// Invariant over `'f`, so each `VaListImpl<'f>` object is tied to
|
||||
// the region of the function it's defined in
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
impl<'f> fmt::Debug for VaListImpl<'f> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "va_list* {:p}", self.ptr)
|
||||
}
|
||||
}
|
||||
|
||||
/// AArch64 ABI implementation of a `va_list`. See the
|
||||
/// [AArch64 Procedure Call Standard] for more details.
|
||||
///
|
||||
/// [AArch64 Procedure Call Standard]:
|
||||
/// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf
|
||||
#[cfg(all(
|
||||
target_arch = "aarch64",
|
||||
not(target_vendor = "apple"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
stack: *mut c_void,
|
||||
gr_top: *mut c_void,
|
||||
vr_top: *mut c_void,
|
||||
gr_offs: i32,
|
||||
vr_offs: i32,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// PowerPC ABI implementation of a `va_list`.
|
||||
#[cfg(all(target_arch = "powerpc", not(target_os = "uefi"), not(windows)))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gpr: u8,
|
||||
fpr: u8,
|
||||
reserved: u16,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// s390x ABI implementation of a `va_list`.
|
||||
#[cfg(target_arch = "s390x")]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gpr: i64,
|
||||
fpr: i64,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// x86_64 ABI implementation of a `va_list`.
|
||||
#[cfg(all(target_arch = "x86_64", not(target_os = "uefi"), not(windows)))]
|
||||
#[cfg_attr(not(doc), repr(C))] // work around https://github.com/rust-lang/rust/issues/66401
|
||||
#[derive(Debug)]
|
||||
#[lang = "va_list"]
|
||||
pub struct VaListImpl<'f> {
|
||||
gp_offset: i32,
|
||||
fp_offset: i32,
|
||||
overflow_arg_area: *mut c_void,
|
||||
reg_save_area: *mut c_void,
|
||||
_marker: PhantomData<&'f mut &'f c_void>,
|
||||
}
|
||||
|
||||
/// A wrapper for a `va_list`
|
||||
#[cfg_attr(not(doc), repr(transparent))] // work around https://github.com/rust-lang/rust/issues/90435
|
||||
#[derive(Debug)]
|
||||
pub struct VaList<'a, 'f: 'a> {
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
inner: VaListImpl<'f>,
|
||||
|
||||
#[cfg(all(
|
||||
any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "powerpc",
|
||||
target_arch = "s390x",
|
||||
target_arch = "x86_64"
|
||||
),
|
||||
any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
|
||||
not(target_family = "wasm"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
inner: &'a mut VaListImpl<'f>,
|
||||
|
||||
_marker: PhantomData<&'a mut VaListImpl<'f>>,
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(
|
||||
not(target_arch = "aarch64"),
|
||||
not(target_arch = "powerpc"),
|
||||
not(target_arch = "s390x"),
|
||||
not(target_arch = "x86_64")
|
||||
),
|
||||
all(target_arch = "aarch64", target_vendor = "apple"),
|
||||
target_family = "wasm",
|
||||
target_os = "uefi",
|
||||
windows,
|
||||
))]
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
|
||||
#[inline]
|
||||
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
|
||||
VaList { inner: VaListImpl { ..*self }, _marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(
|
||||
any(
|
||||
target_arch = "aarch64",
|
||||
target_arch = "powerpc",
|
||||
target_arch = "s390x",
|
||||
target_arch = "x86_64"
|
||||
),
|
||||
any(not(target_arch = "aarch64"), not(target_vendor = "apple")),
|
||||
not(target_family = "wasm"),
|
||||
not(target_os = "uefi"),
|
||||
not(windows),
|
||||
))]
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Convert a `VaListImpl` into a `VaList` that is binary-compatible with C's `va_list`.
|
||||
#[inline]
|
||||
pub fn as_va_list<'a>(&'a mut self) -> VaList<'a, 'f> {
|
||||
VaList { inner: self, _marker: PhantomData }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'f: 'a> Deref for VaList<'a, 'f> {
|
||||
type Target = VaListImpl<'f>;
|
||||
|
||||
#[inline]
|
||||
fn deref(&self) -> &VaListImpl<'f> {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'f: 'a> DerefMut for VaList<'a, 'f> {
|
||||
#[inline]
|
||||
fn deref_mut(&mut self) -> &mut VaListImpl<'f> {
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
// The VaArgSafe trait needs to be used in public interfaces, however, the trait
|
||||
// itself must not be allowed to be used outside this module. Allowing users to
|
||||
// implement the trait for a new type (thereby allowing the va_arg intrinsic to
|
||||
// be used on a new type) is likely to cause undefined behavior.
|
||||
//
|
||||
// FIXME(dlrobertson): In order to use the VaArgSafe trait in a public interface
|
||||
// but also ensure it cannot be used elsewhere, the trait needs to be public
|
||||
// within a private module. Once RFC 2145 has been implemented look into
|
||||
// improving this.
|
||||
mod sealed_trait {
|
||||
/// Trait which permits the allowed types to be used with [super::VaListImpl::arg].
|
||||
pub unsafe trait VaArgSafe {}
|
||||
}
|
||||
|
||||
macro_rules! impl_va_arg_safe {
|
||||
($($t:ty),+) => {
|
||||
$(
|
||||
unsafe impl sealed_trait::VaArgSafe for $t {}
|
||||
)+
|
||||
}
|
||||
}
|
||||
|
||||
impl_va_arg_safe! {i8, i16, i32, i64, usize}
|
||||
impl_va_arg_safe! {u8, u16, u32, u64, isize}
|
||||
impl_va_arg_safe! {f64}
|
||||
|
||||
unsafe impl<T> sealed_trait::VaArgSafe for *mut T {}
|
||||
unsafe impl<T> sealed_trait::VaArgSafe for *const T {}
|
||||
|
||||
impl<'f> VaListImpl<'f> {
|
||||
/// Advance to the next arg.
|
||||
#[inline]
|
||||
pub unsafe fn arg<T: sealed_trait::VaArgSafe>(&mut self) -> T {
|
||||
// SAFETY: the caller must uphold the safety contract for `va_arg`.
|
||||
unsafe { va_arg(self) }
|
||||
}
|
||||
|
||||
/// Copies the `va_list` at the current location.
|
||||
pub unsafe fn with_copy<F, R>(&self, f: F) -> R
|
||||
where
|
||||
F: for<'copy> FnOnce(VaList<'copy, 'f>) -> R,
|
||||
{
|
||||
let mut ap = self.clone();
|
||||
let ret = f(ap.as_va_list());
|
||||
// SAFETY: the caller must uphold the safety contract for `va_end`.
|
||||
unsafe {
|
||||
va_end(&mut ap);
|
||||
}
|
||||
ret
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f> Clone for VaListImpl<'f> {
|
||||
#[inline]
|
||||
fn clone(&self) -> Self {
|
||||
let mut dest = crate::mem::MaybeUninit::uninit();
|
||||
// SAFETY: we write to the `MaybeUninit`, thus it is initialized and `assume_init` is legal
|
||||
unsafe {
|
||||
va_copy(dest.as_mut_ptr(), self);
|
||||
dest.assume_init()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'f> Drop for VaListImpl<'f> {
|
||||
fn drop(&mut self) {
|
||||
// FIXME: this should call `va_end`, but there's no clean way to
|
||||
// guarantee that `drop` always gets inlined into its caller,
|
||||
// so the `va_end` would get directly called from the same function as
|
||||
// the corresponding `va_copy`. `man va_end` states that C requires this,
|
||||
// and LLVM basically follows the C semantics, so we need to make sure
|
||||
// that `va_end` is always called from the same function as `va_copy`.
|
||||
// For more details, see https://github.com/rust-lang/rust/pull/59625
|
||||
// and https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic.
|
||||
//
|
||||
// This works for now, since `va_end` is a no-op on all current LLVM targets.
|
||||
}
|
||||
}
|
||||
|
||||
extern "rust-intrinsic" {
|
||||
/// Destroy the arglist `ap` after initialization with `va_start` or
|
||||
/// `va_copy`.
|
||||
#[rustc_nounwind]
|
||||
fn va_end(ap: &mut VaListImpl<'_>);
|
||||
|
||||
/// Copies the current location of arglist `src` to the arglist `dst`.
|
||||
#[rustc_nounwind]
|
||||
fn va_copy<'f>(dest: *mut VaListImpl<'f>, src: &VaListImpl<'f>);
|
||||
|
||||
/// Loads an argument of type `T` from the `va_list` `ap` and increment the
|
||||
/// argument `ap` points to.
|
||||
#[rustc_nounwind]
|
||||
fn va_arg<T: sealed_trait::VaArgSafe>(ap: &mut VaListImpl<'_>) -> T;
|
||||
}
|
|
@ -1404,8 +1404,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>(
|
|||
|
||||
let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates;
|
||||
if let ty::TraitContainer = assoc_item.container {
|
||||
let bounds =
|
||||
tcx.explicit_item_bounds(assoc_item.def_id).instantiate_identity_iter_copied();
|
||||
let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied();
|
||||
predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied()));
|
||||
}
|
||||
let mut generics = clean_ty_generics(
|
||||
|
|
|
@ -99,7 +99,7 @@ pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'
|
|||
for (predicate, _span) in cx
|
||||
.tcx
|
||||
.explicit_item_super_predicates(def_id)
|
||||
.instantiate_identity_iter_copied()
|
||||
.iter_identity_copied()
|
||||
{
|
||||
match predicate.kind().skip_binder() {
|
||||
// For `impl Trait<U>`, it will register a predicate of `T: Trait<U>`, so we go through
|
||||
|
|
|
@ -296,7 +296,8 @@ pub fn not_contains<P: AsRef<Path>>(path: P, expected: &str) -> bool {
|
|||
}
|
||||
|
||||
/// Returns true if the filename at `path` is not in `expected`.
|
||||
pub fn filename_not_in_denylist<P: AsRef<Path>>(path: P, expected: &[String]) -> bool {
|
||||
pub fn filename_not_in_denylist<P: AsRef<Path>, V: AsRef<[String]>>(path: P, expected: V) -> bool {
|
||||
let expected = expected.as_ref();
|
||||
path.as_ref()
|
||||
.file_name()
|
||||
.is_some_and(|name| !expected.contains(&name.to_str().unwrap().to_owned()))
|
||||
|
|
|
@ -45,6 +45,8 @@ const EXCEPTION_PATHS: &[&str] = &[
|
|||
// pointer regardless of the target architecture. As a result,
|
||||
// we must use `#[cfg(windows)]` to conditionally compile the
|
||||
// correct `VaList` structure for windows.
|
||||
"library/core/src/ffi/va_list.rs",
|
||||
// We placed a linkage against Windows libraries here
|
||||
"library/core/src/ffi/mod.rs",
|
||||
"library/std/src/sys", // Platform-specific code for std lives here.
|
||||
"library/std/src/os", // Platform-specific public interfaces
|
||||
|
|
|
@ -17,9 +17,8 @@ use std::path::PathBuf;
|
|||
// `rustc_invocation`: the rustc command being tested
|
||||
// Any unexpected output files not listed in `must_exist` or `can_exist` will cause a failure.
|
||||
fn assert_expected_output_files(expectations: Expectations, rustc_invocation: impl Fn()) {
|
||||
let must_exist = expectations.expected_files;
|
||||
let can_exist = expectations.allowed_files;
|
||||
let dir = expectations.test_dir;
|
||||
let Expectations { expected_files: must_exist, allowed_files: can_exist, test_dir: dir } =
|
||||
expectations;
|
||||
|
||||
fs_wrapper::create_dir(&dir);
|
||||
rustc_invocation();
|
||||
|
|
|
@ -0,0 +1,18 @@
|
|||
// ignore-tidy-linelength
|
||||
#![feature(trait_alias)]
|
||||
|
||||
// @set StrLike = "$.index[*][?(@.name=='StrLike')].id"
|
||||
// @is "$.index[*][?(@.name=='StrLike')].visibility" \"public\"
|
||||
// @has "$.index[*][?(@.name=='StrLike')].inner.trait_alias"
|
||||
// @is "$.index[*][?(@.name=='StrLike')].span.filename" $FILE
|
||||
pub trait StrLike = AsRef<str>;
|
||||
|
||||
// @is "$.index[*][?(@.name=='f')].inner.function.decl.output.impl_trait[0].trait_bound.trait.id" $StrLike
|
||||
pub fn f() -> impl StrLike {
|
||||
"heya"
|
||||
}
|
||||
|
||||
// @!is "$.index[*][?(@.name=='g')].inner.function.decl.output.impl_trait[0].trait_bound.trait.id" $StrLike
|
||||
pub fn g() -> impl AsRef<str> {
|
||||
"heya"
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
// @set IntVec = "$.index[*][?(@.name=='IntVec')].id"
|
||||
// @is "$.index[*][?(@.name=='IntVec')].visibility" \"public\"
|
||||
// @has "$.index[*][?(@.name=='IntVec')].inner.type_alias"
|
||||
// @is "$.index[*][?(@.name=='IntVec')].span.filename" $FILE
|
||||
pub type IntVec = Vec<u32>;
|
||||
|
||||
// @is "$.index[*][?(@.name=='f')].inner.function.decl.output.resolved_path.id" $IntVec
|
||||
pub fn f() -> IntVec {
|
||||
vec![0; 32]
|
||||
}
|
||||
|
||||
// @!is "$.index[*][?(@.name=='g')].inner.function.decl.output.resolved_path.id" $IntVec
|
||||
pub fn g() -> Vec<u32> {
|
||||
vec![0; 32]
|
||||
}
|
|
@ -1,6 +1,6 @@
|
|||
//! Check that intrinsics that do not get overridden, but are marked as such,
|
||||
//! cause an error instead of silently invoking the body.
|
||||
#![feature(rustc_attrs/* , effects*/)] // FIXME(effects)
|
||||
#![feature(rustc_attrs)]
|
||||
//@ build-fail
|
||||
//@ failure-status:101
|
||||
//@ normalize-stderr-test ".*note: .*\n\n" -> ""
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
error: using `#![feature(effects)]` without enabling next trait solver globally
|
||||
|
|
||||
= note: the next trait solver must be enabled globally for the effects feature to work correctly
|
||||
= help: use `-Znext-solver` to enable
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `size_of`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:5
|
||||
|
|
||||
LL | fn size_of<T>() -> usize;
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `size_of`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:5
|
||||
|
|
||||
LL | fn size_of<T>() -> usize;
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `assume`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:16:1
|
||||
|
|
||||
LL | const fn assume(_b: bool) {}
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: intrinsic has wrong type
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:16:16
|
||||
|
|
||||
LL | const fn assume(_b: bool) {}
|
||||
| ^ expected unsafe fn, found safe fn
|
||||
|
|
||||
= note: expected signature `unsafe fn(_)`
|
||||
found signature `fn(_)`
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `const_deallocate`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:20:1
|
||||
|
|
||||
LL | const fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {}
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: intrinsic has wrong type
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:20:26
|
||||
|
|
||||
LL | const fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {}
|
||||
| ^ expected unsafe fn, found safe fn
|
||||
|
|
||||
= note: expected signature `unsafe fn(_, _, _)`
|
||||
found signature `fn(_, _, _)`
|
||||
|
||||
error: aborting due to 7 previous errors
|
||||
|
||||
For more information about this error, try `rustc --explain E0308`.
|
|
@ -1,6 +1,11 @@
|
|||
//@ revisions: stock effects
|
||||
#![feature(intrinsics)]
|
||||
#![feature(rustc_attrs)]
|
||||
// FIXME(effects) do this with revisions #![feature(effects)]
|
||||
// as effects insert a const generic param to const intrinsics,
|
||||
// check here that it doesn't report a const param mismatch either
|
||||
// enabling or disabling effects.
|
||||
#![cfg_attr(effects, feature(effects))]
|
||||
#![allow(incomplete_features)]
|
||||
|
||||
extern "rust-intrinsic" {
|
||||
fn size_of<T>() -> usize; //~ ERROR intrinsic safety mismatch
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `size_of`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:6:5
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:5
|
||||
|
|
||||
LL | fn size_of<T>() -> usize;
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `size_of`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:6:5
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:5
|
||||
|
|
||||
LL | fn size_of<T>() -> usize;
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
@ -13,13 +13,13 @@ LL | fn size_of<T>() -> usize;
|
|||
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `assume`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:1
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:16:1
|
||||
|
|
||||
LL | const fn assume(_b: bool) {}
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: intrinsic has wrong type
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:11:16
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:16:16
|
||||
|
|
||||
LL | const fn assume(_b: bool) {}
|
||||
| ^ expected unsafe fn, found safe fn
|
||||
|
@ -28,13 +28,13 @@ LL | const fn assume(_b: bool) {}
|
|||
found signature `fn(_)`
|
||||
|
||||
error: intrinsic safety mismatch between list of intrinsics within the compiler and core library intrinsics for intrinsic `const_deallocate`
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:15:1
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:20:1
|
||||
|
|
||||
LL | const fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {}
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error[E0308]: intrinsic has wrong type
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:15:26
|
||||
--> $DIR/safe-intrinsic-mismatch.rs:20:26
|
||||
|
|
||||
LL | const fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {}
|
||||
| ^ expected unsafe fn, found safe fn
|
|
@ -37,6 +37,16 @@ macro_rules! without_dollar_sign_is_an_ident {
|
|||
};
|
||||
}
|
||||
|
||||
macro_rules! literals {
|
||||
($ident:ident) => {{
|
||||
let ${concat(_a, "_b")}: () = ();
|
||||
let ${concat("_b", _a)}: () = ();
|
||||
|
||||
let ${concat($ident, "_b")}: () = ();
|
||||
let ${concat("_b", $ident)}: () = ();
|
||||
}};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
create_things!(behold);
|
||||
behold_separated_idents_in_a_fn();
|
||||
|
@ -55,4 +65,6 @@ fn main() {
|
|||
without_dollar_sign_is_an_ident!(_123);
|
||||
assert_eq!(VARident, 1);
|
||||
assert_eq!(VAR_123, 2);
|
||||
|
||||
literals!(_hello);
|
||||
}
|
||||
|
|
|
@ -26,14 +26,14 @@ macro_rules! idents_11 {
|
|||
macro_rules! no_params {
|
||||
() => {
|
||||
let ${concat(r#abc, abc)}: () = ();
|
||||
//~^ ERROR `${concat(..)}` currently does not support raw identifiers
|
||||
//~^ ERROR expected identifier or string literal
|
||||
//~| ERROR expected pattern, found `$`
|
||||
|
||||
let ${concat(abc, r#abc)}: () = ();
|
||||
//~^ ERROR `${concat(..)}` currently does not support raw identifiers
|
||||
//~^ ERROR expected identifier or string literal
|
||||
|
||||
let ${concat(r#abc, r#abc)}: () = ();
|
||||
//~^ ERROR `${concat(..)}` currently does not support raw identifiers
|
||||
//~^ ERROR expected identifier or string literal
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
@ -1,16 +1,16 @@
|
|||
error: `${concat(..)}` currently does not support raw identifiers
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/raw-identifiers.rs:28:22
|
||||
|
|
||||
LL | let ${concat(r#abc, abc)}: () = ();
|
||||
| ^^^^^
|
||||
|
||||
error: `${concat(..)}` currently does not support raw identifiers
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/raw-identifiers.rs:32:27
|
||||
|
|
||||
LL | let ${concat(abc, r#abc)}: () = ();
|
||||
| ^^^^^
|
||||
|
||||
error: `${concat(..)}` currently does not support raw identifiers
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/raw-identifiers.rs:35:22
|
||||
|
|
||||
LL | let ${concat(r#abc, r#abc)}: () = ();
|
||||
|
|
|
@ -11,9 +11,6 @@ macro_rules! wrong_concat_declarations {
|
|||
${concat(aaaa,)}
|
||||
//~^ ERROR expected identifier
|
||||
|
||||
${concat(aaaa, 1)}
|
||||
//~^ ERROR expected identifier
|
||||
|
||||
${concat(_, aaaa)}
|
||||
|
||||
${concat(aaaa aaaa)}
|
||||
|
@ -30,9 +27,6 @@ macro_rules! wrong_concat_declarations {
|
|||
|
||||
${concat($ex, aaaa,)}
|
||||
//~^ ERROR expected identifier
|
||||
|
||||
${concat($ex, aaaa, 123)}
|
||||
//~^ ERROR expected identifier
|
||||
};
|
||||
}
|
||||
|
||||
|
@ -43,8 +37,80 @@ macro_rules! dollar_sign_without_referenced_ident {
|
|||
};
|
||||
}
|
||||
|
||||
macro_rules! starting_number {
|
||||
($ident:ident) => {{
|
||||
let ${concat("1", $ident)}: () = ();
|
||||
//~^ ERROR `${concat(..)}` is not generating a valid identifier
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! starting_valid_unicode {
|
||||
($ident:ident) => {{
|
||||
let ${concat("Ý", $ident)}: () = ();
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! starting_invalid_unicode {
|
||||
($ident:ident) => {{
|
||||
let ${concat("\u{00BD}", $ident)}: () = ();
|
||||
//~^ ERROR `${concat(..)}` is not generating a valid identifier
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! ending_number {
|
||||
($ident:ident) => {{
|
||||
let ${concat($ident, "1")}: () = ();
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! ending_valid_unicode {
|
||||
($ident:ident) => {{
|
||||
let ${concat($ident, "Ý")}: () = ();
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! ending_invalid_unicode {
|
||||
($ident:ident) => {{
|
||||
let ${concat($ident, "\u{00BD}")}: () = ();
|
||||
//~^ ERROR `${concat(..)}` is not generating a valid identifier
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! empty {
|
||||
() => {{
|
||||
let ${concat("", "")}: () = ();
|
||||
//~^ ERROR `${concat(..)}` is not generating a valid identifier
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! unsupported_literals {
|
||||
($ident:ident) => {{
|
||||
let ${concat(_a, 'b')}: () = ();
|
||||
//~^ ERROR expected identifier or string literal
|
||||
//~| ERROR expected pattern
|
||||
let ${concat(_a, 1)}: () = ();
|
||||
//~^ ERROR expected identifier or string literal
|
||||
|
||||
let ${concat($ident, 'b')}: () = ();
|
||||
//~^ ERROR expected identifier or string literal
|
||||
let ${concat($ident, 1)}: () = ();
|
||||
//~^ ERROR expected identifier or string literal
|
||||
}};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
wrong_concat_declarations!(1);
|
||||
|
||||
dollar_sign_without_referenced_ident!(VAR);
|
||||
|
||||
starting_number!(_abc);
|
||||
starting_valid_unicode!(_abc);
|
||||
starting_invalid_unicode!(_abc);
|
||||
|
||||
ending_number!(_abc);
|
||||
ending_valid_unicode!(_abc);
|
||||
ending_invalid_unicode!(_abc);
|
||||
unsupported_literals!(_abc);
|
||||
|
||||
empty!();
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
error: expected identifier
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:5:10
|
||||
|
|
||||
LL | ${concat()}
|
||||
|
@ -10,59 +10,126 @@ error: `concat` must have at least two elements
|
|||
LL | ${concat(aaaa)}
|
||||
| ^^^^^^
|
||||
|
||||
error: expected identifier
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:11:10
|
||||
|
|
||||
LL | ${concat(aaaa,)}
|
||||
| ^^^^^^^^^^^^^^^
|
||||
|
||||
error: expected identifier, found `1`
|
||||
--> $DIR/syntax-errors.rs:14:24
|
||||
|
|
||||
LL | ${concat(aaaa, 1)}
|
||||
| ^ help: try removing `1`
|
||||
|
||||
error: expected comma
|
||||
--> $DIR/syntax-errors.rs:19:10
|
||||
--> $DIR/syntax-errors.rs:16:10
|
||||
|
|
||||
LL | ${concat(aaaa aaaa)}
|
||||
| ^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: `concat` must have at least two elements
|
||||
--> $DIR/syntax-errors.rs:22:11
|
||||
--> $DIR/syntax-errors.rs:19:11
|
||||
|
|
||||
LL | ${concat($ex)}
|
||||
| ^^^^^^
|
||||
|
||||
error: expected comma
|
||||
--> $DIR/syntax-errors.rs:28:10
|
||||
--> $DIR/syntax-errors.rs:25:10
|
||||
|
|
||||
LL | ${concat($ex, aaaa 123)}
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: expected identifier
|
||||
--> $DIR/syntax-errors.rs:31:10
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:28:10
|
||||
|
|
||||
LL | ${concat($ex, aaaa,)}
|
||||
| ^^^^^^^^^^^^^^^^^^^^
|
||||
|
||||
error: expected identifier, found `123`
|
||||
--> $DIR/syntax-errors.rs:34:29
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:88:26
|
||||
|
|
||||
LL | ${concat($ex, aaaa, 123)}
|
||||
| ^^^ help: try removing `123`
|
||||
LL | let ${concat(_a, 'b')}: () = ();
|
||||
| ^^^
|
||||
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:91:26
|
||||
|
|
||||
LL | let ${concat(_a, 1)}: () = ();
|
||||
| ^
|
||||
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:94:30
|
||||
|
|
||||
LL | let ${concat($ident, 'b')}: () = ();
|
||||
| ^^^
|
||||
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:96:30
|
||||
|
|
||||
LL | let ${concat($ident, 1)}: () = ();
|
||||
| ^
|
||||
|
||||
error: `${concat(..)}` currently only accepts identifiers or meta-variables as parameters
|
||||
--> $DIR/syntax-errors.rs:25:19
|
||||
--> $DIR/syntax-errors.rs:22:19
|
||||
|
|
||||
LL | ${concat($ex, aaaa)}
|
||||
| ^^
|
||||
|
||||
error: variable `foo` is not recognized in meta-variable expression
|
||||
--> $DIR/syntax-errors.rs:41:30
|
||||
--> $DIR/syntax-errors.rs:35:30
|
||||
|
|
||||
LL | const ${concat(FOO, $foo)}: i32 = 2;
|
||||
| ^^^
|
||||
|
||||
error: aborting due to 11 previous errors
|
||||
error: `${concat(..)}` is not generating a valid identifier
|
||||
--> $DIR/syntax-errors.rs:42:14
|
||||
|
|
||||
LL | let ${concat("1", $ident)}: () = ();
|
||||
| ^^^^^^^^^^^^^^^^^^^^^
|
||||
...
|
||||
LL | starting_number!(_abc);
|
||||
| ---------------------- in this macro invocation
|
||||
|
|
||||
= note: this error originates in the macro `starting_number` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: `${concat(..)}` is not generating a valid identifier
|
||||
--> $DIR/syntax-errors.rs:55:14
|
||||
|
|
||||
LL | let ${concat("\u{00BD}", $ident)}: () = ();
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
...
|
||||
LL | starting_invalid_unicode!(_abc);
|
||||
| ------------------------------- in this macro invocation
|
||||
|
|
||||
= note: this error originates in the macro `starting_invalid_unicode` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: `${concat(..)}` is not generating a valid identifier
|
||||
--> $DIR/syntax-errors.rs:74:14
|
||||
|
|
||||
LL | let ${concat($ident, "\u{00BD}")}: () = ();
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
...
|
||||
LL | ending_invalid_unicode!(_abc);
|
||||
| ----------------------------- in this macro invocation
|
||||
|
|
||||
= note: this error originates in the macro `ending_invalid_unicode` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: expected pattern, found `$`
|
||||
--> $DIR/syntax-errors.rs:88:13
|
||||
|
|
||||
LL | let ${concat(_a, 'b')}: () = ();
|
||||
| ^ expected pattern
|
||||
...
|
||||
LL | unsupported_literals!(_abc);
|
||||
| --------------------------- in this macro invocation
|
||||
|
|
||||
= note: this error originates in the macro `unsupported_literals` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: `${concat(..)}` is not generating a valid identifier
|
||||
--> $DIR/syntax-errors.rs:81:14
|
||||
|
|
||||
LL | let ${concat("", "")}: () = ();
|
||||
| ^^^^^^^^^^^^^^^^
|
||||
...
|
||||
LL | empty!();
|
||||
| -------- in this macro invocation
|
||||
|
|
||||
= note: this error originates in the macro `empty` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: aborting due to 18 previous errors
|
||||
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
//@ run-pass
|
||||
|
||||
#![feature(macro_metavar_expr_concat)]
|
||||
|
||||
macro_rules! turn_to_page {
|
||||
($ident:ident) => {
|
||||
const ${concat("Ḧ", $ident)}: i32 = 394;
|
||||
};
|
||||
}
|
||||
|
||||
fn main() {
|
||||
turn_to_page!(P);
|
||||
assert_eq!(ḦP, 394);
|
||||
}
|
|
@ -190,7 +190,7 @@ error: unrecognized meta-variable expression
|
|||
LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } };
|
||||
| ^^^^^^^^^^^^^^ help: supported expressions are count, ignore, index and len
|
||||
|
||||
error: expected identifier
|
||||
error: expected identifier or string literal
|
||||
--> $DIR/syntax-errors.rs:118:33
|
||||
|
|
||||
LL | ( $( $i:ident ),* ) => { ${ {} } };
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
warning: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:8:18
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:13:18
|
||||
|
|
||||
LL | unsafe { mem::zeroed() }
|
||||
| ^^^^^^^^^^^^^
|
||||
|
@ -10,7 +10,7 @@ LL | unsafe { mem::zeroed() }
|
|||
= note: `#[warn(never_type_fallback_flowing_into_unsafe)]` on by default
|
||||
|
||||
warning: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:23:13
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:30:13
|
||||
|
|
||||
LL | core::mem::transmute(Zst)
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
@ -20,7 +20,7 @@ LL | core::mem::transmute(Zst)
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this union access
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:39:18
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:47:18
|
||||
|
|
||||
LL | unsafe { Union { a: () }.b }
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
|
@ -30,7 +30,7 @@ LL | unsafe { Union { a: () }.b }
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this raw pointer dereference
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:49:18
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:58:18
|
||||
|
|
||||
LL | unsafe { *ptr::from_ref(&()).cast() }
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
@ -40,7 +40,7 @@ LL | unsafe { *ptr::from_ref(&()).cast() }
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:67:18
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:79:18
|
||||
|
|
||||
LL | unsafe { internally_create(x) }
|
||||
| ^^^^^^^^^^^^^^^^^^^^
|
||||
|
@ -50,7 +50,7 @@ LL | unsafe { internally_create(x) }
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:83:18
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:97:18
|
||||
|
|
||||
LL | unsafe { zeroed() }
|
||||
| ^^^^^^^^
|
||||
|
@ -60,7 +60,7 @@ LL | unsafe { zeroed() }
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:79:22
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:92:22
|
||||
|
|
||||
LL | let zeroed = mem::zeroed;
|
||||
| ^^^^^^^^^^^
|
||||
|
@ -70,7 +70,7 @@ LL | let zeroed = mem::zeroed;
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:98:17
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:115:17
|
||||
|
|
||||
LL | let f = internally_create;
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
|
@ -80,7 +80,7 @@ LL | let f = internally_create;
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this call to an `unsafe` method
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:122:13
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:140:13
|
||||
|
|
||||
LL | S(marker::PhantomData).create_out_of_thin_air()
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
@ -90,7 +90,7 @@ LL | S(marker::PhantomData).create_out_of_thin_air()
|
|||
= help: specify the type explicitly
|
||||
|
||||
warning: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:139:19
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:158:19
|
||||
|
|
||||
LL | match send_message::<_ /* ?0 */>() {
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
@ -0,0 +1,116 @@
|
|||
error: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:13:18
|
||||
|
|
||||
LL | unsafe { mem::zeroed() }
|
||||
| ^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
= note: `#[deny(never_type_fallback_flowing_into_unsafe)]` on by default
|
||||
|
||||
error: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:30:13
|
||||
|
|
||||
LL | core::mem::transmute(Zst)
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this union access
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:47:18
|
||||
|
|
||||
LL | unsafe { Union { a: () }.b }
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this raw pointer dereference
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:58:18
|
||||
|
|
||||
LL | unsafe { *ptr::from_ref(&()).cast() }
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:79:18
|
||||
|
|
||||
LL | unsafe { internally_create(x) }
|
||||
| ^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:97:18
|
||||
|
|
||||
LL | unsafe { zeroed() }
|
||||
| ^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:92:22
|
||||
|
|
||||
LL | let zeroed = mem::zeroed;
|
||||
| ^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:115:17
|
||||
|
|
||||
LL | let f = internally_create;
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this call to an `unsafe` method
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:140:13
|
||||
|
|
||||
LL | S(marker::PhantomData).create_out_of_thin_air()
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
|
||||
error: never type fallback affects this call to an `unsafe` function
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:158:19
|
||||
|
|
||||
LL | match send_message::<_ /* ?0 */>() {
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
...
|
||||
LL | msg_send!();
|
||||
| ----------- in this macro invocation
|
||||
|
|
||||
= warning: this will change its meaning in a future release!
|
||||
= note: for more information, see issue #123748 <https://github.com/rust-lang/rust/issues/123748>
|
||||
= help: specify the type explicitly
|
||||
= note: this error originates in the macro `msg_send` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
warning: the type `!` does not permit zero-initialization
|
||||
--> $DIR/lint-never-type-fallback-flowing-into-unsafe.rs:13:18
|
||||
|
|
||||
LL | unsafe { mem::zeroed() }
|
||||
| ^^^^^^^^^^^^^ this code causes undefined behavior when executed
|
||||
|
|
||||
= note: the `!` type has no valid value
|
||||
= note: `#[warn(invalid_value)]` on by default
|
||||
|
||||
error: aborting due to 10 previous errors; 1 warning emitted
|
||||
|
|
@ -1,4 +1,9 @@
|
|||
//@ check-pass
|
||||
//@ revisions: e2015 e2024
|
||||
//@[e2015] check-pass
|
||||
//@[e2024] check-fail
|
||||
//@[e2024] edition:2024
|
||||
//@[e2024] compile-flags: -Zunstable-options
|
||||
|
||||
use std::{marker, mem, ptr};
|
||||
|
||||
fn main() {}
|
||||
|
@ -6,8 +11,10 @@ fn main() {}
|
|||
fn _zero() {
|
||||
if false {
|
||||
unsafe { mem::zeroed() }
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
//[e2024]~| warning: the type `!` does not permit zero-initialization
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
|
@ -21,7 +28,8 @@ fn _trans() {
|
|||
unsafe {
|
||||
struct Zst;
|
||||
core::mem::transmute(Zst)
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
}
|
||||
} else {
|
||||
|
@ -37,7 +45,8 @@ fn _union() {
|
|||
}
|
||||
|
||||
unsafe { Union { a: () }.b }
|
||||
//~^ warn: never type fallback affects this union access
|
||||
//[e2015]~^ warn: never type fallback affects this union access
|
||||
//[e2024]~^^ error: never type fallback affects this union access
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
} else {
|
||||
return;
|
||||
|
@ -47,7 +56,8 @@ fn _union() {
|
|||
fn _deref() {
|
||||
if false {
|
||||
unsafe { *ptr::from_ref(&()).cast() }
|
||||
//~^ warn: never type fallback affects this raw pointer dereference
|
||||
//[e2015]~^ warn: never type fallback affects this raw pointer dereference
|
||||
//[e2024]~^^ error: never type fallback affects this raw pointer dereference
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
} else {
|
||||
return;
|
||||
|
@ -57,7 +67,9 @@ fn _deref() {
|
|||
fn _only_generics() {
|
||||
if false {
|
||||
unsafe fn internally_create<T>(_: Option<T>) {
|
||||
let _ = mem::zeroed::<T>();
|
||||
unsafe {
|
||||
let _ = mem::zeroed::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
// We need the option (and unwrap later) to call a function in a way,
|
||||
|
@ -65,7 +77,8 @@ fn _only_generics() {
|
|||
let x = None;
|
||||
|
||||
unsafe { internally_create(x) }
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
|
||||
x.unwrap()
|
||||
|
@ -77,11 +90,13 @@ fn _only_generics() {
|
|||
fn _stored_function() {
|
||||
if false {
|
||||
let zeroed = mem::zeroed;
|
||||
//~^ warn: never type fallback affects this `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
|
||||
unsafe { zeroed() }
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
} else {
|
||||
return;
|
||||
|
@ -91,12 +106,15 @@ fn _stored_function() {
|
|||
fn _only_generics_stored_function() {
|
||||
if false {
|
||||
unsafe fn internally_create<T>(_: Option<T>) {
|
||||
let _ = mem::zeroed::<T>();
|
||||
unsafe {
|
||||
let _ = mem::zeroed::<T>();
|
||||
}
|
||||
}
|
||||
|
||||
let x = None;
|
||||
let f = internally_create;
|
||||
//~^ warn: never type fallback affects this `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
|
||||
unsafe { f(x) }
|
||||
|
@ -120,7 +138,8 @@ fn _method() {
|
|||
if false {
|
||||
unsafe {
|
||||
S(marker::PhantomData).create_out_of_thin_air()
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` method
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` method
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` method
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
}
|
||||
} else {
|
||||
|
@ -137,7 +156,8 @@ fn _objc() {
|
|||
macro_rules! msg_send {
|
||||
() => {
|
||||
match send_message::<_ /* ?0 */>() {
|
||||
//~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2015]~^ warn: never type fallback affects this call to an `unsafe` function
|
||||
//[e2024]~^^ error: never type fallback affects this call to an `unsafe` function
|
||||
//~| warn: this will change its meaning in a future release!
|
||||
Ok(x) => x,
|
||||
Err(_) => loop {},
|
||||
|
|
|
@ -2,7 +2,7 @@ error[E0425]: cannot find value `field` in this scope
|
|||
--> $DIR/field-and-method-in-self-not-available-in-assoc-fn.rs:11:9
|
||||
|
|
||||
LL | field: u32,
|
||||
| ---------- a field by that name exists in `Self`
|
||||
| ----- a field by that name exists in `Self`
|
||||
...
|
||||
LL | fn field(&self) -> u32 {
|
||||
| ----- a method by that name is available on `Self` here
|
||||
|
@ -14,7 +14,7 @@ error[E0425]: cannot find value `field` in this scope
|
|||
--> $DIR/field-and-method-in-self-not-available-in-assoc-fn.rs:12:15
|
||||
|
|
||||
LL | field: u32,
|
||||
| ---------- a field by that name exists in `Self`
|
||||
| ----- a field by that name exists in `Self`
|
||||
...
|
||||
LL | fn field(&self) -> u32 {
|
||||
| ----- a method by that name is available on `Self` here
|
||||
|
|
|
@ -2,7 +2,7 @@ error[E0425]: cannot find value `whiskers` in this scope
|
|||
--> $DIR/issue-2356.rs:39:5
|
||||
|
|
||||
LL | whiskers: isize,
|
||||
| --------------- a field by that name exists in `Self`
|
||||
| -------- a field by that name exists in `Self`
|
||||
...
|
||||
LL | whiskers -= other;
|
||||
| ^^^^^^^^
|
||||
|
@ -35,7 +35,7 @@ error[E0425]: cannot find value `whiskers` in this scope
|
|||
--> $DIR/issue-2356.rs:84:5
|
||||
|
|
||||
LL | whiskers: isize,
|
||||
| --------------- a field by that name exists in `Self`
|
||||
| -------- a field by that name exists in `Self`
|
||||
...
|
||||
LL | whiskers = 4;
|
||||
| ^^^^^^^^
|
||||
|
|
|
@ -2,7 +2,7 @@ error[E0425]: cannot find value `banana` in this scope
|
|||
--> $DIR/issue-60057.rs:8:21
|
||||
|
|
||||
LL | banana: u8,
|
||||
| ---------- a field by that name exists in `Self`
|
||||
| ------ a field by that name exists in `Self`
|
||||
...
|
||||
LL | banana: banana
|
||||
| ^^^^^^
|
||||
|
|
|
@ -2,7 +2,7 @@ error[E0425]: cannot find value `config` in this scope
|
|||
--> $DIR/typo-suggestion-for-variable-with-name-similar-to-struct-field.rs:7:16
|
||||
|
|
||||
LL | config: String,
|
||||
| -------------- a field by that name exists in `Self`
|
||||
| ------ a field by that name exists in `Self`
|
||||
...
|
||||
LL | Self { config }
|
||||
| ^^^^^^ help: a local variable with a similar name exists: `cofig`
|
||||
|
@ -11,7 +11,7 @@ error[E0425]: cannot find value `config` in this scope
|
|||
--> $DIR/typo-suggestion-for-variable-with-name-similar-to-struct-field.rs:11:20
|
||||
|
|
||||
LL | config: String,
|
||||
| -------------- a field by that name exists in `Self`
|
||||
| ------ a field by that name exists in `Self`
|
||||
...
|
||||
LL | println!("{config}");
|
||||
| ^^^^^^ help: a local variable with a similar name exists: `cofig`
|
||||
|
|
|
@ -2,7 +2,7 @@ error[E0425]: cannot find value `cx` in this scope
|
|||
--> $DIR/unresolved_static_type_field.rs:9:11
|
||||
|
|
||||
LL | cx: bool,
|
||||
| -------- a field by that name exists in `Self`
|
||||
| -- a field by that name exists in `Self`
|
||||
...
|
||||
LL | f(cx);
|
||||
| ^^
|
||||
|
|
|
@ -1,12 +1,16 @@
|
|||
//@ known-bug: #110395
|
||||
//@ failure-status: 101
|
||||
//@ normalize-stderr-test ".*note: .*\n\n" -> ""
|
||||
//@ normalize-stderr-test "thread 'rustc' panicked.*:\n.*\n" -> ""
|
||||
//@ rustc-env:RUST_BACKTRACE=0
|
||||
// FIXME(effects) check-pass
|
||||
// FIXME(effects) fix intrinsics const parameter counting
|
||||
//@ compile-flags: -Znext-solver
|
||||
|
||||
#![crate_type = "lib"]
|
||||
#![feature(no_core, lang_items, unboxed_closures, auto_traits, intrinsics, rustc_attrs, staged_api)]
|
||||
#![feature(fundamental)]
|
||||
#![feature(fundamental, marker_trait_attr)]
|
||||
#![feature(const_trait_impl, effects, const_mut_refs)]
|
||||
#![allow(internal_features)]
|
||||
#![allow(internal_features, incomplete_features)]
|
||||
#![no_std]
|
||||
#![no_core]
|
||||
#![stable(feature = "minicore", since = "1.0.0")]
|
||||
|
@ -532,3 +536,35 @@ fn test_const_eval_select() {
|
|||
|
||||
const_eval_select((), const_fn, rt_fn);
|
||||
}
|
||||
|
||||
mod effects {
|
||||
use super::Sized;
|
||||
|
||||
#[lang = "EffectsNoRuntime"]
|
||||
pub struct NoRuntime;
|
||||
#[lang = "EffectsMaybe"]
|
||||
pub struct Maybe;
|
||||
#[lang = "EffectsRuntime"]
|
||||
pub struct Runtime;
|
||||
|
||||
#[lang = "EffectsCompat"]
|
||||
pub trait Compat<#[rustc_runtime] const RUNTIME: bool> {}
|
||||
|
||||
impl Compat<false> for NoRuntime {}
|
||||
impl Compat<true> for Runtime {}
|
||||
impl<#[rustc_runtime] const RUNTIME: bool> Compat<RUNTIME> for Maybe {}
|
||||
|
||||
#[lang = "EffectsTyCompat"]
|
||||
#[marker]
|
||||
pub trait TyCompat<T: ?Sized> {}
|
||||
|
||||
impl<T: ?Sized> TyCompat<T> for T {}
|
||||
impl<T: ?Sized> TyCompat<T> for Maybe {}
|
||||
impl<T: ?Sized> TyCompat<Maybe> for T {}
|
||||
|
||||
#[lang = "EffectsIntersection"]
|
||||
pub trait Intersection {
|
||||
#[lang = "EffectsIntersectionOutput"]
|
||||
type Output: ?Sized;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,17 +1,13 @@
|
|||
warning: the feature `effects` is incomplete and may not be safe to use and/or cause compiler crashes
|
||||
--> $DIR/minicore.rs:8:30
|
||||
|
|
||||
LL | #![feature(const_trait_impl, effects, const_mut_refs)]
|
||||
| ^^^^^^^
|
||||
|
|
||||
= note: see issue #102090 <https://github.com/rust-lang/rust/issues/102090> for more information
|
||||
= note: `#[warn(incomplete_features)]` on by default
|
||||
error: the compiler unexpectedly panicked. this is a bug.
|
||||
|
||||
error: requires `EffectsCompat` lang_item
|
||||
--> $DIR/minicore.rs:455:9
|
||||
|
|
||||
LL | impl<T: Clone> Clone for RefCell<T> {
|
||||
| ^^^^^
|
||||
query stack during panic:
|
||||
#0 [check_well_formed] checking that `<impl at $DIR/minicore.rs:459:1: 459:36>` is well-formed
|
||||
#1 [check_mod_type_wf] checking that types are well-formed in top-level module
|
||||
end of query stack
|
||||
|
||||
error: aborting due to 1 previous error; 1 warning emitted
|
||||
error: the compiler unexpectedly panicked. this is a bug.
|
||||
|
||||
query stack during panic:
|
||||
#0 [check_well_formed] checking that `drop` is well-formed
|
||||
#1 [check_mod_type_wf] checking that types are well-formed in top-level module
|
||||
end of query stack
|
||||
|
|
Loading…
Reference in New Issue