Skip to content
Closed
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
54 changes: 54 additions & 0 deletions src/rgen/Microsoft.Macios.Generator/Emitters/ClassEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ namespace Microsoft.Macios.Generator.Emitters;
/// Emitter for Objective-C classes.
/// </summary>
class ClassEmitter : IClassEmitter {

const string initWithCoderSelector = "initWithCoder:";

/// <inheritdoc />
public string GetSymbolName (in Binding binding)
{
Expand All @@ -47,6 +50,45 @@ public string GetSymbolName (in Binding binding)
"ObjCRuntime",
];

/// <summary>
/// Emits the NSCoding constructor (initWithCoder:) for classes that inherit from NSCoding or implement INSCoding.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inheriting from NSCoding doesn't make sense, we only care for classes that implement INSCoding.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's coming from the branch we depend. will update accordingly.

/// This constructor is required for proper serialization support and includes appropriate thread checks when needed.
/// </summary>
/// <param name="context">The current binding context containing class information.</param>
/// <param name="classBlock">The writer for the class block to emit the constructor into.</param>
static void EmitNSCondingConstructor (in BindingContext context, TabbedWriter<StringWriter> classBlock)
{
// used to check if we need to check that we are running in the ui thread, this is a special case
// for the NSCoding constructor
var uiThreadCheck = (context.NeedsThreadChecks)
? EnsureUiThread (context.RootContext.CurrentPlatform)
: null;

classBlock.WriteDocumentation (Documentation.Class.InitWithCoder (context.Changes.Name));
classBlock.AppendGeneratedCodeAttribute (optimizable: true);
classBlock.AppendDesignatedInitializer ();
classBlock.AppendEditorBrowsableAttribute (EditorBrowsableState.Advanced);
if (GeneratorConfiguration.BGenCompatible) {
classBlock.AppendBgenExportAttribute (initWithCoderSelector);
}
using (var constructorBlock = classBlock.CreateBlock (
$"public {context.Changes.Name} (NSCoder coder) : base (NSObjectFlag.Empty)", block: true)) {
if (uiThreadCheck is not null) {
constructorBlock.WriteLine (uiThreadCheck.ToString ());
constructorBlock.WriteLine ();
}

constructorBlock.WriteRaw (
$@"if (IsDirectBinding) {{
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle (""{initWithCoderSelector}""), coder.Handle), ""{initWithCoderSelector}"");
}} else {{
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle (""{initWithCoderSelector}:""), coder.Handle), ""{initWithCoderSelector}"");
}}
GC.KeepAlive (coder);
");
}
}

