Kent Boogaart
Kent Boogaart

Reputation: 178780

Generating syntax for a method signature from a method symbol in Roslyn

I'm trying to generate code using Roslyn (first time user). I'm finding it so verbose that I can only assume I'm doing something wrong. At the moment I'm generating an implementation of a method for a given IMethodSymbol (which came from an interface):

private static MethodDeclarationSyntax GetMethodDeclarationSyntax(IMethodSymbol methodSymbol)
{
    if (methodSymbol.MethodKind != MethodKind.Ordinary)
    {
        return null;
    }

    var parameters = methodSymbol
        .Parameters
        .Select(x => SF
            .Parameter(SF.Identifier(x.Name))
            .WithType(SF.IdentifierName(x.Type.ToDisplayString(symbolDisplayFormat))));

    return SF
        .MethodDeclaration(
            SF.IdentifierName(methodSymbol.ReturnType.ToDisplayString(symbolDisplayFormat)),
            SF.Identifier(methodSymbol.Name))
        .WithModifiers(
            SF.TokenList(
                SF.Token(SyntaxKind.PublicKeyword)))
        .WithParameterList(
            SF.ParameterList(
                SF.SeparatedList<ParameterSyntax>(parameters)));
}

It's already pretty hefty and I haven't accounted for the actual implementation, generic parameters, ref/out parameters etcetera.

Is there a simpler way to achieve this?

Upvotes: 3

Views: 1729

Answers (2)

Kent Boogaart
Kent Boogaart

Reputation: 178780

Given Kevin's answer, this is what I arrived at:

var methodDeclaration = syntaxGenerator.MethodDeclaration(methodSymbol);
methodDeclaration = syntaxGenerator
    .WithModifiers(
        methodDeclaration,
        syntaxGenerator
            .GetModifiers(methodDeclaration)
            .WithIsAbstract(false));
methodDeclaration = syntaxGenerator
    .WithStatements(
        methodDeclaration,
        GetMethodStatementsSyntax(syntaxGenerator, semanticModel, methodSymbol));

Notice we have to manually remove the abstract modifier from the method symbol (since it originated from an interface, it is intrinsically abstract). I also add the statements after removing the abstract modifier because otherwise they're ignored.

Upvotes: 2

Kevin Pilch
Kevin Pilch

Reputation: 11615

As of VS 2015 CTP 6 and the Roslyn 1.0-rc1 NuGet packages, take a look at the SyntaxGenerator class.

Upvotes: 2

Related Questions