Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new operator in C# using Roslyn

Tags:

c#

roslyn

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.

like image 872
Shahed Avatar asked Apr 07 '14 15:04

Shahed


People also ask

What is new operator in C?

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.

Can we create new operator?

No, unfortunately you cannot define new operators—you can only overload existing operators (with a few important exceptions, such as operator. ).

Does C have a new 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.

What is new operator in C give example?

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.


1 Answers

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.

like image 158
svick Avatar answered Nov 05 '22 02:11

svick