Accessing the `DefId` of a Trait Implementation

Hi all,

Suppose I define my own type and implement a trait for it e.g.

pub struct MyType { ... } 

impl Iterator for MyType { 
  type Item = MyItem;
  fn next(...) -> MyItem { ... }      // can we get this DefId at the usage site?
} 

Now suppose I have some client code of the form

let my_typ_inst = MyType::new(...):
let foo = my_typ_inst.next();

The MIR for the above call looks something like

<MyType as std::iter::Iterator>::next(...)

I have two questions:

  1. Is there some way to get the DefId for the MyType implementation of next() ?

  2. Is there some way to recover the fact that the signature of next at the above site is fn (&Self) -> Option<MyItem> ?

Should I be looking around here for example?

Thanks in advance!

What you want is some sort of normalize to resolve the projection; perhaps rustc_trait_selection::traits::normalize? The raw query is on tcx but you're supposed to call it through a wrapper normalize rather than directly and I can't quickly find the one you probably want in rustdoc.

1 Like

Thanks @CAD97 ! Digging around I tried to use the functions here

(because the normalize you linked to requires an InferCtx among other things, which I don't know how to get a hold of yet.)

However, I was surprised that all those functions (in normalize_erasing_regions) have no effect. In particular, I am puzzled by this:

println!("has_projections `{exp_ty:?}` = {:?}", exp_ty.has_projections());

yields the following output

has_projections `for<'r> fn(&'r mut range::Rng) -> std::option::Option<<range::Rng as std::iter::Iterator>::Item> {<range::Rng as std::iter::Iterator>::next}` = false

all the rest of the code in normalize_erasing_regions skips normalization when the above is false. Is the idea that the normalization doesn't happen for a whole function signature but must be done separately on each component?

Thanks in advance for any pointers!

I'm not super familiar with this part of rustc, but yeah, you'll have the most luck if you can drill down to the part of the type with the projection you care about and then normalize/resolve that.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.