Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions compiler/rustc_ast/src/ast.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3921,6 +3921,12 @@ pub struct Delegation {
pub from_glob: bool,
}

impl Delegation {
pub fn last_segment_span(&self) -> Span {
self.path.segments.last().unwrap().ident.span
}
}

#[derive(Clone, Encodable, Decodable, Debug, Walkable)]
pub enum DelegationSuffixes {
List(ThinVec<(Ident, Option<Ident>)>),
Expand Down
174 changes: 96 additions & 78 deletions compiler/rustc_ast_lowering/src/delegation.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -44,22 +44,20 @@ use hir::{BodyId, HirId};
use rustc_abi::ExternAbi;
use rustc_ast as ast;
use rustc_ast::*;
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::ErrorGuaranteed;
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
use rustc_hir::attrs::{AttributeKind, InlineAttr};
use rustc_hir::def_id::DefId;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::{self as hir, FnDeclFlags};
use rustc_middle::span_bug;
use rustc_middle::ty::Asyncness;
use rustc_middle::ty::{Asyncness, TyCtxt};
use rustc_span::symbol::kw;
use rustc_span::{Ident, Span, Symbol};
use smallvec::SmallVec;
use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol};

use crate::delegation::generics::{GenericsGenerationResult, GenericsGenerationResults};
use crate::errors::{CycleInDelegationSignatureResolution, UnresolvedDelegationCallee};
use crate::{
AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode,
ResolverAstLoweringExt,
ResolverAstLoweringExt, index_crate,
};

mod generics;
Expand DownExpand Up@@ -105,6 +103,66 @@ static ATTRS_ADDITIONS: &[AttrAdditionInfo] = &[
},
];

pub(crate) fn delegations_resolutions(
tcx: TyCtxt<'_>,
_: (),
) -> FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
let krate = tcx.hir_crate(());

let (resolver, ast_crate) = &*krate.delayed_resolver.borrow();

// FIXME!!!(fn_delegation): make ast index lifetime same as resolver,
// as it is too bad to reindex whole crate on each delegation lowering.
let ast_index = index_crate(resolver, ast_crate);

let mut result = FxIndexMap::<LocalDefId, Result<DefId, ErrorGuaranteed>>::default();

for &def_id in &krate.delayed_ids {
let delegation = ast_index[def_id].delegation().expect("processing delegations");
let span = delegation.last_segment_span();

if let Some(info) = resolver.delegation_info(def_id) {
let res = info.resolution_id.map(|id| check_for_cycles(tcx, id, span).map(|_| id));
result.insert(def_id, res.flatten());
} else {
tcx.dcx().span_delayed_bug(
span,
format!("delegation resolution record was not found for {def_id:?}"),
);
}
}

result
}

