Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to introspect all available methods and members of a Rust type?

Is there a way to print out a complete list of available members of a type or instance in Rust?

For example:

  • In Python, I can use print(dir(object))
  • In C, Clang has a Python API that can parse C code and introspect it.

Being unfamiliar with Rust tools, I'm interested to know if there is some way to do this, either at run-time or compile-time, either with compiler features (macros for example), or using external tools.

This question is intentionally broad because the exact method isn't important. It is common in any language to want to find all of a variable's methods/functions. Not knowing Rust well, I'm not limiting the question to specific methods for discovery.

The reason I don't define the exact method is that I assume IDEs will need this information, so there will need to be some kinds of introspection available to support this (eventually). For all I know, Rust has something similar.

I don't think this is a duplicate of Get fields of a struct type in a macro since this answer could include use of external tools (not necessarily macros).

like image 785
ideasman42 Avatar asked Sep 01 '16 08:09

ideasman42


3 Answers

Is there a way to print out a complete list of available members of a type or instance in Rust?

Currently, there is no such built-in API that you can get the fields at runtime. However you can retrieve fields by using two different ways.

  1. Declarative Macros
  2. Procedural Macros

Solution By Using Declarative Macro

macro_rules! generate_struct {
    ($name:ident {$($field_name:ident : $field_type:ty),+}) => {
        struct $name { $($field_name: $field_type),+ }
        impl $name {
            fn introspect() {
            $(
            let field_name = stringify!($field_name);
            let field_type = stringify!($field_type);
               println!("Field Name: {:?} , Field Type: {:?}",field_name,field_type);
            )*
            }
        }
    };
}

generate_struct! { MyStruct { num: i32, s: String } }

fn main() {
    MyStruct::introspect();
}

This will give you the output:

Field Name: "num" , Field Type: "i32"
Field Name: "s" , Field Type: "String"

Playground


Solution Using Procedural Macro

Since procedural macros are more complicated from the declarative macros, you better to read some references(ref1, ref2, ref3) before starting.

We are going to write a custom derive which is named "Instrospect". To create this custom derive, we need to parse our struct as a TokenStream with the help of syn crate.

#[proc_macro_derive(Introspect)]
pub fn derive_introspect(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as ItemStruct);

    // ...
}

Since our input can be parsed as ItemStruct and ItemStruct has the fields() method in it, we can use this to get fields of our struct.

After we get these fields, we can parse them as named and we can print their field name and field type accordingly.

input
    .fields
    .iter()
    .for_each(|field| match field.parse_named() {
        Ok(field) => println!("{:?}", field),
        Err(_) => println!("Field can not be parsed successfully"),
    });

If you want to attach this behavior to your custom derive you can use the following with the help of the quote crate:

let name = &input.ident;

let output = quote! {
    impl #name {
        pub fn introspect(){
            input
            .fields
            .iter()
            .for_each(|field| match field.parse_named() {
                Ok(field) => println!("{:?}", field),
                Err(_) => println!("Field can not be parsed successfully"),
             });
        }
    }
};

// Return output TokenStream so your custom derive behavior will be attached.
TokenStream::from(output)

Since the behaviour injected to your struct as introspect function, you can call it in your application like following:

#[derive(Introspect)]
struct MyStruct {
    num: i32,
    text: String
}

MyStruct::introspect();

Note: Since the example you are looking for similar to this question. This Proc Macro Answer and Declarative Macro Answer should give you insight as well

like image 106
Akiner Alkan Avatar answered Nov 09 '22 19:11

Akiner Alkan


To expand on my comment, you can use rustdoc, the Rust documentation generator, to view almost everything you're asking for (at compile time). rustdoc will show:

  • Structs (including public members and their impl blocks)
  • Enums
  • Traits
  • Functions
  • Any documentation comments written by the crate author with /// or //!.

rustdoc also automatically links to the source of each file in the [src] link.

Here is an example of the output of rustdoc.

Standard Library

The standard library API reference is available here and is available for anything in the std namespace.

Crates

You can get documentation for any crate available on crates.io on docs.rs. This automatically generates documentation for each crate every time it is released on crates.io.

Your Project

You can generate documentation for your project with Cargo, like so:

cargo doc

This will also automatically generate documentation for your dependencies (but not the standard library).

like image 7
Aurora0001 Avatar answered Nov 09 '22 19:11

Aurora0001


I have written a very simple crate which uses procedural macro. It gives you access to members information plus some simple information about struct/enum you use. Information about methods can not be given because procedural macros simply can't get this information, and as far as I know, there are no any methods which may give such information.

like image 1
Victor Polevoy Avatar answered Nov 09 '22 20:11

Victor Polevoy