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
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,10 @@ static void WriteConstructors (JavaPeerInfo type, TextWriter writer)
string parameters = FormatParameterList (ctorParams);
string superArgs = ctor.SuperArgumentsString ?? FormatArgumentList (ctorParams);
string args = FormatArgumentList (ctorParams);
string throwsClause = FormatThrowsClause (ctor.ThrownNames);

writer.Write ($$"""
public {{simpleClassName}} ({{parameters}})
public {{simpleClassName}} ({{parameters}}){{throwsClause}}
{
super ({{superArgs}});

Expand Down Expand Up @@ -251,10 +252,7 @@ static void WriteMethods (JavaPeerInfo type, TextWriter writer)
string returnPrefix = isVoid ? "" : "return ";

// throws clause for [Export] methods
string throwsClause = "";
if (method.ThrownNames != null && method.ThrownNames.Count > 0) {
throwsClause = $"\n\t\tthrows {string.Join (", ", method.ThrownNames)}";
}
string throwsClause = FormatThrowsClause (method.ThrownNames);

if (method.Connector != null && !method.IsExport) {
writer.Write ($$"""
Expand Down Expand Up @@ -309,6 +307,19 @@ static void WriteClassClose (TextWriter writer)
writer.WriteLine ('}');
}

static string FormatThrowsClause (IReadOnlyList<string>? thrownNames)
{
if (thrownNames == null || thrownNames.Count == 0) {
return "";
}

var javaNames = new string [thrownNames.Count];
for (int i = 0; i < thrownNames.Count; i++) {
javaNames [i] = JniSignatureHelper.JniNameToJavaName (thrownNames [i]);
}
return $"\n\t\tthrows {string.Join (", ", javaNames)}";
}

static string FormatParameterList (IReadOnlyList<JniParameterInfo> parameters)
{
if (parameters.Count == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,12 @@ public sealed record JavaConstructorInfo
/// </summary>
public string? SuperArgumentsString { get; init; }

/// <summary>
/// For [Export] constructors: Java exception types that the constructor declares it can throw.
/// Null for [Register] constructors.
/// </summary>
public IReadOnlyList<string>? ThrownNames { get; init; }

/// <summary>
/// Managed constructor parameter types, in declaration order.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2479,6 +2479,7 @@ List<JavaConstructorInfo> BuildJavaConstructors (List<MarshalMethodInfo> marshal
JniSignature = mm.JniSignature,
ConstructorIndex = ctorIndex,
SuperArgumentsString = mm.SuperArgumentsString,
ThrownNames = mm.ThrownNames,
HasMatchingManagedCtor = managedParams != null,
ManagedParameterTypes = managedParams ?? [],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,23 @@ internal bool ValidateJavaNames (IReadOnlyList<JavaPeerInfo> peers, string? appl
}
foreach (var constructor in peer.JavaConstructors) {
ValidateJniSignature (constructor.JniSignature);
if (constructor.ThrownNames is not null) {
foreach (var thrownName in constructor.ThrownNames) {
var javaThrownName = JniSignatureHelper.JniNameToJavaName (thrownName);
if (JavaNameValidator.TryGetInvalidJavaSourceTypeSegment (javaThrownName, out invalidIdentifier)) {
ReportInvalidName (thrownName, invalidIdentifier);
}
}
}
}
foreach (var method in peer.MarshalMethods) {
if (!method.IsConstructor) {
ValidateJniSignature (method.JniSignature);
}
if (method.ThrownNames is not null) {
foreach (var thrownName in method.ThrownNames) {
if (JavaNameValidator.TryGetInvalidJavaSourceTypeSegment (thrownName, out invalidIdentifier)) {
var javaThrownName = JniSignatureHelper.JniNameToJavaName (thrownName);
if (JavaNameValidator.TryGetInvalidJavaSourceTypeSegment (javaThrownName, out invalidIdentifier)) {
ReportInvalidName (thrownName, invalidIdentifier);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ static string UserTypesFixturePath {
}

static MarshalMethodInfo[] GetMarshalMethods (string javaName)
{
return GetPeer (javaName).MarshalMethods.ToArray ();
}

static JavaPeerInfo GetPeer (string javaName)
{
var fixturePath = UserTypesFixturePath;
var dir = AssertNotNull (Path.GetDirectoryName (fixturePath));
Expand All @@ -53,7 +58,7 @@ static MarshalMethodInfo[] GetMarshalMethods (string javaName)

var peers = scanner.Scan (assemblies);
var peer = peers.FirstOrDefault (p => p.ManagedTypeName.EndsWith (javaName));
return AssertNotNull (peer).MarshalMethods.ToArray ();
return AssertNotNull (peer);
} finally {
foreach (var pe in peReaders)
pe.Dispose ();
Expand Down Expand Up @@ -120,6 +125,16 @@ public void Export_WithThrowsClause_SurfacesDeclaredExceptions ()
Assert.Contains ("java/lang/IllegalStateException", multiThrownNames);
}

[Fact]
public void ExportConstructor_WithThrowsClause_SurfacesDeclaredExceptions ()
{
var peer = GetPeer ("ExportThrowsShapes");
var constructor = Assert.Single (peer.JavaConstructors);
var thrownNames = AssertNotNull (constructor.ThrownNames);

Assert.Equal (["java/io/IOException", "java/lang/IllegalStateException"], thrownNames);
}

[Fact]
public void MixedRegisterAndExport_BothPathsSurface ()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,9 @@ public class StaticExportShapes : Java.Lang.Object
// A.2: [Export(Throws = ...)] — declared exceptions in JNI signature.
public class ExportThrowsShapes : Java.Lang.Object
{
[Export (Throws = new [] { typeof (Java.IO.IOException), typeof (Java.Lang.IllegalStateException) }, SuperArgumentsString = "")]
public ExportThrowsShapes () { }

[Export ("ioCall", Throws = new [] { typeof (Java.IO.IOException) })]
public void IoCall () { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,13 @@ public void Generate_ExportWithThrows_HasThrowsClause ()
AssertContainsLine ("throws java.io.IOException, java.lang.IllegalStateException\n", java);
}

[Fact]
public void Generate_ExportConstructorWithThrows_HasThrowsClause ()
{
var java = GenerateFixture ("my/app/ExportWithThrows");
AssertContainsLine ("public ExportWithThrows ()\n\t\tthrows java.io.IOException, java.lang.IllegalStateException\n", java);
}

}

public class StaticExportMethods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ public void ValidateJavaNames_ReservedEmittedTypeReferences_LogErrors ()
new JavaConstructorInfo {
JniSignature = "(Lcom/example/Outer$for;)V",
ConstructorIndex = 0,
ThrownNames = ["com/example/Outer$permits"],
},
],
MarshalMethods = [
Expand All @@ -188,7 +189,7 @@ public void ValidateJavaNames_ReservedEmittedTypeReferences_LogErrors ()
JniSignature = "([Lcom/example/Outer$record;)Lcom/example/Outer$yield;",
ManagedMethodName = "Method",
NativeCallbackName = "n_method",
ThrownNames = ["com.example.Outer.permits"],
ThrownNames = ["com/example/Outer$sealed"],
},
],
JavaFields = [
Expand All @@ -206,7 +207,8 @@ public void ValidateJavaNames_ReservedEmittedTypeReferences_LogErrors ()
Assert.Contains (logMessages, message => message.Contains ("Java name 'com/example/Outer$for' contains reserved Java identifier 'for'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com/example/Outer$record' contains reserved Java identifier 'record'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com/example/Outer$yield' contains reserved Java identifier 'yield'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com.example.Outer.permits' contains reserved Java identifier 'permits'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com/example/Outer$permits' contains reserved Java identifier 'permits'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com/example/Outer$sealed' contains reserved Java identifier 'sealed'."));
Assert.Contains (logMessages, message => message.Contains ("Java name 'com.example.Outer.sealed' contains reserved Java identifier 'sealed'."));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,11 +178,12 @@ public sealed class ContentProviderAttribute : Attribute, Java.Interop.IJniNameP

namespace Java.Interop
{
[AttributeUsage (AttributeTargets.Method, AllowMultiple = false)]
[AttributeUsage (AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = false)]
public sealed class ExportAttribute : Attribute
{
public string? Name { get; set; }
public string[]? ThrownNames { get; set; }
public string? SuperArgumentsString { get; set; }

public ExportAttribute () { }
public ExportAttribute (string name) => Name = name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1244,6 +1244,9 @@ public class ExportWithThrows : Java.Lang.Object
{
protected ExportWithThrows (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) { }

[Java.Interop.Export (SuperArgumentsString = "", ThrownNames = new [] { "java.io.IOException", "java.lang.IllegalStateException" })]
public ExportWithThrows () { }

[Java.Interop.Export ("riskyMethod", ThrownNames = new [] { "java.io.IOException", "java.lang.IllegalStateException" })]
public void RiskyMethod () { }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ public void JavaSideThrowingConstructorPropagatesException ()
Assert.IsTrue (exception.ToString ().Contains (ConstructorActivationThrowing.ExceptionMessage));
}

[Test]
[Category ("ConstructorParity")]
public void JavaSideExportConstructorWithThrowsRunsOnce ()
{
ConstructorActivationWithThrows.Reset ();

using (var instance = CreateFromJava<ConstructorActivationWithThrows> ("()V")) {
Assert.AreEqual (1, ConstructorActivationWithThrows.ConstructorInvocations);
AssertRegisteredSame (instance);
}
}

[Test]
public void JavaSideContextConstructorForwardsArgument ()
{
Expand Down Expand Up @@ -796,6 +808,23 @@ public static void Reset ()
}
}

[Register ("net/dot/android/test/ConstructorActivationWithThrows")]
public class ConstructorActivationWithThrows : Java.Lang.Object
{
public static int ConstructorInvocations;

[Export (SuperArgumentsString = "", Throws = new [] { typeof (Java.IO.IOException) })]
public ConstructorActivationWithThrows ()
{
ConstructorInvocations++;
}

public static void Reset ()
{
ConstructorInvocations = 0;
}
}

[Register ("net/dot/android/test/ConstructorActivationBase", DoNotGenerateAcw = true)]
public class ConstructorActivationBase : Java.Lang.Object
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,29 @@ public void NewClosedGenericTypeWorks ()
}
}

[Test]
[Category ("ConstructorParity")]
public void ExistingJavaObjectWrapsAsKnownClosedGenericType ()
{
GenericHolder<int>.ActivationConstructorInvocations = 0;

IntPtr handle = JNIEnv.CreateInstance (typeof (GenericHolder<int>), "()V");
try {
using var first = Java.Lang.Object.GetObject<GenericHolder<int>> (handle, JniHandleOwnership.DoNotTransfer);
var second = Java.Lang.Object.GetObject<GenericHolder<int>> (handle, JniHandleOwnership.DoNotTransfer);
try {
Assert.IsNotNull (first);
Assert.AreSame (first, second);
Assert.AreEqual (1, GenericHolder<int>.ActivationConstructorInvocations);
} finally {
if (!ReferenceEquals (first, second))
second?.Dispose ();
}
} finally {
JNIEnv.DeleteLocalRef (handle);
}
}

[Test]
public void NewObjectArrayWithNullArray ()
{
Expand Down Expand Up @@ -686,6 +709,18 @@ public MultiCtorActivatedFromJava (Java.Lang.Throwable cause)

class GenericHolder<T> : Java.Lang.Object {

public static int ActivationConstructorInvocations;

public GenericHolder ()
{
}

protected GenericHolder (IntPtr handle, JniHandleOwnership transfer)
: base (handle, transfer)
{
ActivationConstructorInvocations++;
}

public T Value {get; set;}

}
Expand Down