mozilla / uniffi-rs

a multi-language bindings generator for rust
https://mozilla.github.io/uniffi-rs/
Mozilla Public License 2.0
2.9k stars 232 forks source link

Let `#[Enum]` interfaces have methods #1470

Open linabutler opened 1 year ago

linabutler commented 1 year ago

One thing that I've found super helpful when working with enums with associated data is being able to define getters and predicates on them. Here's an example inspired by https://github.com/mozilla/application-services/pull/5346#discussion_r1095272665:

dictionary SuggestionDetails {
    string title;
    string url;
    string? icon;
};

// Each suggestion type has a common set of details, and additional fields specific to that type.
#[Enum]
interface Suggestion {
  Shopping(SuggestionDetails details, string full_keyword, string advertiser);
  Education(SuggestionDetails details, string full_keyword);
  Wikipedia(SuggestionDetails details);
  Weather(SuggestionDetails details, CurrentConditions current_conditions, Forecast forecast);
};

I'd love to be able to define methods on Suggestion like:

UniFFI doesn't allow doing that yet, but @mhammond's follow-up comment (https://github.com/mozilla/application-services/pull/5346#discussion_r1095317470) inspired me to file a ticket to see if it could! 😊 As a workaround, we can add extensions in hand-written Kotlin and Swift files, but I wonder if we could push this down into UniFFI.

(It would be even nicer to make these readonly attributes instead of methods—I think all our target languages support that? Python has @property, Kotlin has getters, Swift has computed properties, Ruby's getters are regular methods—but that might be too tricky).

┆Issue is synchronized with this Jira Task ┆Issue Number: UNIFFI-236

Sajjon commented 9 months ago

@linabutler nice! I also had the idea id of generaring computed properties in the land of Swift, but we probably need to be able to chose if a no arg method should be exported as computed property or method, since at least in Swift there is an informal rule that computed properties SHOULD be constant time.