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.
new operator. The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
No, unfortunately you cannot define new operators—you can only overload existing operators (with a few important exceptions, such as operator. ).
There's no new / delete expression in C. The closest equivalent are the malloc and free functions, if you ignore the constructors/destructors and type safety.
An Example of allocating array elements using “new” operator is given below: int* myarray = NULL; myarray = new int[10]; Here, new operator allocates 10 continuous elements of type integer to the pointer variable myarray and returns the pointer to the first element of myarray.
There are two ways how you could use Roslyn to implement a new C#-based language.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With