Skip to content

Commit ebc6002

Browse files
authored
Avoid repeated comments in subclasses, fix #88 (#126)
1 parent adae786 commit ebc6002

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

JavaToCSharp.Tests/CommentTests.cs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,4 +102,68 @@ public class Foo
102102

103103
Assert.Equal(expected.ReplaceLineEndings(), parsed.ReplaceLineEndings());
104104
}
105+
106+
[Theory]
107+
[InlineData("Child", "Child")]
108+
[InlineData("Child extends Parent", "Child : Parent")]
109+
[InlineData("Child implements Parent", "Child : Parent")]
110+
[InlineData("Child extends Parent implements IParent", "Child : Parent, IParent")]
111+
112+
[InlineData("Parent<T>", "Parent<T>")]
113+
[InlineData("Child<T extends BoundType<T>>", "Child<T>")] // issue #125, should add: where T : BoundType<T>
114+
[InlineData("Child extends Parent<BoundType>", "Child : Parent<BoundType>")]
115+
public void CommentsInsideClass_ShouldNotBeDuplicated_Fix_88(string javaClass, string csharpClass)
116+
{
117+
string javaCode = $$"""
118+
//class comment
119+
public class {{javaClass}} {
120+
//before comment 1
121+
public void method1() {
122+
doSomething(); //after comment1
123+
}
124+
//before comment 2
125+
public void method1() {
126+
doSomething(); //after comment2
127+
}
128+
//before comment 3
129+
public void method1() {
130+
}
131+
}
132+
""";
133+
var options = new JavaConversionOptions
134+
{
135+
IncludeUsings = false,
136+
IncludeNamespace = false,
137+
};
138+
139+
var parsed = JavaToCSharpConverter.ConvertText(javaCode, options) ?? "";
140+
141+
testOutputHelper.WriteLine(parsed);
142+
143+
string expected = $$"""
144+
//class comment
145+
public class {{csharpClass}}
146+
{
147+
//before comment 1
148+
public virtual void Method1()
149+
{
150+
DoSomething(); //after comment1
151+
}
152+
153+
//before comment 2
154+
public virtual void Method1()
155+
{
156+
DoSomething(); //after comment2
157+
}
158+
159+
//before comment 3
160+
public virtual void Method1()
161+
{
162+
}
163+
}
164+
165+
""";
166+
167+
Assert.Equal(expected.ReplaceLineEndings(), parsed.ReplaceLineEndings());
168+
}
105169
}

JavaToCSharp/CommentsHelper.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,7 @@ private static bool HasNextSibling(JavaAst.Node parentNode, JavaParser.Position
232232
return parentNode.getChildNodes()
233233
.OfType<JavaAst.Node>()
234234
.Where(sibling => sibling is not JavaComments.Comment)
235+
.OrderBy(sibling => sibling.getEnd().FromOptional<JavaParser.Position>()) // fix #88
235236
.LastOrDefault(sibling =>
236237
{
237238
var siblingEnd = sibling.getEnd().FromOptional<JavaParser.Position>();

0 commit comments

Comments
 (0)