Bill Barry
Bill Barry

Reputation: 3523

Is it possible to create something like a MethodCallExpression without knowing the types of the related expressions?

I am playing with the Roslyn CTP nuget package and thought I would acquainted with the SyntaxVisitor<> class so I am creating a Roslyn.Compilers.CSharp.SyntaxNode to System.Linq.Expression converter (which appears to work for any code that doesn't involve semantic knowledge unknown to the AST or provided outside of the visit call).

Anyway, I have the following code:

public override Expression VisitInvocationExpression(InvocationExpressionSyntax node) {
    ???
}

And I've got nothing. node has an Expression property which can be resolved by visiting it as long as it isn't a method call:

return Expression.Invoke(
    Visit(node.Expression), 
    node.ArgumentList.Arguments.Select(a => Visit(a.Expression))
)

This seems to work as long as Expression is not a method call. If it is a method call though (static, instance or extension), the first Visit winds up calling VisitMemberAccessExpression where I then fail (due to the nature of these not being members).

Is there a way around this?

Upvotes: 4

Views: 358

Answers (1)

Arek Bal
Arek Bal

Reputation: 733

Expression.Call is the way to go. But still you would need to use semantic data to get associated reflection data such as Types and MethodInfo.

The way to go about it is:

  1. Get compilation object by calling Compilation.Create(...) in other words: compile your program using Roslyn API
  2. Get SemanticModel out of it by calling GetSemanticModel(ast)
  3. Get TypeInfo calling GetTypeInfo(expression)

So... to sum it up

Compilation.Create(...).GetSemanticModel(ast).GetTypeInfo(expression);

Upvotes: 2

Related Questions