3

I am trying to write a parser for a QML-like markup language and I would like to allow C# expressions in the markup. So an example might look like this:

ClassName {
    Property1: 10
    Property2: Math.Sqrt(123)
    Property3: string.Format("{0} {1}", "Hello", "World")
}

(This is also somewhat like ASP.NET's Razor engine but afaics Razor doesn't use Roslyn?)

How would I do this? I want to parse only a single expression, whether that be a literal, a method call, a lambda etc. I've tried using CSharpSyntaxTree.ParseText but that expects a whole file and I can't find any documentation that seems to relate to this use-case.

Grokys
  • 16,228
  • 14
  • 69
  • 101

3 Answers3

6

You need to call CSharpSyntaxTree.ParseText(), and pass a CSharpParseOptions with SourceCodeKind.Interactive, which allows top-level expressions.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Does this really work? I'm getting a NotSupportedException when I pass the SourceCodeKind.Interactive option... – glopes Sep 05 '15 at 23:22
  • Ok, it seems like the feature was shelved for 1.0. I've added the clarification as an answer for future visitors. – glopes Sep 05 '15 at 23:44
4

SyntaxFactory.ParseExpression() worked for me.

0

It looks like this feature was available in some of the preview releases of Roslyn, but was in the meantime shelved for the 1.0 release.

Interactive (REPL) and Scripting support are planned to make a comeback on 1.1 as can be seen in the interactive design meeting notes@github.

EDIT: In fact, in the latest pre-release NuGet package it is again possible to pass SourceCodeKind.Interactive to ParseText.

glopes
  • 4,038
  • 3
  • 26
  • 29