Skip to content

Elastic marker only when necessary #302

@sharwell

Description

@sharwell

We're working on diagnostics and code fixes that affect the coding style within files. As such, it's very important that the changes we make preserve the original formatting for everything not directly related to the change being made. For example, if the code fix is supposed to remove parentheses from an expression, then the input and output could resemble this:

// input:
int x =  (0 +2- 1-1) ;
// output:
int x =  0 +2- 1-1 ;

We're having trouble with certain cases where the code fix must insert a space for correctness, such as the following:

// input:
return(0);
// output:
return 0;

It seems like the option we want is to add SyntaxFactory.ElasticMarker to the leading trivia of the expression. Unfortunately, when we use this, the formatter treats this as a request to reformat the entire expression (or at minimum both the leading and trailing trivia for the expression, even if no changes are required).

We found a solution by using SyntaxFactory.ParseSyntaxTree to check if the actual output without a space is equivalent to our intended output, but this seems like a very expensive approach, and we aren't even 100% sure it works in all cases.

We want to be able to include a SyntaxTrivia which means the following:

This trivia contains no text, unless omitting it would change the meaning of the code. In the latter case, the trivia is written as exactly one space. No alterations will be made to any other SyntaxTrivia as a result of using this trivia.

Solution using ElasticMarker which caused undesired reformatting:

DotNetAnalyzers/StyleCopAnalyzers#450

Solution using ParseSyntaxTree which we'd like to avoid:

DotNetAnalyzers/StyleCopAnalyzers#453

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions