rust-diplomat / diplomat

Experimental Rust tool for generating FFI definitions allowing many other languages to call Rust code
https://rust-diplomat.github.io/book/
Other
511 stars 48 forks source link

JS2: Support Constructors #582

Open ambiguousname opened 2 months ago

ambiguousname commented 2 months ago

Per https://tc39.es/proposal-temporal/docs/, we could use .from,

Or we could check for a symbol passed into the args that's only defined in the diplomat runtime to allow for calling a hidden constructor.

Manishearth commented 2 months ago

Annoyingly, we must have a constructor to be able to correctly generate objects with the right instanceof. There may be a way to hack this using __proto__, but AIUI that's not always perfect.

This model would work something like this:

class Locale {
   constructor(symbol, ptr, selfEdges) {
         if (symbol !== diplomat_runtime.RawConstructorSymbol) { throw; }
         // regular constructor
   }

}

and when the locale constructor has been overridden:

class Locale {
   constructor() {
         if (arguments.length > 0 && arguments[0] == diplomat_runtime.RawConstructorSymbol) {
            // regular constructor
         } else {
            Locale.create.apply(arguments)
         }
   }

   // generated method for `create()`, private but extant
   #create(string) {...}

}
Manishearth commented 1 month ago

I don't think this is fixed: in Diplomat by "constructors" I would mean #[diplomat::attr(*, constructor)]

I think how this should work is that any type with a constructor gets a constructor() that works there, with the Symbol.diplomatConstructor path working for internal stuff.

For structs, we default-generate a field-based ctor, but if we end up overriding it, we still generate a fromFields() method or something.