/// <summary>
/// Emit the code for all the constructors in the class.
/// </summary>
Expand All @@ -57,6 +99,12 @@ void EmitConstructors (in BindingContext context, TabbedWriter<StringWriter> cla
// When dealing with constructors we cannot sort them by name because the name is always the same as the class
// instead we will sort them by the selector name so that we will always generate the constructors in the same order
foreach (var constructor in context.Changes.Constructors.OrderBy (c => c.ExportMethodData.Selector)) {
// if the class implements extends NSConding or implements INSCoding we need to skip the constructor
// with the selector 'initWithCoder:' since that is generated by default and we do not want to have two
// constructors with the same signature
if (context.Changes.TypeInfo.IsNSCoding && constructor.Selector == initWithCoderSelector)
continue;

classBlock.AppendMemberAvailability (constructor.SymbolAvailability);
classBlock.AppendGeneratedCodeAttribute (optimizable: true);
if (constructor.ExportMethodData.Flags.HasFlag (Constructor.DesignatedInitializer)) {
Expand Down Expand Up @@ -256,6 +304,12 @@ public bool TryEmit (in BindingContext bindingContext, [NotNullWhen (false)] out
classBlock: classBlock,
disableDefaultCtor: bindingData.Flags.HasFlag (ObjCBindings.Class.DisableDefaultCtor));

// A class that inherits from NSCoding OR implements the INSCoding interface requires to create
// the 'initWithCoder:' constructor
if (bindingContext.Changes.TypeInfo.IsNSCoding) {
EmitNSCondingConstructor (bindingContext, classBlock);
}

// emit any other constructor that is not the default one
EmitConstructors (bindingContext, classBlock);
}
Expand Down
10 changes: 10 additions & 0 deletions src/rgen/Microsoft.Macios.Generator/Emitters/Documentation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,15 @@ public static string DefaultInitWithHandle (string name) =>
public static string TrampolineStaticClass (string name) =>
"/// <summary>This class bridges native block invocations that call into C#</summary>";

public static string InitWithCoder (string name) =>
@"/// <summary>A constructor that initializes the object from the data stored in the unarchiver object.</summary>
/// <param name=""coder"">The unarchiver object.</param>
/// <remarks>
/// <para>This constructor is provided to allow the class to be initialized from an unarchiver (for example, during NIB deserialization). This is part of the <see cref=""Foundation.NSCoding"" /> protocol.</para>
/// <para>If developers want to create a subclass of this object and continue to support deserialization from an archive, they should implement a constructor with an identical signature: taking a single parameter of type <see cref=""Foundation.NSCoder"" /> and decorate it with the <c>[Export(""initWithCoder:""]</c> attribute.</para>
/// <para>The state of this object can also be serialized by using the <see cref=""Foundation.INSCoding.EncodeTo"" /> companion method.</para>
/// </remarks>";

}

public static class StrongDictionary {
Expand All @@ -149,5 +158,6 @@ public static string EmptyConstructor (string name) =>
public static string InitWithDictionary (string name) =>
$@"/// <summary>Creates a new <see cref=""{name}"" /> from the values that are specified in <paramref name=""dictionary"" />.</summary>
/// <param name=""dictionary"">The dictionary to use to populate the properties of this type.</param>";

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,17 @@ public class TestDataGenerator : BaseTestDataGenerator, IEnumerable<object []> {
{"EventTests_RgenNSKeyedArchiverDelegate.g.cs", "ExpectedEventTests_RgenNSKeyedArchiverDelegate.cs"}
}
},

// NSCoding tests
new (ApplePlatform.iOS, "NSCodingSubclass", "NSCodingSubclass.cs", "ExpectedNSCodingSubclass.cs"),
new (ApplePlatform.TVOS, "NSCodingSubclass", "NSCodingSubclass.cs", "ExpectedNSCodingSubclass.cs"),
new (ApplePlatform.MacCatalyst, "NSCodingSubclass", "NSCodingSubclass.cs", "ExpectedNSCodingSubclass.cs"),
new (ApplePlatform.MacOSX, "NSCodingSubclass", "macosNSCodingSubclass.cs", "macosExpectedNSCodingSubclass.cs"),

new (ApplePlatform.iOS, "NSCodingSubclassWithConstructor", "NSCodingSubclassWithConstructor.cs", "ExpectedNSCodingSubclassWithConstructor.cs"),
new (ApplePlatform.TVOS, "NSCodingSubclassWithConstructor", "NSCodingSubclassWithConstructor.cs", "ExpectedNSCodingSubclassWithConstructor.cs"),
new (ApplePlatform.MacCatalyst, "NSCodingSubclassWithConstructor", "NSCodingSubclassWithConstructor.cs", "ExpectedNSCodingSubclassWithConstructor.cs"),
new (ApplePlatform.MacOSX, "NSCodingSubclassWithConstructor", "macosNSCodingSubclassWithConstructor.cs", "macosExpectedNSCodingSubclassWithConstructor.cs"),
};

public IEnumerator<object []> GetEnumerator ()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// <auto-generated />

#nullable enable

using AVFoundation;
using CoreGraphics;
using Foundation;
using ObjCBindings;
using ObjCRuntime;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

namespace UIKit;

