This repository was archived by the owner on Jul 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathNewLineAtEndOfFileRule.cs
More file actions
70 lines (62 loc) · 2.48 KB
/
NewLineAtEndOfFileRule.cs
File metadata and controls
70 lines (62 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.DotNet.CodeFormatting.Rules
{
[SyntaxRule(SyntaxRuleOrder.NewLineAtEndOfFileRule)]
internal sealed class NewLineAtEndOfFileRule : CSharpOnlyFormattingRule, ISyntaxFormattingRule
{
public SyntaxNode Process(SyntaxNode syntaxRoot, string languageName)
{
bool needsNewLine;
var endOfFileToken = syntaxRoot.GetLastToken(true, true, true, true);
if (!endOfFileToken.IsKind(SyntaxKind.EndOfFileToken))
{
throw new InvalidOperationException("Expected last token to be EndOfFileToken, was actually: " + endOfFileToken.Kind());
}
if (endOfFileToken.HasLeadingTrivia)
{
return AddNewLineToEndOfFileTokenLeadingTriviaIfNecessary(syntaxRoot, endOfFileToken);
}
var lastToken = syntaxRoot.GetLastToken();
if (!lastToken.HasTrailingTrivia)
{
needsNewLine = true;
}
else
{
var lastTrivia = lastToken.TrailingTrivia.Last();
if (lastTrivia.IsKind(SyntaxKind.EndOfLineTrivia))
{
needsNewLine = false;
}
else
{
needsNewLine = true;
}
}
if (needsNewLine)
{
var newLine = SyntaxUtil.GetBestNewLineTriviaRecursive(lastToken.Parent);
var newLastToken = lastToken.WithTrailingTrivia(lastToken.TrailingTrivia.Concat(new[] { newLine }));
return syntaxRoot.ReplaceToken(lastToken, newLastToken);
}
return syntaxRoot;
}
SyntaxNode AddNewLineToEndOfFileTokenLeadingTriviaIfNecessary(SyntaxNode syntaxRoot, SyntaxToken endofFileToken)
{
if (endofFileToken.LeadingTrivia.Last().IsKind(SyntaxKind.EndOfLineTrivia))
{
return syntaxRoot;
}
var newLine = SyntaxUtil.GetBestNewLineTriviaRecursive(endofFileToken.Parent);
var newLastToken = endofFileToken.WithTrailingTrivia(endofFileToken.TrailingTrivia.Concat(new[] { newLine }));
return syntaxRoot.ReplaceToken(endofFileToken, newLastToken);
return syntaxRoot;
}
}
}