Accessing the `FnSig` of a `DefId`

Hi all,

(My apologies if this is the wrong place to ask this question!)

We are trying to build a rustc plugin -- and am having a bit of trouble trying to extract the FnSig (type) of a DefId. When you have a LocalDefId (which, as I understand it, means a DefId defined in the current crate, you can simply do something like

let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
let hir_fn_sig = tcx.hir().fn_sig_by_hir_id(hir_id).unwrap();

However, I'd like to do the same thing but for identifiers defined in external crates (e.g. std::process::exit to pick a random example).

Can anyone give some pointers? Maybe there is some API to

  • Convert a DefId to a Node or HirId and then extract the FnSig ?

Or some other route? [Or do we only have Node and HirId for LocalDefId and should I be looking elsewhere entirely?]

Any pointers will be most welcome, thanks in advance!

  • Ranjit.
1 Like

You can take a look at

1 Like

Thanks! That moves things along quite a bit, however I am next stuck on the following.

  • For the LocalDefId,we get the rustc_hir::hir::FnSig but
  • For the DefId (following the code above) we get a rustc_middle::ty::FnSig

The two are slightly different, e.g. the constituent types (inputs and outputs) have respectively

  • rustc_hir::hir::Ty vs
  • rustc_middle::ty::Ty

Do you know if it is possible to convert the middle versions to the hir versions (or vice versa)?

No, going from hir::Ty -> ty::Ty only happens during hir lowering. The other way around is inpossible. You can convert a LocalDefId to a DefId though and then use the linked code.

1 Like

Usually ty::Tys are more useful to perform analyses on, since they are the semantic rather than syntactic representation of a type. The main limitation of ty::Tys I know of is that type aliases are fully expanded and aren't represented.

You can't get HIR from external crates because it's not stored in the crate metadata files.

1 Like

TyCtxt::fn_sig() is probably the function you want.

1 Like

I believe tcx.fn_sig doesn't work for closures and generators. The code I linked does work for them.

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