fn check_for_cycles(tcx: TyCtxt<'_>, mut def_id: DefId, span: Span) -> Result<(), ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();

let (resolver, _) = &*tcx.hir_crate(()).delayed_resolver.borrow();

loop {
visited.insert(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(info) = resolver.delegation_info(local_id)
&& let Ok(id) = info.resolution_id
{
def_id = id;
if visited.contains(&def_id) {
return Err(match visited.len() {
1 => tcx.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => tcx.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(());
}
}
}

impl<'hir> LoweringContext<'_, 'hir> {
fn is_method(&self, def_id: DefId, span: Span) -> bool {
match self.tcx.def_kind(def_id) {
Expand All@@ -119,13 +177,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
delegation: &Delegation,
item_id: NodeId,
) -> DelegationResults<'hir> {
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
let span = self.lower_span(delegation.last_segment_span());

// Delegation can be unresolved in illegal places such as function bodies in extern blocks (see #151356)
let sig_id = if let Some(delegation_info) = self.resolver.delegation_info(self.owner.def_id)
{
self.get_sig_id(delegation_info.resolution_id, span)
} else {
let sig_id = self.tcx.delegations_resolutions(()).get(&self.owner.def_id).copied();

// Delegation can be missing from the `delegations_resolutions` table
// in illegal places such as function bodies in extern blocks (see #151356).
let Some(Ok(sig_id)) = sig_id else {
self.dcx().span_delayed_bug(
span,
format!("LoweringContext: the delegation {:?} is unresolved", item_id),
Expand All@@ -134,49 +192,39 @@ impl<'hir> LoweringContext<'_, 'hir> {
return self.generate_delegation_error(span, delegation);
};

match sig_id {
Ok(sig_id) => {
self.add_attrs_if_needed(span, sig_id);
self.add_attrs_if_needed(span, sig_id);

let is_method = self.is_method(sig_id, span);
let is_method = self.is_method(sig_id, span);

let (param_count, c_variadic) = self.param_count(sig_id);
let (param_count, c_variadic) = self.param_count(sig_id);

let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);
let mut generics = self.uplift_delegation_generics(delegation, sig_id, is_method);

let (body_id, call_expr_id) = self.lower_delegation_body(
delegation,
is_method,
param_count,
&mut generics,
span,
);
let (body_id, call_expr_id) =
self.lower_delegation_body(delegation, is_method, param_count, &mut generics, span);

let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);
let decl = self.lower_delegation_decl(
sig_id,
param_count,
c_variadic,
span,
&generics,
delegation.id,
call_expr_id,
);

let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);
let sig = self.lower_delegation_sig(sig_id, decl, span);
let ident = self.lower_ident(delegation.ident);

let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});
let generics = self.arena.alloc(hir::Generics {
has_where_clause_predicates: false,
params: self.arena.alloc_from_iter(generics.all_params()),
predicates: self.arena.alloc_from_iter(generics.all_predicates()),
span,
where_clause_span: span,
});

DelegationResults { body_id, sig, ident, generics }
}
Err(_) => self.generate_delegation_error(span, delegation),
}
DelegationResults { body_id, sig, ident, generics }
}

fn add_attrs_if_needed(&mut self, span: Span, sig_id: DefId) {
Expand DownExpand Up@@ -230,36 +278,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
.collect::<Vec<_>>()
}

fn get_sig_id(&self, mut def_id: DefId, span: Span) -> Result<DefId, ErrorGuaranteed> {
let mut visited: FxHashSet<DefId> = Default::default();
let mut path: SmallVec<[DefId; 1]> = Default::default();

loop {
visited.insert(def_id);

path.push(def_id);

// If def_id is in local crate and it corresponds to another delegation
// it means that we refer to another delegation as a callee, so in order to obtain
// a signature DefId we obtain NodeId of the callee delegation and try to get signature from it.
if let Some(local_id) = def_id.as_local()
&& let Some(delegation_info) = self.resolver.delegation_info(local_id)
{
def_id = delegation_info.resolution_id;
if visited.contains(&def_id) {
// We encountered a cycle in the resolution, or delegation callee refers to non-existent
// entity, in this case emit an error.
return Err(match visited.len() {
1 => self.dcx().emit_err(UnresolvedDelegationCallee { span }),
_ => self.dcx().emit_err(CycleInDelegationSignatureResolution { span }),
});
}
} else {
return Ok(path[0]);
}
}
}

fn get_resolution_id(&self, node_id: NodeId) -> Option<DefId> {
self.get_partial_res(node_id).and_then(|r| r.expect_full_res().opt_def_id())
}
Expand Down
33 changes: 24 additions & 9 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -60,6 +60,7 @@ use rustc_hir::{
use rustc_index::{Idx, IndexSlice, IndexVec};
use rustc_macros::extension;
use rustc_middle::hir::{self as mid_hir};
use rustc_middle::queries::Providers;
use rustc_middle::span_bug;
use rustc_middle::ty::{DelegationInfo, PerOwnerResolverData, ResolverAstLowering, TyCtxt};
use rustc_session::errors::add_feature_diagnostics;
Expand DownExpand Up@@ -91,6 +92,12 @@ mod pat;
mod path;
pub mod stability;

pub fn provide(providers: &mut Providers) {
providers.hir_crate = lower_to_hir;
providers.lower_delayed_owner = lower_delayed_owner;
providers.delegations_resolutions = delegation::delegations_resolutions;
}

struct LoweringContext<'a, 'hir> {
tcx: TyCtxt<'hir>,
resolver: &'a ResolverAstLowering<'hir>,
Expand DownExpand Up@@ -433,6 +440,16 @@ enum AstOwner<'a> {
ForeignItem(&'a ast::ForeignItem),
}

impl AstOwner<'_> {
fn delegation(&self) -> Option<&ast::Delegation> {
match self {
AstOwner::Item(Item { kind: ItemKind::Delegation(d), .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation(d), .. }, _) => Some(d),
_ => None,
}
}
}

#[derive(Copy, Clone, Debug)]
enum TryBlockScope {
/// There isn't a `try` block, so a `?` will use `return`.
Expand DownExpand Up@@ -512,7 +529,7 @@ fn compute_hir_hash(
})
}

pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
// Queries that borrow `resolver_for_lowering`.
tcx.ensure_done().output_filenames(());
tcx.ensure_done().early_lint_checks(());
Expand All@@ -536,13 +553,11 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
let mut delayed_ids: FxIndexSet<LocalDefId> = Default::default();

for def_id in ast_index.indices() {
match &ast_index[def_id] {
AstOwner::Item(Item { kind: ItemKind::Delegation { .. }, .. })
| AstOwner::AssocItem(Item { kind: AssocItemKind::Delegation { .. }, .. }, _) => {
delayed_ids.insert(def_id);
}
_ => lowerer.lower_node(def_id),
};
if ast_index[def_id].delegation().is_some() {
delayed_ids.insert(def_id);
} else {
lowerer.lower_node(def_id);
}
}

// Don't hash unless necessary, because it's expensive.
Expand All@@ -554,7 +569,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> mid_hir::Crate<'_> {
}

