Skip to content

[src] Improve generics support. #22527

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 30, 2025
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
11 changes: 9 additions & 2 deletions src/Foundation/NSEnumerator_1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
namespace Foundation {
[Register ("NSEnumerator", SkipRegistration = true)]
public sealed class NSEnumerator<TKey> : NSEnumerator
where TKey : class, INativeObject {
where TKey : INativeObject {
#if !NET
public NSEnumerator ()
{
Expand All @@ -53,7 +53,14 @@ internal NSEnumerator (NativeHandle handle)

public new TKey NextObject ()
{
return (TKey) (object) base.NextObject ();
var nextObject = base.NextObject ();
if (nextObject is null)
return default (TKey)!;
if (nextObject is TKey rv)
return rv;
var rv2 = Runtime.GetINativeObject<TKey> (nextObject.GetHandle (), false)!;
GC.KeepAlive (nextObject);
return rv2;
}
}
}
6 changes: 3 additions & 3 deletions src/ObjCRuntime/DynamicRegistrar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -570,17 +570,17 @@ public override bool VerifyIsConstrainedToNSObject (Type type, out Type constrai
return true;

if (type.IsGenericParameter) {
if (typeof (NSObject).IsAssignableFrom (type)) {
if (typeof (INativeObject).IsAssignableFrom (type)) {
// First look for a more specific constraint
var constraints = type.GetGenericParameterConstraints ();
foreach (var constraint in constraints) {
if (constraint.IsSubclassOf (typeof (NSObject))) {
if (constraint.IsSubclassOf (typeof (INativeObject))) {
constrained_type = constraint;
return true;
}
}
// Fallback to NSObject.
constrained_type = typeof (NSObject);
constrained_type = typeof (INativeObject);
return true;
}
return false;
Expand Down
8 changes: 4 additions & 4 deletions src/ObjCRuntime/RegistrarHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,18 +228,18 @@ internal static uint LookupRegisteredTypeId (Type type)
}

internal static T? ConstructNSObject<T> (Type type, NativeHandle nativeHandle)
where T : class, INativeObject
where T : INativeObject
{
if (!TryGetMapEntry (type.Assembly.GetName ().Name!, out var entry))
return null;
return default (T);
return (T?) entry.Registrar.ConstructNSObject (type.TypeHandle, nativeHandle);
}

internal static T? ConstructINativeObject<T> (Type type, NativeHandle nativeHandle, bool owns)
where T : class, INativeObject
where T : INativeObject
{
if (!TryGetMapEntry (type.Assembly.GetName ().Name!, out var entry))
return null;
return default (T);
return (T?) entry.Registrar.ConstructINativeObject (type.TypeHandle, nativeHandle, owns);
}

Expand Down
28 changes: 16 additions & 12 deletions src/ObjCRuntime/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1421,7 +1421,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM
}

// The generic argument T is only used to cast the return value.
static T? ConstructINativeObject<T> (IntPtr ptr, bool owns, Type type, MissingCtorResolution missingCtorResolution, IntPtr sel, RuntimeMethodHandle method_handle) where T : class, INativeObject
static T? ConstructINativeObject<T> (IntPtr ptr, bool owns, Type type, MissingCtorResolution missingCtorResolution, IntPtr sel, RuntimeMethodHandle method_handle) where T : INativeObject
{
if (type is null)
throw new ArgumentNullException (nameof (type));
Expand All @@ -1431,7 +1431,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM

if (Runtime.IsManagedStaticRegistrar) {
var nativeHandle = new NativeHandle (ptr);
T? instance = null;
T? instance = default (T);

// We want to create an instance of `type` and if we have the chance to use the factory method
// on the generic type, we will prefer it to using the lookup table.
Expand All @@ -1446,7 +1446,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM
// fall back to the lookup tables and we need to stop here.
if (type.IsGenericType && instance is null) {
CannotCreateManagedInstanceOfGenericType (ptr, IntPtr.Zero, type, missingCtorResolution, sel, method_handle);
return null;
return default (T);
}

// If we couldn't create an instance of T through the factory method, we'll use the lookup table
Expand Down Expand Up @@ -1481,7 +1481,7 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM

if (ctor is null) {
MissingCtor (ptr, IntPtr.Zero, type, missingCtorResolution, sel, method_handle);
return null;
return default (T);
}

var ctorArguments = new object [2];
Expand All @@ -1501,7 +1501,12 @@ static void AppendAdditionalInformation (StringBuilder msg, IntPtr sel, RuntimeM
//
// When the same call is made from a separate function, it works fine.
static T? ConstructINativeObjectViaFactoryMethod (NativeHandle nativeHandle, bool owns)
=> T._Xamarin_ConstructINativeObject (nativeHandle, owns) as T;
{
var rv = T._Xamarin_ConstructINativeObject (nativeHandle, owns);
if (rv is T t)
return t;
return default (T);
}
}

static IntPtr CreateNSObject (IntPtr type_gchandle, IntPtr handle, NSObject.Flags flags)
Expand Down Expand Up @@ -1956,29 +1961,28 @@ static Type LookupINativeObjectImplementation (IntPtr ptr, Type target_type, Typ
/// <remarks>
/// <para>Returns an instance of the specified type even if the native object is not in the class hierarchy of type (there are no type checks).</para>
/// </remarks>
public static T? GetINativeObject<T> (IntPtr ptr, bool owns) where T : class, INativeObject
public static T? GetINativeObject<T> (IntPtr ptr, bool owns) where T : INativeObject
{
return GetINativeObject<T> (ptr, false, owns);
}

public static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, bool owns) where T : class, INativeObject
public static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, bool owns) where T : INativeObject
{
return GetINativeObject<T> (ptr, forced_type, null, owns);
}

internal static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, Type? implementation, bool owns) where T : class, INativeObject
internal static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, Type? implementation, bool owns) where T : INativeObject
{
return GetINativeObject<T> (ptr, forced_type, implementation, owns, IntPtr.Zero, default (RuntimeMethodHandle));
}

static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, Type? implementation, bool owns, IntPtr sel, RuntimeMethodHandle method_handle) where T : class, INativeObject
static T? GetINativeObject<T> (IntPtr ptr, bool forced_type, Type? implementation, bool owns, IntPtr sel, RuntimeMethodHandle method_handle) where T : INativeObject
{
if (ptr == IntPtr.Zero)
return null;
return default (T);

var o = TryGetNSObject (ptr, evenInFinalizerQueue: false);
var t = o as T;
if (t is not null) {
if (o is T t) {
// found an existing object with the right type.
if (owns)
TryReleaseINativeObject (t);
Expand Down
33 changes: 23 additions & 10 deletions src/bgen/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5725,21 +5725,34 @@ public void Generate (Type type)
class_name += TypeManager.FormatType (type, gargs [i]);

where_list += "\n\t\twhere " + gargs [i].Name + " : ";

var constraintList = new List<string> ();

var genericAttributes = gargs [i].GenericParameterAttributes;
if (genericAttributes.HasFlag (GenericParameterAttributes.ReferenceTypeConstraint)) {
constraintList.Add ("class");
genericAttributes &= ~GenericParameterAttributes.ReferenceTypeConstraint;
}
if (genericAttributes.HasFlag (GenericParameterAttributes.DefaultConstructorConstraint)) {
constraintList.Add ("new()");
genericAttributes &= ~GenericParameterAttributes.DefaultConstructorConstraint;
}
if (genericAttributes != GenericParameterAttributes.None) {
exceptions.Add (ErrorHelper.CreateError (99, $"Unexpected generic constraint attributes: {genericAttributes}"));
}

var constraints = gargs [i].GetGenericParameterConstraints ();
if (constraints.Length > 0) {
var comma = string.Empty;
if (IsProtocol (constraints [0])) {
where_list += "NSObject";
comma = ", ";
}
if (IsProtocol (constraints [0]))
constraintList.Add ("NSObject");

for (int c = 0; c < constraints.Length; c++) {
where_list += comma + TypeManager.FormatType (type, constraints [c]);
comma = ", ";
}
for (int c = 0; c < constraints.Length; c++)
constraintList.Add (TypeManager.FormatType (type, constraints [c]));
} else {
where_list += "NSObject";
constraintList.Add ("NSObject");
}

where_list += string.Join (", ", constraintList);
}
class_name += ">";
if (where_list.Length > 0)
Expand Down
59 changes: 59 additions & 0 deletions tests/bindings-test/ApiDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -513,4 +513,63 @@ interface SwiftTestClass2 {
[Export ("SayHello2")]
string SayHello2 ();
}

[Protocol]
interface VeryGenericElementProtocol {
[Export ("when", ArgumentSemantic.Retain)]
NSDate When { get; }
}

interface IVeryGenericElementProtocol : INativeObject { }

[Protocol]
interface VeryGenericElementProtocol1 : VeryGenericElementProtocol {
[Export ("number")]
nint Number { get; }
}

interface IVeryGenericElementProtocol1 : IVeryGenericElementProtocol { }

[Protocol]
interface VeryGenericElementProtocol2 : VeryGenericElementProtocol {
[Export ("animal", ArgumentSemantic.Retain)]
string Animal { get; }
}

interface IVeryGenericElementProtocol2 : IVeryGenericElementProtocol { }

[BaseType (typeof (NSObject))]
interface VeryGenericCollection<Key, Element>
where Key : NSString
where Element : IVeryGenericElementProtocol {
[Export ("count")]
nuint Count { get; }

[Export ("getElement:"), NullAllowed]
Element GetElement (Key key);

[Export ("elementEnumerator"), NullAllowed]
NSEnumerator<Element> GetEnumerator ();

[Export ("add:")]
void Add (Element element);
}

[Protocol]
interface VeryGenericConsumerProtocol {
[Export ("first", ArgumentSemantic.Retain)]
VeryGenericCollection<NSString, IVeryGenericElementProtocol1> First { get; }

[Export ("second", ArgumentSemantic.Retain)]
VeryGenericCollection<NSString, IVeryGenericElementProtocol2> Second { get; }
}

interface IVeryGenericConsumerProtocol { }

[BaseType (typeof (NSObject))]
interface VeryGenericFactory {
[Export ("getConsumer")]
[Static]
IVeryGenericConsumerProtocol GetConsumer ();
}
}
24 changes: 24 additions & 0 deletions tests/bindings-test/RuntimeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,5 +132,29 @@ public void SwiftTestClass2 ()
using var obj = new SwiftTestClass2 ();
Assert.AreEqual ("Hello from Swift 2", obj.SayHello2 (), "Hello");
}

[Test]
public void VeryGeneric ()
{
Assert.Multiple (() => {
using var obj = VeryGenericFactory.GetConsumer ();

using var first = obj.First;
Assert.That (first, Is.Not.Null, "first");
Assert.That ((int) first.Count, Is.EqualTo (1), "first Count");
var firstObject = first.GetElement ((NSString) "whatever");
Assert.That (firstObject, Is.Not.Null, "first element 1");
Assert.That ((int) firstObject.Number, Is.EqualTo (42), "first element 1 - number");
Assert.That (firstObject.When.SecondsSince1970, Is.EqualTo (-62135769600d), "first element 1 - when");

using var second = obj.Second;
Assert.That (second, Is.Not.Null, "second");
Assert.That ((int) second.Count, Is.EqualTo (1), "second Count");
var secondObject = second.GetElement ((NSString) "whatever");
Assert.That (secondObject, Is.Not.Null, "second element 1");
Assert.That (secondObject.Animal, Is.EqualTo ("Sand cat"), "second element 1 - animal");
Assert.That (secondObject.When.SecondsSince1970, Is.EqualTo (64092211200d), "second element 1 - when");
});
}
}
}
32 changes: 32 additions & 0 deletions tests/test-libraries/libtest.h
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,38 @@ typedef void (^outerBlock) (innerBlock callback);

