jhugman / uniffi-bindgen-react-native

A uniffi bindings generator for calling Rust from react-native
Other
0 stars 0 forks source link

Add `instanceOf` methods to every type. #49

Open jhugman opened 1 month ago

jhugman commented 1 month ago

So far, Error, Object and non-flat Enum have all grown instanceOf methods.

This ticket is to generate instanceOf methods for all types:

  1. add a instanceOf(obj: any): obj is T to FfiConverter.
    • for types with existing instanceOf methods, the converter should call that type's static methods.
    • for object, the FfiConverter takes a factory which is generated. This should have the instanceOf method.
    • for primitive types, these can be hard coded e.g. typeof v === 'number'.
    • for Record, an structural types, we can implement the FfiConverter.instanceOf in terms of other FfiConverter.instanceOf methods, recursively calling instanceOf until a false is found.
      1. Add instanceOf to the decl_type_name objects: mostly, I think for Record, but there may be others.

Consider a record:

type MyRecord = { name: string, age: /*uint8/ number; };

const MyRecord = {
  create(value: { … }): MyRecord { … },
  instanceOf(obj: any): obj is MyRecord { return FfiConverterTypeMyRecord.instanceOf(obj); },
};

then, in the FfiConverterTypeMyRecord an instanceOf method can be implemented:

instanceOf(obj: any): obj is T {
  return (
    FfiConverterString.instanceOf(obj.name) && 
    FfiConverterUInt8.instanceOf(obj.age) && 
  );
}