Reflective struct editor?


#1

A standard exercise for dynamic languages is to use reflection to build a GUI for editing arbitrary objects. You start by getting the type of the object, and if it’s a primitive type, just generate the appropriate GUI element. For composite types, you get the list of elements of the type, then generate a GUI by combining the GUI you get from recursive calls for each element.

Based on a cursory examination, this should be possible work with reflect_marker feature. Has anyone done this? Or that feature hasn’t really worked out? Or maybe I’m wrong about it being possible?


#2

There’s some support here, but it’s spotty. You can use the Any trait to downcast a trait object to a known type, so you can test for each primitive type and act accordingly. Composite types don’t come so freely, however.

The problem is that Rust does not retain much reflective information at runtime; it’s not like a dynamic language where the interpreter or VM knows almost everything about every type in the program.

There is some metadata included with crates compiled as .rlibs but I don’t know what kind of type information is included. Any method to get at it and act upon it would be hacky as hell anyways.

The closest I think you could get with an existing solution is with rustc_serialize and the corresponding compiler support for #[derive(RustcEncodable)], so any composite type you control can have a trait impl which will write out its structure and data at runtime.

This is obviously not a universal solution because it only works for types which implement or derive rustc_serialize::Encodable, which you might not have control over. And there’s nothing that says that the encoded representation of a type has to match its actual structure.

There’s also no way to update the struct unless you want to work with the Decodable trait and the extensive copying that will incur.

You could always implement your own compiler plugin to add all the reflective information you want. Perhaps by adding a #[reflect] attribute. However, this is still limited to types you control, AFAIK. I’m not sure if even compiler plugins can inspect types from crates external to the one they are currently operating on.


#3

This is really not a started exercise for a static language. While there is a potential for rust to support these things in the future, or not quite as well, currently (compiler plugins, serde, macros, …), this is not what I would start out on.