How to add a new operator in C # using Roslyn

I am trying to implement a DSL function in C #. It might look something like LINQ queries. I am wondering if it is possible to implement new unary or binary operators using Roslyn.

In the past few days, I have searched for searches without much success. It would be great if someone could point me to some of Roslin’s samples or documents.

+7
c # roslyn
source share
1 answer

There are two ways to use Roslyn to implement a new language in C #.

  • Use the Roslyn API to parse the source code in the syntax tree, then convert the syntax tree to actual C # and compile it.

    This is ideal if your language is really syntactically correct C # code, but the semantics are different. For example, you can implement await this way if you made await look like a function call (for example, await(x) would be right, but not await x ).

    If you want to introduce a new syntax (for example, a new statement), it may work, since Roslyn supports parsing broken code. But this, most likely, will not work as well, because then the syntax tree may not look the way you want. Worse, the results can be consistent (sometimes your new syntax will be parsed one way, sometimes the other).

  • Since Roslyn is now open source, you can modify the source code of the compiler in some way, including adding a new statement.

    But to do this, most likely, will not be easy. And I think that the workflow will also be more complicated: you need to compile your own version of the compiler, and not just use the library from NuGet, as in option 1.

+9
source share

All Articles