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
1 change: 1 addition & 0 deletions docs/api/ObjCRuntime/BindAsAttribute.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ NSString [] SupportedScrollModes { get; set; }
]]></code>
</example>
<para>In this example, the <c>rect</c> parameter will be bound as a managed <see cref="CoreGraphics.CGRect" />, and the return value will be bound as <c>bool?</c>.</para>
<para>In protocol and model binding definitions, this attribute is supported on parameters, but not on properties or return values.</para>
<list type="table">
<listheader>
<term>Supported combinations:</term>
Expand Down
7 changes: 3 additions & 4 deletions docs/website/binding_objc_libs.md
Original file line number Diff line number Diff line change
Expand Up @@ -871,10 +871,9 @@ The [`[BindAs]`](~/cross-platform/macios/binding/binding-types-reference.md#Bind

You can decorate methods (on return value), parameters and properties with
[`[BindAs]`](~/cross-platform/macios/binding/binding-types-reference.md#BindAsAttribute).
The only restriction is that your member **must not** be inside a
[`[Protocol]`](~/cross-platform/macios/binding/binding-types-reference.md#ProtocolAttribute)
or [`[Model]`](~/cross-platform/macios/binding/binding-types-reference.md#ModelAttribute)
interface.
In [`[Protocol]`](~/cross-platform/macios/binding/binding-types-reference.md#ProtocolAttribute)
and [`[Model]`](~/cross-platform/macios/binding/binding-types-reference.md#ModelAttribute)
interfaces, `BindAs` is supported on parameters, but not on properties or return values.

For example:

Expand Down
2 changes: 1 addition & 1 deletion docs/website/binding_types_reference_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -1054,7 +1054,7 @@ and return value.

The `[BindAsAttribute]` allows binding `NSNumber`, `NSValue` and `NSString`(enums) into more accurate C# types. The attribute can be used to create better, more accurate, .NET API over the native API.

You can decorate methods (on return value), parameters and properties with `BindAs`. The only restriction is that your member **must not** be inside a `[Protocol]` or [`[Model]`](#ModelAttribute) interface.
You can decorate methods (on return value), parameters and properties with `BindAs`. In `[Protocol]` and [`[Model]`](#ModelAttribute) interfaces, `BindAs` is supported on parameters, but not on properties or return values.

For example:

Expand Down
2 changes: 1 addition & 1 deletion docs/website/generator-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ This usually indicates a bug in the product; please [file a bug report](https://

### <a name='BI1049'/>BI1049: Could not unbox type \* from \* container used on \* member decorated with [BindAs].

### <a name='BI1050'/>BI1050: [BindAs] cannot be used inside Protocol or Model types. Type: \*
### <a name='BI1050'/>BI1050: [BindAs] cannot be used on properties or return values inside Protocol or Model types. Type: \*

### <a name='BI1051'/>BI1051: Internal error: Don't know how to get attributes for \*. Please file a bug report (https://github.com/dotnet/macios/issues/new) with a test case.

Expand Down
4 changes: 2 additions & 2 deletions src/ObjCRuntime/BindAsAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace ObjCRuntime {
// BindAsAttribute
//
// The BindAsAttribute allows binding NSNumber, NSValue and NSString(enums) into more accurate C# types.
// It can be used in methods, parameters and properties. The only restriction is that your member must not
// be inside a [Protocol] or [Model] interface.
// It can be used in methods, parameters and properties. Parameters are supported inside [Protocol] and
// [Model] interfaces, but return values and properties are not.
//
// For example:
//
Expand Down
10 changes: 9 additions & 1 deletion src/ObjCRuntime/DynamicRegistrar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,15 @@ class DynamicRegistrar : Registrar {
// Note that the registrar is already making sure it's not _mutated_ from
// multiple threads at the same time.
Dictionary<Type, object?> custom_type_map; // Use Dictionary instead of HashSet to avoid pulling in System.Core.dll.
Dictionary<Type, Dictionary<MethodBase, List<MethodBase>>?> cached_interface_method_mappings;

protected object lock_obj = new object ();

public DynamicRegistrar ()
{
type_map = new Dictionary<IntPtr, ObjCType> (Runtime.IntPtrEqualityComparer);
custom_type_map = new Dictionary<Type, object?> (Runtime.TypeEqualityComparer);
cached_interface_method_mappings = new Dictionary<Type, Dictionary<MethodBase, List<MethodBase>>?> (Runtime.TypeEqualityComparer);
}

protected override bool SkipRegisterAssembly (Assembly assembly)
Expand Down Expand Up @@ -360,7 +362,13 @@ protected override IEnumerable<Type> CollectTypes (Assembly assembly)

protected override Dictionary<MethodBase, List<MethodBase>>? PrepareMethodMapping (Type type)
{
return SharedDynamic.PrepareInterfaceMethodMapping (type);
lock (cached_interface_method_mappings) {
if (!cached_interface_method_mappings.TryGetValue (type, out var methodMap)) {
methodMap = SharedDynamic.PrepareInterfaceMethodMapping (type);
cached_interface_method_mappings [type] = methodMap;
}
return methodMap;
}
}

protected override ExportAttribute? GetExportAttribute (PropertyInfo property)
Expand Down
58 changes: 42 additions & 16 deletions src/ObjCRuntime/Registrar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -717,26 +717,32 @@ public TType []? Parameters {

public TType []? NativeParameters {
get {
if (native_parameters is null && Parameters is not null) {
// Put the parameters in a temporary variable, and only store them in the instance field once done,
// so that if an exception occurs, the same exception will be raised the next time too.
var native_parameters = new TType [parameters!.Length];
for (int i = 0; i < parameters.Length; i++) {
var originalType = Registrar.GetBindAsAttribute (this, i)?.OriginalType;
if (originalType is not null) {
if (!IsValidToManagedTypeConversion (originalType, parameters [i]))
throw Registrar.CreateException (4172, Method, Errors.MT4172, Registrar.GetTypeFullName (parameters [i]), originalType.FullName, Registrar.GetParameterName (Method, i), DescriptiveMethodName);
native_parameters [i] = originalType;
} else {
native_parameters [i] = parameters [i];
}
}
this.native_parameters = native_parameters;
}
PrepareNativeParameters ();
return native_parameters;
}
}

void PrepareNativeParameters ()
{
if (native_parameters is not null || Parameters is null)
return;

// Put the parameters in a temporary variable, and only store them in the instance field once done,
// so that if an exception occurs, the same exception will be raised the next time too.
var computedNativeParameters = new TType [parameters!.Length];
for (int i = 0; i < parameters.Length; i++) {
var originalType = Registrar.GetBindAsAttribute (this, i)?.OriginalType;
if (originalType is not null) {
if (!IsValidToManagedTypeConversion (originalType, parameters [i]))
throw Registrar.CreateException (4172, Method, Errors.MT4172, Registrar.GetTypeFullName (parameters [i]), originalType.FullName, Registrar.GetParameterName (Method, i), DescriptiveMethodName);
computedNativeParameters [i] = originalType;
} else {
computedNativeParameters [i] = parameters [i];
}
}
native_parameters = computedNativeParameters;
}

bool IsValidToManagedTypeConversion (TType inputType, TType outputType)
{
var nullableType = Registrar.GetNullableType (outputType);
Expand Down Expand Up @@ -962,6 +968,7 @@ public bool ValidateSignature ([NotNullWhen (false)][NotNullIfNotNull (nameof (e

if (signature is null) {
try {
PrepareNativeParameters ();
signature = ComputeSignature ();
} catch (ProductException mte) {
AddException (ref exceptions, mte);
Expand Down Expand Up @@ -1229,6 +1236,25 @@ protected bool IsEnum (TType type)
{
var mthd = method.Method!;
var attrib = GetBindAsAttribute (mthd, parameter_index);
if (attrib is null && parameter_index >= 0 && !method.IsPropertyAccessor && !method.IsConstructor && !method.IsCategory && !IsInterface (method.DeclaringType.Type)) {
// Parameter attributes aren't inherited from protocol methods, so look up the mapped interface method.
var methodMap = PrepareMethodMapping (method.DeclaringType.Type);
if (methodMap is not null && methodMap.TryGetValue (mthd, out var interfaceMethods)) {
List<TMethod>? bindAsInterfaceMethods = null;
foreach (var interfaceMethod in interfaceMethods) {
var interfaceAttribute = GetBindAsAttribute (interfaceMethod, parameter_index);
if (interfaceAttribute is null)
continue;

bindAsInterfaceMethods ??= new List<TMethod> ();
bindAsInterfaceMethods.Add (interfaceMethod);
attrib = interfaceAttribute;
}

if (bindAsInterfaceMethods is not null && interfaceMethods.Count != 1)
throw new AggregateException (Shared.GetMT4127 (mthd, interfaceMethods));
}
}
if (attrib is not null) {
var type = parameter_index == -1 ? GetReturnType (mthd) : GetParameters (mthd)! [parameter_index];
if (parameter_index == -1) {
Expand Down
2 changes: 1 addition & 1 deletion src/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@
</data>

<data name="BI1050" xml:space="preserve">
<value>[BindAs] cannot be used inside Protocol or Model types. Type: {0}</value>
<value>[BindAs] cannot be used on properties or return values inside Protocol or Model types. Type: {0}</value>
</data>

<data name="BI1051" xml:space="preserve">
Expand Down
4 changes: 2 additions & 2 deletions src/bgen/DocumentationManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public bool TryGetDocumentation (MemberInfo member, [NotNullWhen (true)] out str
// There's already an implementation in Roslyn, but that's a rather heavy dependency,
// so we're implementing this in our own code instead.

public static string GetDocId (MethodInfo md, bool includeDeclaringType = true, bool alwaysIncludeParenthesis = false)
public static string GetDocId (MethodInfo md, bool includeDeclaringType = true, bool alwaysIncludeParenthesis = false, Func<ParameterInfo, Type>? parameterTypeProvider = null)
{
var methodName = md.Name.Replace ('.', '#');
var name = methodName;
Expand All @@ -122,7 +122,7 @@ public static string GetDocId (MethodInfo md, bool includeDeclaringType = true,
name += $"``{md.GetGenericArguments ().Length}";
var parameters = md.GetParameters ();
if (parameters.Length > 0) {
name += "(" + string.Join (",", parameters.Select (p => GetDocId (p.ParameterType))) + ")";
name += "(" + string.Join (",", parameters.Select (p => GetDocId (parameterTypeProvider?.Invoke (p) ?? p.ParameterType))) + ")";
} else if (alwaysIncludeParenthesis) {
name += "()";
}
Expand Down
12 changes: 6 additions & 6 deletions src/bgen/Generator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ string GetToBindAsWrapper (MethodInfo mi, MemberInformation? minfo = null, Param
string? temp = null;
var declaringType = minfo?.mi?.DeclaringType ?? pi?.Member?.DeclaringType;

if (IsMemberInsideProtocol (declaringType))
if (pi is null && IsMemberInsideProtocol (declaringType))
throw new BindingException (1050, true, declaringType?.Name);

if (pi is null) {
Expand All @@ -395,10 +395,10 @@ string GetToBindAsWrapper (MethodInfo mi, MemberInformation? minfo = null, Param
attrib = GetOneBindAsAttribute (minfo.mi);
var property = minfo.mi as PropertyInfo;
var method = minfo.mi as MethodInfo;
originalType = (method?.ReturnType ?? property?.PropertyType)!;
originalType = attrib.OriginalType ?? (method?.ReturnType ?? property?.PropertyType)!;
} else {
attrib = GetOneBindAsAttribute (pi);
originalType = pi.ParameterType;
originalType = attrib.OriginalType ?? pi.ParameterType;
}

if (originalType.IsByRef)
Expand Down Expand Up @@ -475,7 +475,7 @@ string GetFromBindAsWrapper (MemberInformation minfo, out string suffix)
var append = string.Empty;
var property = minfo.mi as PropertyInfo;
var method = minfo.mi as MethodInfo;
var originalReturnType = method?.ReturnType ?? property?.PropertyType;
var originalReturnType = attrib.OriginalType ?? method?.ReturnType ?? property?.PropertyType;

if (originalReturnType == TypeCache.NSNumber) {
if (!TypeManager.NSNumberReturnMap.TryGetValue (retType, out append)) {
Expand Down Expand Up @@ -5161,7 +5161,7 @@ void GenerateProtocolTypes (Type type, string class_visibility, string TypeName,
// linker description file (which supports conditional preservation better).
// Ref: https://github.com/dotnet/runtime/issues/37352#issuecomment-644385807
var docIds = instanceMethods
.Select (mi => DocumentationManager.GetDocId (mi, includeDeclaringType: false, alwaysIncludeParenthesis: true))
.Select (mi => DocumentationManager.GetDocId (mi, includeDeclaringType: false, alwaysIncludeParenthesis: true, parameterTypeProvider: p => AttributeManager.GetCustomAttribute<BindAsAttribute> (p)?.Type ?? p.ParameterType))
.Concat (instanceProperties.Select (v => v.Name))
.Select (v => $"\"{v}\"");
dynamicDependencies.AddRange (docIds);
Expand Down Expand Up @@ -5557,7 +5557,7 @@ public void PrintBindAsAttribute (ICustomAttributeProvider? mi, StringBuilder? s
var property = mi as PropertyInfo;
var method = mi as MethodInfo;
var param = mi as ParameterInfo;
var originalType = method?.ReturnType ?? property?.PropertyType;
var originalType = p.OriginalType ?? method?.ReturnType ?? property?.PropertyType;
originalType = originalType ?? param?.ParameterType;

var declaringType = (mi as MemberInfo)?.DeclaringType ?? param?.Member.DeclaringType;
Expand Down
7 changes: 3 additions & 4 deletions src/bgen/Models/MarshalInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
#nullable enable

//
// Used to encapsulate flags about types in either the parameter or the return value
// For now, it only supports the [PlainString] attribute on strings.
// Used to encapsulate flags about types in either the parameter or the return value.
//
public class MarshalInfo {
public Generator Generator { get; }
Expand All @@ -20,7 +19,7 @@ public MarshalInfo (Generator generator, MethodInfo mi, ParameterInfo pi)
{
this.Generator = generator;
PlainString = Generator.AttributeManager.HasAttribute<PlainStringAttribute> (pi);
Type = pi.ParameterType;
Type = Generator.AttributeManager.GetCustomAttribute<BindAsAttribute> (pi)?.OriginalType ?? pi.ParameterType;
IsOut = pi.IsOut;
}

Expand All @@ -29,6 +28,6 @@ public MarshalInfo (Generator generator, MethodInfo mi)
{
this.Generator = generator;
PlainString = Generator.AttributeManager.HasAttribute<PlainStringAttribute> (mi.ReturnParameter);
Type = mi.ReturnType;
Type = Generator.AttributeManager.GetCustomAttribute<BindAsAttribute> (mi.ReturnParameter)?.OriginalType ?? mi.ReturnType;
}
}
4 changes: 2 additions & 2 deletions tests/bgen/ErrorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ public void BI1050_model (Profile profile)
bgen.Profile = profile;
bgen.CreateTemporaryBinding (File.ReadAllText (Path.Combine (Configuration.SourceRoot, "tests", "bgen", "tests", "bindas1050modelerror.cs")));
bgen.AssertExecuteError ("build");
bgen.AssertError (1050, "[BindAs] cannot be used inside Protocol or Model types. Type: MyFooClass");
bgen.AssertError (1050, "[BindAs] cannot be used on properties or return values inside Protocol or Model types. Type: MyFooClass");
}

[Test]
Expand All @@ -205,7 +205,7 @@ public void BI1050_protocol (Profile profile)
bgen.Profile = profile;
bgen.CreateTemporaryBinding (File.ReadAllText (Path.Combine (Configuration.SourceRoot, "tests", "bgen", "tests", "bindas1050protocolerror.cs")));
bgen.AssertExecuteError ("build");
bgen.AssertError (1050, "[BindAs] cannot be used inside Protocol or Model types. Type: MyFooClass");
bgen.AssertError (1050, "[BindAs] cannot be used on properties or return values inside Protocol or Model types. Type: MyFooClass");
}

[Test]
Expand Down
20 changes: 20 additions & 0 deletions tests/bgen/tests/ExpectedXmlDocs.MacCatalyst.xml
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,16 @@
Summary for P1.PMethodWithArgs
</summary>
</member>
<member name="M:XmlDocumentation.IP1.PMethodWithBindAs(XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.IP1._PMethodWithBindAs(XmlDocumentation.IP1,XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="P:XmlDocumentation.IP1.PProperty">
<summary>
Summary for P1.PProperty
Expand Down Expand Up @@ -310,6 +320,11 @@
Summary for P1.PMethodWithArgs
</summary>
</member>
<member name="M:XmlDocumentation.P1_Extensions.PMethodWithBindAs(XmlDocumentation.IP1,XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.P1_Extensions.GetPProperty(XmlDocumentation.IP1)">
<summary>
Summary for P1.PProperty
Expand Down Expand Up @@ -448,6 +463,11 @@
Summary for P1.PMethodWithArgs
</summary><param name="arg0">Docs for arg0.</param>
</member>
<member name="M:XmlDocumentation.T1.PMethodWithBindAs(XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.T1.PMethodWithUndocumentedArgs(System.Int32)">
<summary>
Summary for P1.PMethodWithArgs
Expand Down
20 changes: 20 additions & 0 deletions tests/bgen/tests/ExpectedXmlDocs.iOS.xml
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,16 @@
Summary for P1.PMethodWithArgs
</summary>
</member>
<member name="M:XmlDocumentation.IP1.PMethodWithBindAs(XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.IP1._PMethodWithBindAs(XmlDocumentation.IP1,XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="P:XmlDocumentation.IP1.PProperty">
<summary>
Summary for P1.PProperty
Expand Down Expand Up @@ -310,6 +320,11 @@
Summary for P1.PMethodWithArgs
</summary>
</member>
<member name="M:XmlDocumentation.P1_Extensions.PMethodWithBindAs(XmlDocumentation.IP1,XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.P1_Extensions.GetPProperty(XmlDocumentation.IP1)">
<summary>
Summary for P1.PProperty
Expand Down Expand Up @@ -448,6 +463,11 @@
Summary for P1.PMethodWithArgs
</summary><param name="arg0">Docs for arg0.</param>
</member>
<member name="M:XmlDocumentation.T1.PMethodWithBindAs(XmlDocumentation.E2)">
<summary>
Summary for P1.PMethodWithBindAs
</summary><param name="value">Docs for value.</param>
</member>
<member name="M:XmlDocumentation.T1.PMethodWithUndocumentedArgs(System.Int32)">
<summary>
Summary for P1.PMethodWithArgs
Expand Down
Loading
Loading