Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a trailing end of line to AttribueList using Roslyn CTP

I am trying to generate a few properties with [DataContractAttribute] using Roslyn CTP Syntax. Unfortunately, Roslyn puts the attribute on the same line as the property.

Here is what I get:

[DataContract]public int Id { get; set; }
[DataContract]public int? Age { get; set; }

What I would like to achieve:

[DataContract]
public int Id { get; set; }
[DataContract]
public int? Age { get; set; }

Generator's code:

string propertyType = GetPropertyType();
string propertyName = GetPropertyName();
var property = Syntax
    .PropertyDeclaration(Syntax.ParseTypeName(propertyType), propertyName)
    .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword)))
    .WithAttributeLists(
        Syntax.AttributeList(
            Syntax.SeparatedList<AttributeSyntax>(
                Syntax.Attribute(Syntax.ParseName("DataContract")))))
    .WithAccessorList(
        Syntax.AccessorList(
            Syntax.List(
                Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)),
                Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken))
        )));

After wrapping those properties in a class, a namespace and finally CompilationUnit, I am using the following code to get the string result:

var compUnit = Syntax.CompilationUnit().WithMembers(...);
IFormattingResult fResult = compUnit.Format(new FormattingOptions(false, 4, 4));
string result = fResult.GetFormattedRoot().GetText().ToString();
like image 931
Maciej Wozniak Avatar asked Jun 17 '13 19:06

Maciej Wozniak


2 Answers

One way to do this would to format your code and then modify it by adding trailing trivia to all property attribute lists. Something like:

var formattedUnit = (SyntaxNode)compUnit.Format(
    new FormattingOptions(false, 4, 4)).GetFormattedRoot();

formattedUnit = formattedUnit.ReplaceNodes(
    formattedUnit.DescendantNodes()
                 .OfType<PropertyDeclarationSyntax>()
                 .SelectMany(p => p.AttributeLists),
    (_, node) => node.WithTrailingTrivia(Syntax.Whitespace("\n")));

string result = formattedUnit.GetText().ToString();
like image 141
svick Avatar answered Nov 04 '22 16:11

svick


Use it like below:

.WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)
like image 44
Eugene Shelukhin Avatar answered Nov 04 '22 16:11

Eugene Shelukhin