Skip to content

Commit 2d9c155

Browse files
authored
Fix subclass ordering in generated code (#371)
1 parent 81c928a commit 2d9c155

2 files changed

Lines changed: 17 additions & 12 deletions

File tree

src/NodeApi.Generator/ModuleGenerator.cs

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -443,25 +443,23 @@ private void ExportModule(
443443
}
444444
}
445445

446+
/// <summary>
447+
/// Orders types by their inheritance hierarchy, so base types are ordered before derived
448+
/// types, and types with the same base type are in alphabetical order.
446449
private static int OrderByTypeHierarchy(ITypeSymbol a, ITypeSymbol b)
447450
{
448-
for (ITypeSymbol? t = a.BaseType; t != null; t = t.BaseType)
451+
static string GetTypeHierarchyPath(ITypeSymbol type)
449452
{
450-
if (SymbolEqualityComparer.Default.Equals(t, b))
453+
if (type.BaseType == null) // System.Object
451454
{
452-
return 1;
455+
return "/";
453456
}
454-
}
455457

456-
for (ITypeSymbol? t = b.BaseType; t != null; t = t.BaseType)
457-
{
458-
if (SymbolEqualityComparer.Default.Equals(t, a))
459-
{
460-
return -1;
461-
}
458+
string typeFullName = GetFullName(type);
459+
return GetTypeHierarchyPath(type.BaseType) + "/" + typeFullName;
462460
}
463461

464-
return 0;
462+
return string.CompareOrdinal(GetTypeHierarchyPath(a), GetTypeHierarchyPath(b));
465463
}
466464

467465
/// <summary>
@@ -514,7 +512,7 @@ private void ExportType(
514512
{
515513
string baseTypeVariableName = "type_" +
516514
GetFullName(type.BaseType!).Replace('.', '_');
517-
s += $".DefineClass({baseTypeVariableName});";
515+
s += $".DefineClass(baseClass: {baseTypeVariableName});";
518516
}
519517
else
520518
{

test/TestCases/napi-dotnet/ComplexTypes.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,13 @@ public enum TestEnum
209209
Two,
210210
}
211211

212+
// The subclass is declared before the base class to ensure the module generator handles this case.
213+
[JSExport]
214+
public class SubClass2 : SubClass
215+
{
216+
public SubClass2(int value, int value2) : base(value, value2) {}
217+
}
218+
212219
[JSExport]
213220
public interface IBaseInterface
214221
{

0 commit comments

Comments
 (0)