Search code examples
f#type-providers

Using reflection in type providers to mimic RFC FS-1023


As I understand it, only primitive types can be given as parameters to a type provider so you can't do something like TypeProvider<Option<int>> but you can do TypeProvider<"Option<int>">. Is there some way I can use reflection to mimic the former with the latter?

The idea would be to be able to types in some way to generate new types based off them. For example, a simple TypeProvider that copies the type might do this:

type Foo = {Str : string}
type Bar = TypeProvider<Foo>
// Bar.Foo is a string

Solution

  • This cannot be done in any sensible way.

    The main problem is that the type Foo is not yet compiled at the point when the type provider is instantiated, so you cannot access it through reflection.

    Type providers can be abused in a variety of interesting ways. If you want to see most of them, the Mixin type provider is perhaps the most adventurous example - but I'm not sure if it has a way of doing what you're asking about.

    That said, nothing prevents the type provider such as Crazy<"Foo"> from looking at the disk and trying to find the type definition for Foo somewhere in the F# source code. I imagine this could potentially work. The caveat is that you will only be able to get the source code - and so you'd have to parse that yourself and extract the type definition on your own.