rust-lang / cargo

The Rust package manager
https://doc.rust-lang.org/cargo
Apache License 2.0
12.85k stars 2.43k forks source link

Cargo list trait implementors #14852

Open walksanatora opened 1 week ago

walksanatora commented 1 week ago

Problem

I am writing a program and would like a way to see every struct that implements a trait (eg: serde::Serialize) I know that at somepoint during compilation the full type information is avaliable because rust is able to give output like

     = help: the following other types implement trait `_::_serde::Serialize`:
               &'a T
               &'a mut T
               ()
               (T,)
               (T0, T1)
               (T0, T1, T2)
               (T0, T1, T2, T3)
               (T0, T1, T2, T3, T4)
             and 150 others

when using types that dont implement a trait.

Proposed Solution

if I had to guess this would probally be best relegated to some kind of nightly -Z flag probally smth like -Z dump-impls probally producing either a debug output dump of the crates. or just a simple tabulated tree of crates and traits and impls

Notes

No response

walksanatora commented 1 week ago

this may also work as a sub-command of cargo report eg: cargo report trait-implementations

epage commented 1 week ago

Another way to consider this is that cargo doc is able to collect this information. On top of that, there is experimental json output for it. Someone could experiment with specific queries or a general purpose set of queries for types and traits based on that. This would likely be the best way forward for experimenting and evaluating the idea before inclusion into Cargo in some form.

walksanatora commented 1 week ago

odd is that when I ran cargo +nightly rustdoc -Z unstable-options --output-format=json it only included the trait implementation information for my crate. (as the unstable option of output-format is not on the base doc command yet)

weihanglo commented 1 week ago

Guess it is because cargo rustdoc passes those trailing arguments to only one crate selected in CLI, which by default is your primary package.

charmitro commented 3 days ago

I'm also interested in this feature.

I've been thinking about a potential cargo trait-query subcommand.

Maybe use rustdoc experimental JSON output to build a queryable index of trait implementations?