Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
266 changes: 266 additions & 0 deletions JavaToCSharp.Tests/ConvertJava21GapTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,266 @@
namespace JavaToCSharp.Tests;

/// <summary>
/// Tests for Java constructs at or below Java 21 that previously failed to convert or converted
/// into code with different runtime behavior than the Java source.
/// </summary>
public class ConvertJava21GapTests
{
/// <summary>
/// Local records previously threw, since <c>LocalRecordDeclarationStmt</c> was missing from the
/// statement visitor registry, aborting conversion of the entire file. C# has no local record
/// declaration (the compiler reads one as a local function), so it is hoisted to the enclosing
/// type rather than left in the method body.
/// </summary>
[Fact]
public void Local_Record_Declaration_Is_Hoisted_To_The_Enclosing_Type()
{
const string javaCode = """
package com.example;
public class Shapes {
public int test() {
record Point(int x, int y) {}
Point p = new Point(1, 2);
return p.x;
}
}
""";

var parsed = Convert(javaCode);

Assert.Contains("record Point(int x, int y)", parsed);

// The declaration must sit outside the method body, after the method that declared it.
var methodStart = parsed.IndexOf("public virtual int Test()", StringComparison.Ordinal);
var recordStart = parsed.IndexOf("record Point", StringComparison.Ordinal);
var methodEnd = parsed.IndexOf("return p.x;", StringComparison.Ordinal);

Assert.True(methodStart >= 0 && recordStart > methodEnd, "The local record must be hoisted out of the method body.");
}

/// <summary>
/// A method reference is a method group, not a call. Emitting an invocation would call the
/// method at the point of reference instead of passing it as a delegate.
/// </summary>
[Fact]
public void Method_Reference_Is_Converted_To_A_Method_Group()
{
const string javaCode = """
package com.example;
import java.util.List;
import java.util.function.Function;
public class Shapes {
public Function<String, Integer> test(List<String> items) {
items.forEach(System.out::println);
return String::length;
}
}
""";

var parsed = Convert(javaCode);

Assert.Contains("return string.Length;", parsed);
Assert.DoesNotContain("string.Length()", parsed);
}

/// <summary>
/// C# has no constructor-reference syntax, so <c>Foo::new</c> becomes a lambda. Generic
/// arguments on the referenced type must survive the conversion.
/// </summary>
[Fact]
public void Constructor_Reference_Is_Converted_To_A_Lambda()
{
const string javaCode = """
package com.example;
import java.util.ArrayList;
import java.util.function.Supplier;
public class Shapes {
public Supplier<ArrayList<String>> test() {
return ArrayList<String>::new;
}
}
""";

var parsed = Convert(javaCode);

Assert.Contains("() => new List<string>()", parsed);
}

/// <summary>
/// A static import names the declaring type, so the type must be retained and the directive
/// emitted as <c>using static</c>. Treating it as a namespace import dropped the type name.
/// </summary>
[Fact]
public void Static_Import_Is_Converted_To_A_Using_Static()
{
const string javaCode = """
package com.example;
import static java.lang.Math.max;
public class Shapes {
public int test(int a, int b) {
return max(a, b);
}
}
""";

var parsed = Convert(javaCode);

Assert.Contains("using static Java.Lang.Math;", parsed);
}

/// <summary>
/// A non-static import must keep converting to a plain namespace using, with the class name
/// stripped off.
/// </summary>
[Fact]
public void Non_Static_Import_Remains_A_Namespace_Using()
{
const string javaCode = """
package com.example;
import java.util.List;
public class Shapes {
public int test(List<String> items) {
return items.size();
}
}
""";

var parsed = Convert(javaCode);

Assert.Contains("using Java.Util;", parsed);
Assert.DoesNotContain("using static", parsed);
}

/// <summary>
/// Java runs an instance initializer at the start of every constructor. It was previously
/// emitted as a static constructor, which runs once per type rather than once per instance.
/// </summary>
[Fact]
public void Instance_Initializer_Is_Prepended_To_Each_Constructor()
{
const string javaCode = """
package com.example;
public class Shapes {
private int x;
{ x = 42; }
public Shapes() { }
public Shapes(int y) { this.x = y; }
}
""";

var parsed = Convert(javaCode);

Assert.DoesNotContain("static Shapes()", parsed);

// Both constructors run the initializer, and it runs before the constructor's own body so a
// constructor parameter still wins over the initialized value.
var body = parsed[parsed.IndexOf("public Shapes(int y)", StringComparison.Ordinal)..];
Assert.Contains("x = 42;", body);
Assert.True(
body.IndexOf("x = 42;", StringComparison.Ordinal) < body.IndexOf("this.x = y;", StringComparison.Ordinal),
"The instance initializer must run before the constructor body.");
}

/// <summary>
/// A constructor chaining to <c>this(...)</c> must not re-run the initializer, since it already
/// ran in the constructor being chained to.
/// </summary>
[Fact]
public void Instance_Initializer_Is_Not_Repeated_In_A_Chained_Constructor()
{
const string javaCode = """
package com.example;
public class Shapes {
private int x;
{ x = 42; }
public Shapes(int y) { this.x = y; }
public Shapes(String s) { this(s.length()); }
}
""";

var parsed = Convert(javaCode);

var chained = parsed[parsed.IndexOf("public Shapes(string s)", StringComparison.Ordinal)..];
Assert.DoesNotContain("x = 42;", chained);
}

/// <summary>
/// A class with an instance initializer but no declared constructor needs one synthesized,
/// otherwise the initializer would be dropped.
/// </summary>
[Fact]
public void Instance_Initializer_Without_A_Constructor_Synthesizes_One()
{
const string javaCode = """
package com.example;
public class Shapes {
private int x;
{ x = 42; }
}
""";

var parsed = Convert(javaCode);

Assert.Contains("public Shapes()", parsed);
Assert.Contains("x = 42;", parsed);
}

/// <summary>
/// Static initializers must still become static constructors.
/// </summary>
[Fact]
public void Static_Initializer_Remains_A_Static_Constructor()
{
const string javaCode = """
package com.example;
public class Shapes {
private static int x;
static { x = 42; }
}
""";

var parsed = Convert(javaCode);

Assert.Contains("static Shapes()", parsed);
}

/// <summary>
/// Asserts on the converted form of every method reference kind in the integration resource.
/// That resource is conversion-only, since java.util.function has no BCL delegate mapping and
/// so its output cannot be compiled and run by the integration harness.
/// </summary>
[Fact]
public void Method_Reference_Resource_Converts_Every_Reference_Kind()
{
var parsed = Convert(File.ReadAllText("Resources/Java8MethodReferences.java"));

// Instance method of a type, and of a particular object.
Assert.Contains("return string.Length;", parsed);
Assert.Contains("return this.Upper;", parsed);

// Static method.
Assert.Contains("return Java8MethodReferences.Add;", parsed);

// Constructor reference, keeping the generic argument.
Assert.Contains("() => new List<string>()", parsed);

// No method reference may become an invocation.
Assert.DoesNotContain("string.Length()", parsed);
Assert.DoesNotContain("Java8MethodReferences.Add()", parsed);
}

private static string Convert(string javaCode, bool allowWarnings = false)
{
var options = new JavaConversionOptions { IncludeComments = false };

options.WarningEncountered += (_, eventArgs) =>
{
if (!allowWarnings)
{
throw new InvalidOperationException($"Encountered a warning in conversion: {eventArgs.Message}");
}
};

return JavaToCSharpConverter.ConvertText(javaCode, options) ?? "";
}
}
5 changes: 5 additions & 0 deletions JavaToCSharp.Tests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ public class IntegrationTests(ITestOutputHelper testOutputHelper)
[InlineData("Resources/Java11LambdaInference.java")]
[InlineData("Resources/MultidimensionalArrays.java", true)]
[InlineData("Resources/Java17SealedClasses.java", true)]
// Conversion-only: java.util.function has no BCL delegate mapping, so the output cannot be run.
[InlineData("Resources/Java8MethodReferences.java")]
public void GeneralSuccessfulConversionTest(string filePath, bool allowWarnings = false)
{
var options = new JavaConversionOptions
Expand Down Expand Up @@ -82,6 +84,9 @@ public void GeneralUnsuccessfulConversionTest(string filePath)
[InlineData("Resources/BooleanArrays.java")]
[InlineData("Resources/BinaryLiterals.java")]
[InlineData("Resources/NestedEnumStaticUsing.java")]
[InlineData("Resources/Java16LocalRecords.java")]
[InlineData("Resources/InstanceInitializers.java")]
[InlineData("Resources/StaticImports.java")]
public void FullIntegrationTests(string filePath, bool allowWarnings = false)
{
var options = new JavaConversionOptions
Expand Down
75 changes: 75 additions & 0 deletions JavaToCSharp.Tests/Resources/InstanceInitializers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/// Expect:
/// - output: "a: count=1 tag=init\nb: count=2 tag=x\nc: count=2 tag=x-y\nd: count=1 tag=init\nstatic=7\n"
package example;

// Instance initializer blocks run at the start of every constructor that does not chain to another
// constructor of the same class. A constructor that chains via this(...) must not re-run them.
public class Program {
static int staticValue;

static {
staticValue = 7;
}

public static class Counter {
public String tag;
public int count;

// Two separate initializer blocks, to verify both run and in declaration order.
{
tag = "init";
}

{
count = 1;
}

public Counter() {
}

public Counter(String first) {
tag = first;
count = 2;
}

// Chains to Counter(String), so the initializers already ran there and must not run again.
public Counter(String first, String second) {
this(first);
tag = tag + "-" + second;
}
}

// A class with an initializer but no declared constructor needs one synthesized, or the
// initializer would be dropped entirely.
public static class Implicit {
public String tag;
public int count;

{
tag = "init";
count = 1;
}
}

public static void describe(String label, int count, String tag) {
System.out.println(label + ": count=" + count + " tag=" + tag);
}

public static void main(String[] args) {
Counter a = new Counter();
describe("a", a.count, a.tag);

Counter b = new Counter("x");
describe("b", b.count, b.tag);

// count stays 2 rather than resetting to 1, because the chained constructor did not re-run
// the initializer.
Counter c = new Counter("x", "y");
describe("c", c.count, c.tag);

Implicit d = new Implicit();
describe("d", d.count, d.tag);

System.out.println("static=" + staticValue);
}
}
36 changes: 36 additions & 0 deletions JavaToCSharp.Tests/Resources/Java16LocalRecords.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/// Expect:
/// - output: "area=6\npair=1,2\nsame=True\nnested=9\n"
package example;

// Java 16 local records (JEP 395) may be declared in a method body. C# has no local record
// declaration, so they are hoisted to the enclosing type.
public class Program {
public static int scale(int value) {
// A local record in a second method, to verify each is hoisted independently.
record Factor(int amount) {
}

Factor f = new Factor(3);
return value * f.amount;
}

public static void main(String[] args) {
record Rect(int width, int height) {
}

Rect r = new Rect(2, 3);
System.out.println("area=" + (r.width * r.height));

// A second local record in the same method, to verify both are hoisted.
record Pair(int left, int right) {
}

Pair p = new Pair(1, 2);
System.out.println("pair=" + p.left + "," + p.right);

// Records have value equality in both languages.
System.out.println("same=" + p.equals(new Pair(1, 2)));

System.out.println("nested=" + scale(3));
}
}
Loading
Loading