randomPoison / cs-bindgen

Experiment in using Rust to build a library that can be loaded by Unity across multiple platforms
4 stars 0 forks source link

Support generating properties for getters and setters #20

Open randomPoison opened 4 years ago

randomPoison commented 4 years ago

Right now all methods in an impl block are generated as methods in the corresponding C# class. For simple getters, though, the more idiomatic equivalent in C# would be to use a property. For example, in the following case:

impl PersonInfo {
    pub fn age(&self) -> u32 {
        self.age
    }
}

The idiomatic C# equivalent would be:

public int Age => ...;

Similarly, simple setters should also be generated as properties instead of methods.

In simple cases, it's not too difficult to automatically detect getters and setters: A method that takes no parameters and returns a single value is a getter, and a method that takes a single parameter and returns nothing is a setter. However not all methods that follow this pattern should be converted into properties: Generally methods that "look like" getters but perform expensive calculations are kept as methods in C# in order to encourage users to only call the method once and cache the result of the calculation. As such, we'll need to decide if we want to use this heuristic to optimistically generate properties on a best-effort basis, or if we should require users to annotate functions that should be made into properties.

Either way, we'll need attributes that allow users to manually specify when methods should (or should not) be generated as properties. I'm thinking:

The #[cs_bindgen(name = "Foo")] should probably be generalized such that it can be used to control the name of any generated item.