[SupportedOSPlatform ("macos")]
[SupportedOSPlatform ("ios")]
[SupportedOSPlatform ("tvos")]
[SupportedOSPlatform ("maccatalyst13.1")]
[Register ("NSCodingSubclass", true)]
public partial class NSCodingSubclass
{
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
static readonly global::ObjCRuntime.NativeHandle class_ptr = global::ObjCRuntime.Class.GetHandle ("NSCodingSubclass");

/// <summary>The Objective-C class handle for this class.</summary>
/// <value>The pointer to the Objective-C class.</value>
/// <remarks>
/// Each managed class mirrors an unmanaged Objective-C class.
/// This value contains the pointer to the Objective-C class.
/// It is similar to calling the managed <see cref=\"ObjCRuntime.Class.GetHandle(string)\" /> or the native <see href=\"https://developer.apple.com/documentation/objectivec/1418952-objc_getclass\">objc_getClass</see> method with the type name.
/// </remarks>
public override global::ObjCRuntime.NativeHandle ClassHandle => class_ptr;

/// <summary>Creates a new <see cref="NSCodingSubclass" /> with default values.</summary>
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[DesignatedInitializer]
[Export ("init")]
public NSCodingSubclass () : base (global::Foundation.NSObjectFlag.Empty)
{
if (IsDirectBinding)
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
else
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
}

/// <summary>Constructor to call on derived classes to skip initialization and merely allocate the object.</summary>
/// <param name="t">Unused sentinel value, pass NSObjectFlag.Empty.</param>
/// <remarks>
/// <para>
/// This constructor should be called by derived classes when they completely construct the object in managed code and merely want the runtime to allocate and initialize the <see cref="Foundation.NSObject" />.
/// This is required to implement the two-step initialization process that Objective-C uses, the first step is to perform the object allocation, the second step is to initialize the object.
/// When developers invoke this constructor, they take advantage of a direct path that goes all the way up to <see cref="Foundation.NSObject" /> to merely allocate the object's memory and bind the Objective-C and C# objects together.
/// The actual initialization of the object is up to the developer.
/// </para>
/// <para>
/// This constructor is typically used by the binding generator to allocate the object, but prevent the actual initialization to take place.
/// Once the allocation has taken place, the constructor has to initialize the object.
/// With constructors generated by the binding generator this means that it manually invokes one of the "init" methods to initialize the object.
/// </para>
/// <para>It is the developer's responsibility to completely initialize the object if they chain up using this constructor chain.</para>
/// <para>
/// In general, if the developer's constructor invokes the corresponding base implementation, then it should also call an Objective-C init method.
/// If this is not the case, developers should instead chain to the proper constructor in their class.
/// </para>
/// <para>
/// The argument value is ignored and merely ensures that the only code that is executed is the construction phase is the basic <see cref="Foundation.NSObject" /> allocation and runtime type registration.
/// Typically the chaining would look like this:
/// </para>
/// <example>
/// <code lang="csharp lang-csharp"><![CDATA[
/// //
/// // The NSObjectFlag constructor merely allocates the object and registers the C# class with the Objective-C runtime if necessary.
/// // No actual initXxx method is invoked, that is done later in the constructor
/// //
/// // This is taken from the iOS SDK's source code for the UIView class:
/// //
/// [Export ("initWithFrame:")]
/// public UIView (System.Drawing.RectangleF frame) : base (NSObjectFlag.Empty)
/// {
/// // Invoke the init method now.
/// var initWithFrame = new Selector ("initWithFrame:").Handle;
/// if (IsDirectBinding) {
/// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSend_CGRect (this.Handle, initWithFrame, frame);
/// } else {
/// Handle = ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_CGRect (this.SuperHandle, initWithFrame, frame);
/// }
/// }
/// ]]></code>
/// </example>
/// </remarks>
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected NSCodingSubclass (global::Foundation.NSObjectFlag t) : base (t) {}

/// <summary>A constructor used when creating managed representations of unmanaged objects. Called by the runtime.</summary>
/// <param name="handle">Pointer (handle) to the unmanaged object.</param>
/// <remarks>
/// <para>
/// This constructor is invoked by the runtime infrastructure (<see cref="ObjCRuntime.Runtime.GetNSObject(System.IntPtr)" />) to create a new managed representation for a pointer to an unmanaged Objective-C object.
/// Developers should not invoke this method directly, instead they should call <see cref="ObjCRuntime.Runtime.GetNSObject(System.IntPtr)" /> as it will prevent two instances of a managed object pointing to the same native object.
/// </para>
/// </remarks>
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected internal NSCodingSubclass (global::ObjCRuntime.NativeHandle handle) : base (handle) {}

/// <summary>A constructor that initializes the object from the data stored in the unarchiver object.</summary>
/// <param name="coder">The unarchiver object.</param>
/// <remarks>
/// <para>This constructor is provided to allow the class to be initialized from an unarchiver (for example, during NIB deserialization). This is part of the <see cref="Foundation.NSCoding" /> protocol.</para>
/// <para>If developers want to create a subclass of this object and continue to support deserialization from an archive, they should implement a constructor with an identical signature: taking a single parameter of type <see cref="Foundation.NSCoder" /> and decorate it with the <c>[Export("initWithCoder:"]</c> attribute.</para>
/// <para>The state of this object can also be serialized by using the <see cref="Foundation.INSCoding.EncodeTo" /> companion method.</para>
/// </remarks>
[BindingImpl (BindingImplOptions.GeneratedCode | BindingImplOptions.Optimizable)]
[DesignatedInitializer]
[EditorBrowsable (EditorBrowsableState.Advanced)]
[Export ("initWithCoder:")]
public NSCodingSubclass (NSCoder coder) : base (NSObjectFlag.Empty)
{
UIKit.UIApplication.EnsureUIThread ();

if (IsDirectBinding) {
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("initWithCoder:"), coder.Handle), "initWithCoder:");
} else {
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithCoder::"), coder.Handle), "initWithCoder:");
Copy link

Copilot AI Sep 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The selector string has an extra colon. It should be initWithCoder: not initWithCoder::.

Suggested change
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithCoder::"), coder.Handle), "initWithCoder:");
InitializeHandle (global::ObjCRuntime.Messaging.IntPtr_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("initWithCoder:"), coder.Handle), "initWithCoder:");

Copilot uses AI. Check for mistakes.
}
GC.KeepAlive (coder);
}
}
Loading
Loading