Question

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

I have been googling last few days without much success. It would be great if someone could point me to some samples or Roslyn documentations.

Was it helpful?

Solution

There are two ways how you could use Roslyn to implement a new C#-based language.

  1. Use the Roslyn API to parse the source code into a syntax tree, then transform the syntax tree into actual C# and compile that.

    This is ideal if your language is actually syntactically valid C# code, but the semantics are different. For example, you could implement await this way, if you forced await to look like a function call (e.g. await(x) would be valid, but not await x).

    If you want to introduce new syntax (like a new operator), it might work, since Roslyn does support parsing “broken” code. But it most likely won't work that well, because then the syntax tree might not look the way you want. Worse, the results might not be consistent (sometimes, your new syntax will be parsed one way, sometimes another).

  2. Since Roslyn is now open source, you can actually modify the source code of the compiler in any way you want, including adding a new operator.

    But doing that is most likely not going to be simple. And I think the workflow is also going to be more complicated: you need to compile your own version of the compiler, not just use a library from NuGet like in option 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top