Translate C# code into AST?

2019-01-31 13:58发布

Is it currently possible to translate C# code into an Abstract Syntax Tree?

Edit: some clarification; I don't necessarily expect the compiler to generate the AST for me - a parser would be fine, although I'd like to use something "official." Lambda expressions are unfortunately not going to be sufficient given they don't allow me to use statement bodies, which is what I'm looking for.

12条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-31 14:35

Is it currently possible to translate C# code into an Abstract Syntax Tree?

Yes, trivially in special circumstances (= using the new Expressions framework):

// Requires 'using System.Linq.Expressions;'
Expression<Func<int, int>> f = x => x * 2;

This creates an expression tree for the lambda, i.e. a function taking an int and returning the double. You can modify the expression tree by using the Expressions framework (= the classes from in that namespace) and then compile it at run-time:

var newBody = Expression.Add(f.Body, Expression.Constant(1));
f = Expression.Lambda<Func<int, int>>(newBody, f.Parameters);
var compiled = f.Compile();
Console.WriteLine(compiled(5)); // Result: 11

Notice that all expressions are immutable so they have to be built anew by composition. In this case, I've prepended an addition of 1.

Notice that these expression trees only work on real expressions i.e. content found in a C# function. You can't get syntax trees for higher constructs such as classes this way. Use the CodeDom framework for these.

查看更多
时光不老,我们不散
3楼-- · 2019-01-31 14:35

It is strange that nobody suggested hacking the existing Mono C# compiler.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-31 14:41

Check out .NET CodeDom support. There is an old article on code project for a C# CodeDOM parser, but it won't support the new language features.

There is also supposed to be support in #develop for generating a CodeDom tree from C# source code according to this posting.

查看更多
Lonely孤独者°
5楼-- · 2019-01-31 14:42

Personally, I would use NRefactory, which is free, open source and gains popularity.

查看更多
祖国的老花朵
6楼-- · 2019-01-31 14:46

ANTLR is not very useful. LINQ is not what u want.

Try Mono.Cecil! http://www.mono-project.com/Cecil

It is used in many projects, including NDepend! http://www.ndepend.com/

查看更多
可以哭但决不认输i
7楼-- · 2019-01-31 14:49

Our C# front end for DMS parses full C# 3.0 including LINQ and produces ASTs. DMS in fact is an ecosystem for analyzing/transforming source code using ASTs for front-end provided langauges.

EDIT 3/10/2010: ... Now handles full C# 4.0

EDIT: 6/27/2014: Handles C# 5.0 since quite awhile.

EDIT: 6/15/2016: Handles C# 6.0. See https://stackoverflow.com/a/37847714/120163 for a sample AST.

查看更多
登录 后发表回答