简体   繁体   中英

Is it possible to modify a SyntaxTree in Roslyn and run the edited code?

I am changing a code using Roslyn, however, after the change a new SyntaxNode is generated, but I am not able to find a way to execute this new code. The only one I found was to get the ToString from the new Root and call EvaluateAsync with the new string. There should be a means to outperform this, since I already have a new code already compiled.

static void Main(string[] args)
{
    var expression = "System.Console.WriteLine(\"Test\")";
    var compile = CSharpScript.Create<EntityRepresentation>(expression).GetCompilation();
    var root = compile.SyntaxTrees.Single().GetRoot();

    var descentands = root.DescendantNodes().Where(n =>
    {
        if (n is ArgumentSyntax)
            return true;
        return false;
    }).ToList();

    var otherRoot = root.ReplaceNodes(descentands, (n1, n2) =>
    {
        var argumentName = Argument(LiteralExpression(SyntaxKind.StringLiteralExpression, Literal("NewValue")));
        return argumentName;
    });

    var newCode = otherRoot.ToString();

    // Faz o que estou querendo, contudo não me parece a melhor maneira
    var result = CSharpScript.EvaluateAsync(newCode).Result;
}

The methods that create a Script object from a syntax tree, are unfortunately internal to the Microsoft assemblies.

But, you don't have to compile twice - you can just parse the first time, and then compile the second time.

var expression = "System.Console.WriteLine(\"Test\")";
var origTree = CSharpSyntaxTree.ParseText(expression, 
                  CSharpParseOptions.Default.WithKind(SourceCodeKind.Script));
var root = origTree.GetRoot();

// -Snip- tree manipulation

var script = CSharpScript.Create(otherRoot.ToString());
var errors = script.Compile();
if(errors.Any(x => x.Severity == DiagnosticSeverity.Error)) {
    throw new Exception($"Compilation errors:\n{string.Join("\n", errors.Select(x => x.GetMessage()))}");
}
await script.RunAsync();

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