简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM