rescript-compiler icon indicating copy to clipboard operation
rescript-compiler copied to clipboard

Support coercing on a function type

Open TheSpyder opened this issue 1 year ago • 2 comments

I recently discovered that coercion works for variants where everything is represented by the same primitive type: https://rescript-lang.org/docs/manual/latest/variant#coercing-variants-to-primitives

This is great, but I have a function that returns one of these variants and I can't coerce that. It seems to work for no-argument functions, but not functions with arguments. https://rescript-lang.org/try?version=v11.1.1&code=C4TwDgpgBAhgzgSQHbCgXigHygAXgCgEYBKKAeSWmzznwCZSAVAdwHstcCBmJgCwCcIEAFDCANhFStKyYAC5YiFOnKVxkqMFayV+aRB1yAfFACWKYqImpBwAK78ksgKpJTqDPlJoTFEdahbBycUAGVzAHMJXQB9b181dVQtWQAxQl0gxxc3VGMofDtc9BNzYGJLAJSUVLpMyWDZcKQo6Hz8AHIYErMLYiA

The specific example I'm trying to model is array sort, so I'd need it to work on 2-argument functions as well. https://rescript-lang.org/try?version=v11.1.1&code=C4TwDgpgBAxg9gWzAQwE4EsDOcB2UC8AUFFAD5QACymAFALQCMAlFADISaYAqAFsjsTKVqNAAwsAogEcArsgA2g8lVrMoAcVQRkwCKl79ChOJDwApTADoAgqlTIQAJkLyIwKNlTv8UGmlQANFAAfgBmAFy+AOTIQTEs+AB8sIgoGNg4CYmCnsAAkjgACvLIMBAA6ujAPH52dImY8uhlAGKoiGJMQTShUOHJ6DjATExAA

TheSpyder avatar Jun 19 '24 07:06 TheSpyder

One observation: the coercion in the example seems to work if the argument type is not polymorphic, e.g. float. Coercion was not modified for function types, it still uses the original implementation, but the way it's been implemented for variants might interfere with the pre-existing mechanism in certain cases (e.g. polymorphic argument).

cristianoc avatar Jun 19 '24 10:06 cristianoc

Ah, that makes sense. Unfortunately the way I'm trying to use it with Array sort requires polymorphism.

For now I've just used an obj magic.

TheSpyder avatar Jun 19 '24 10:06 TheSpyder

@TheSpyder any more tests for https://github.com/rescript-lang/rescript-compiler/pull/6828 ?

cristianoc avatar Jul 02 '24 09:07 cristianoc

@cristianoc the second example is the one I pulled from my codebase, I haven't come across any others (although I haven't really been looking). I appreciate you looking at this!

TheSpyder avatar Jul 02 '24 10:07 TheSpyder

@cristianoc the second example is the one I pulled from my codebase, I haven't come across any others (although I haven't really been looking). I appreciate you looking at this!

Great, that example is covered already.

cristianoc avatar Jul 02 '24 11:07 cristianoc

Done in https://github.com/rescript-lang/rescript-compiler/pull/6828

cristianoc avatar Jul 03 '24 06:07 cristianoc