@end

// VeryGeneric stuff

@protocol VeryGenericElementProtocol <NSObject>
@property (retain, readonly) NSDate * when;
@end

@protocol VeryGenericElementProtocol1 <VeryGenericElementProtocol>
@property (readonly) NSInteger number;
@end

@protocol VeryGenericElementProtocol2 <VeryGenericElementProtocol>
@property (retain, readonly) NSString * animal;
@end

@interface VeryGenericCollection<Key: NSString*, __covariant Element: id<VeryGenericElementProtocol>> : NSObject <NSFastEnumeration>
@property (retain) Element element;
@property () NSUInteger count;
- (Element _Nullable)getElement:(Key)alias;
- (NSEnumerator<Element> *)elementEnumerator;
- (void) add: (Element) value;
@end

@protocol VeryGenericConsumerProtocol <NSObject>
@property (retain, readonly) VeryGenericCollection<NSString *, id<VeryGenericElementProtocol1>> *first;
@property (retain, readonly) VeryGenericCollection<NSString *, id<VeryGenericElementProtocol2>> *second;
@end

@interface VeryGenericFactory : NSObject {
}
+(id<VeryGenericConsumerProtocol>) getConsumer;
@end

#pragma clang diagnostic pop
// NS_ASSUME_NONNULL_END

Expand Down
Loading
Loading