forked from paulirwin/JavaToCSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSyntaxNodeExtensions.cs
More file actions
51 lines (46 loc) · 2.02 KB
/
Copy pathSyntaxNodeExtensions.cs
File metadata and controls
51 lines (46 loc) · 2.02 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
using System.Collections.Generic;
using System.Linq;
using com.github.javaparser.ast;
using com.github.javaparser.ast.comments;
using com.github.javaparser.ast.stmt;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace JavaToCSharp
{
public static class SyntaxNodeExtensions
{
public static T AddComment<T>(this T syntax, ConversionContext context, Node node) where T : SyntaxNode
{
if (context.Options.IncludeComments)
{
var comment = (node as Comment) ?? node.getComment();
if (comment != null)
{
// Get the orphaned comments directly above the node
var leadingComments =
node.getParentNode()?.getChildrenNodes().AsEnumerable<Node>()
.Where(n => n.isPositionedBefore(node.getBeginLine(), node.getBeginColumn()))
.OrderByDescending(n => n.getBeginLine())
.TakeWhile(n => (n as Comment)?.isOrphan() ?? false)
.Cast<Comment>()
.Reverse();
// See if the comment is before or after the node
var isLeadingComment = comment.getBeginLine() < node.getBeginLine() ||
comment.getBeginLine() == node.getBeginLine() && comment.getEndColumn() <= node.getBeginColumn();
if (!isLeadingComment)
{
syntax = syntax.WithTrailingTrivia(SyntaxFactory.Comment(comment.toString().TrimStart('\r', '\n')));
}
else
{
leadingComments = leadingComments.Concat(new[] {comment});
}
syntax =
syntax.WithLeadingTrivia(
leadingComments.Select(c => SyntaxFactory.Comment(c.toString().TrimEnd('\r', '\n'))));
}
}
return syntax;
}
}
}