thi-ng / umbrella

⛱ Broadly scoped ecosystem & mono-repository of 198 TypeScript projects (and ~175 examples) for general purpose, functional, data driven development
https://thi.ng
Apache License 2.0
3.31k stars 144 forks source link

[shader-ast] Allow type inference of defn with arbitrary number of arguments #440

Open sylee957 opened 7 months ago

sylee957 commented 7 months ago

It is possible to avoid overloads TaggedFn5, TaggedFn6, ... by using variadic tuple types and mapped types. I try to demonstrate the implementation here.

Also, args: [...Args], is very useful here to infer the type as heterogeneous tuples than homogeneous arrays. If I do args: Args, and if I pass array like ['int', 'float', 'bool'], the types of parameters are inferred as Sym<'int' | 'float' | 'bool'> which is not desirable.

As I check the integration with stdlib, I had seen some failing cases of implementation that uses very generic types, such as matching types of mul<TypeOfArg<T>, 'float'>.

However, I was able to fix the issues by extending some overloads, and I also tested out by removing some other any casting that were used before.

I wonder if there is more robust suggestion to make T round trip to Sym<T> instead of Sym<TypeOfArg<T>>, which seems quite complicated to debug. I think that the complexity comes from the fact that args is defined as union T | [T, string, options] which is a bit involved to descompose.

The other rationale that I want to remove the restriction of number of parateters of function, is that shader-ast does not support struct yet. The only workaround to transform a program that uses struct, into a program that doesn't use struct, is to expand struct into a lot of variables, and to use functions with many parameters with out or inout qualifier. And I worry about if I encouter such limitations in production, and if I want to avoid 'death by a thousand overloads' problem. So it can be useful to remove such limitation to define functions more than 8 parameters.

postspectacular commented 6 months ago

My experience with using mapped types has been hit & miss over the years, esp. since they (TS team) keep on playing with inferencing rules and so making mapped types more brittle over time. A mapped type which worked in one TS version might not work in the future. Again (just as with template literal types in your other PR), a lot of this based on (repeated) experience with older (but not that old!) versions of TS and maybe most of these issues have been resolved or are more stable now, but I've literally wasted weeks of my life setting up complicated mapped type systems only to have them break completely in a TS upgrade a year later... But having said all that, mapped types are of course a beautiful thing (when they work) I will check our your branch and report back in a few days! So THANK YOU for that already!