From 01ce642321b103099a9cb59dd5c4b80a447c5f7d Mon Sep 17 00:00:00 2001 From: Javier <10879637+javiertuya@users.noreply.github.com> Date: Mon, 2 Sep 2024 08:16:07 +0200 Subject: [PATCH] Avoid repeated comments in subclasses, fix #88 --- JavaToCSharp.Tests/CommentTests.cs | 64 ++++++++++++++++++++++++++++++ JavaToCSharp/CommentsHelper.cs | 1 + 2 files changed, 65 insertions(+) diff --git a/JavaToCSharp.Tests/CommentTests.cs b/JavaToCSharp.Tests/CommentTests.cs index 115822b1..1b666ded 100644 --- a/JavaToCSharp.Tests/CommentTests.cs +++ b/JavaToCSharp.Tests/CommentTests.cs @@ -102,4 +102,68 @@ public class Foo Assert.Equal(expected.ReplaceLineEndings(), parsed.ReplaceLineEndings()); } + + [Theory] + [InlineData("Child", "Child")] + [InlineData("Child extends Parent", "Child : Parent")] + [InlineData("Child implements Parent", "Child : Parent")] + [InlineData("Child extends Parent implements IParent", "Child : Parent, IParent")] + + [InlineData("Parent", "Parent")] + [InlineData("Child>", "Child")] // issue #125, should add: where T : BoundType + [InlineData("Child extends Parent", "Child : Parent")] + public void CommentsInsideClass_ShouldNotBeDuplicated_Fix_88(string javaClass, string csharpClass) + { + string javaCode = $$""" + //class comment + public class {{javaClass}} { + //before comment 1 + public void method1() { + doSomething(); //after comment1 + } + //before comment 2 + public void method1() { + doSomething(); //after comment2 + } + //before comment 3 + public void method1() { + } + } + """; + var options = new JavaConversionOptions + { + IncludeUsings = false, + IncludeNamespace = false, + }; + + var parsed = JavaToCSharpConverter.ConvertText(javaCode, options) ?? ""; + + testOutputHelper.WriteLine(parsed); + + string expected = $$""" + //class comment + public class {{csharpClass}} + { + //before comment 1 + public virtual void Method1() + { + DoSomething(); //after comment1 + } + + //before comment 2 + public virtual void Method1() + { + DoSomething(); //after comment2 + } + + //before comment 3 + public virtual void Method1() + { + } + } + + """; + + Assert.Equal(expected.ReplaceLineEndings(), parsed.ReplaceLineEndings()); + } } diff --git a/JavaToCSharp/CommentsHelper.cs b/JavaToCSharp/CommentsHelper.cs index 8aacd4a9..a0b74b97 100644 --- a/JavaToCSharp/CommentsHelper.cs +++ b/JavaToCSharp/CommentsHelper.cs @@ -232,6 +232,7 @@ private static bool HasNextSibling(JavaAst.Node parentNode, JavaParser.Position return parentNode.getChildNodes() .OfType() .Where(sibling => sibling is not JavaComments.Comment) + .OrderBy(sibling => sibling.getEnd().FromOptional()) // fix #88 .LastOrDefault(sibling => { var siblingEnd = sibling.getEnd().FromOptional();