dart-lang / native

Dart packages related to FFI and native assets bundling.
BSD 3-Clause "New" or "Revised" License
115 stars 40 forks source link

Generated Dart code doesn't allow combining `NS_OPTIONS` #1518

Open stuartmorgan opened 2 weeks ago

stuartmorgan commented 2 weeks ago

I was attempting to migrate the following Obj-C code to Dart:

[item addObserver:observer
       forKeyPath:@"loadedTimeRanges"
          options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
          context:NULL];

Where the options are defined by:

typedef NS_OPTIONS(NSUInteger, NSKeyValueObservingOptions) {
    NSKeyValueObservingOptionNew = 0x01,
    NSKeyValueObservingOptionOld = 0x02,
    NSKeyValueObservingOptionInitial = 0x04,
    NSKeyValueObservingOptionPrior = 0x08

};

The generated code is:

enum NSKeyValueObservingOptions {
  NSKeyValueObservingOptionNew(1),
  NSKeyValueObservingOptionOld(2),
  NSKeyValueObservingOptionInitial(4),
  NSKeyValueObservingOptionPrior(8);

  final int value;
  const NSKeyValueObservingOptions(this.value);

  static NSKeyValueObservingOptions fromValue(int value) => switch (value) {
        1 => NSKeyValueObservingOptionNew,
        2 => NSKeyValueObservingOptionOld,
        4 => NSKeyValueObservingOptionInitial,
        8 => NSKeyValueObservingOptionPrior,
        _ => throw ArgumentError(
            "Unknown value for NSKeyValueObservingOptions: $value"),
      };
}

which is essentially unusable:

Since the whole point of NS_OPTIONS as distinct from NS_ENUM is to allow combining values, the generator needs to make different code for NS_OPTIONS.

liamappelbe commented 2 weeks ago

Use the enums.as-int option to choose which enums to generate as int constants instead of Dart enums.