user1454265
user1454265

Reputation: 878

Can I use Roslyn to accomplish this C# syntax transformation?

Two-part question here about adding C# syntax sugar using Roslyn:

First, is it possible using Roslyn to add new syntax to C#, or does it always have to be a transformation from valid C# to other valid C#? For example, I'd like to do something like VB.NET's XML literals:

XElement lvalue = <some><xml /></some>;

Is it possible to transform this at compile time to:

XElement lvalue = new XElement("some", new XElement("xml")); // or whatever

Second, if that's possible, what does it look like to the user? Can I do this such that one writes the first expression, and never sees the transformation to the second expression (it happens transparently at compile-time)? Or do Roslyn syntax transformations have to appear as sort of an IDE "refactoring suggestion"? I'm unclear on this from the Roslyn docs.

Upvotes: 1

Views: 560

Answers (2)

Eric Lippert
Eric Lippert

Reputation: 660455

First, is it possible using Roslyn to add new syntax to C#

Nope.

or does it always have to be a transformation from valid C# to other valid C#?

Yep.

Roslyn is a C#/VB analysis engine; those are the only languages it analyzes. It is not for extending the C# or VB languages.

The C# compiler is open sourced under a fairly permissive license. If you want to write your own version of it, you can certainly fork the repository and make the parser do whatever you like.

Upvotes: 9

Stuart
Stuart

Reputation: 5506

If it has to look the the snippet you provided then no (without having to solve some much bigger problems), however you could go down a similar route that stackoverflow went with for localisation

You could introduce something like _x("<some><xml /></some>"), you don't get much benefit in terms of syntax (cause you could have a runtime method that parses this), but you could have Roslyn take the work of replacing it with the exact code you want it to generate.

Upvotes: 2

Related Questions