/// Lowers an AST owner corresponding to `def_id`, now only delegations are lowered this way.
pub fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
fn lower_delayed_owner(tcx: TyCtxt<'_>, def_id: LocalDefId) {
let krate = tcx.hir_crate(());

let (resolver, krate) = &*krate.delayed_resolver.borrow();
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_interface/src/passes.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -877,8 +877,6 @@ pub fn write_interface<'tcx>(tcx: TyCtxt<'tcx>) {
pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
let providers = &mut Providers::default();
providers.queries.analysis = analysis;
providers.queries.hir_crate = rustc_ast_lowering::lower_to_hir;
providers.queries.lower_delayed_owner = rustc_ast_lowering::lower_delayed_owner;
// `hir_delayed_owner` is fed during `lower_delayed_owner`, by default it returns phantom,
// as if this query was not fed it means that `MaybeOwner` does not exist for provided LocalDefId.
providers.queries.hir_delayed_owner = |_, _| MaybeOwner::Phantom;
Expand All@@ -887,6 +885,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
providers.queries.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.queries.early_lint_checks = early_lint_checks;
providers.queries.env_var_os = env_var_os;
rustc_ast_lowering::provide(&mut providers.queries);
limits::provide(&mut providers.queries);
proc_macro_decls::provide(&mut providers.queries);
rustc_expand::provide(&mut providers.queries);
Expand Down
6 changes: 6 additions & 0 deletions compiler/rustc_middle/src/queries.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2069,6 +2069,12 @@ rustc_queries! {
desc { "getting delegation user-specified args" }
}

query delegations_resolutions(_: ()) -> &'tcx FxIndexMap<LocalDefId, Result<DefId, ErrorGuaranteed>> {
arena_cache
eval_always
desc { "getting delegations resolutions" }
}

/// Does lifetime resolution on items. Importantly, we can't resolve
/// lifetimes directly on things like trait methods, because of trait params.
/// See `rustc_resolve::late::lifetimes` for details.
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -270,7 +270,7 @@ pub struct DelegationInfo {
/// Refers to the next element in a delegation resolution chain.
/// Usually points to the final resolution, as most "chains" are just
/// one step to a trait or an impl.
pub resolution_id: DefId,
pub resolution_id: Result<DefId, ErrorGuaranteed>,
}

#[derive(Clone, Copy, Debug, StableHash)]
Expand Down
20 changes: 10 additions & 10 deletions compiler/rustc_resolve/src/late.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3899,24 +3899,24 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_path(&delegation.path);
});

let resolution_id = if is_in_trait_impl { item_id } else { delegation.id };
let resolution_node_id = if is_in_trait_impl { item_id } else { delegation.id };
let def_id = self
.r
.partial_res_map
.get(&resolution_id)
.get(&resolution_node_id)
.and_then(|r| r.expect_full_res().opt_def_id());
if let Some(resolution_id) = def_id {
self.r
.delegation_infos
.insert(self.r.current_owner.def_id, DelegationInfo { resolution_id });
} else {

let resolution_id = def_id.ok_or_else(|| {
self.r.tcx.dcx().span_delayed_bug(
delegation.path.span,
format!(
"LoweringContext: couldn't resolve node {resolution_id:?} in delegation item",
"LateResolutionVisitor: couldn't resolve node {resolution_node_id:?} in delegation item",
),
);
};
)
});

let info = DelegationInfo { resolution_id };
self.r.delegation_infos.insert(self.r.current_owner.def_id, info);

let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
Expand Down
Loading