Skip to content

Commit

Permalink
Fix subclass ordering in generated code (#371)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasongin authored Sep 3, 2024
1 parent 81c928a commit 2d9c155
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
22 changes: 10 additions & 12 deletions src/NodeApi.Generator/ModuleGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -443,25 +443,23 @@ private void ExportModule(
}
}

/// <summary>
/// Orders types by their inheritance hierarchy, so base types are ordered before derived
/// types, and types with the same base type are in alphabetical order.
private static int OrderByTypeHierarchy(ITypeSymbol a, ITypeSymbol b)
{
for (ITypeSymbol? t = a.BaseType; t != null; t = t.BaseType)
static string GetTypeHierarchyPath(ITypeSymbol type)
{
if (SymbolEqualityComparer.Default.Equals(t, b))
if (type.BaseType == null) // System.Object
{
return 1;
return "/";
}
}

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

return 0;
return string.CompareOrdinal(GetTypeHierarchyPath(a), GetTypeHierarchyPath(b));
}

/// <summary>
Expand Down Expand Up @@ -514,7 +512,7 @@ private void ExportType(
{
string baseTypeVariableName = "type_" +
GetFullName(type.BaseType!).Replace('.', '_');
s += $".DefineClass({baseTypeVariableName});";
s += $".DefineClass(baseClass: {baseTypeVariableName});";
}
else
{
Expand Down
7 changes: 7 additions & 0 deletions test/TestCases/napi-dotnet/ComplexTypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,13 @@ public enum TestEnum
Two,
}

// The subclass is declared before the base class to ensure the module generator handles this case.
[JSExport]
public class SubClass2 : SubClass
{
public SubClass2(int value, int value2) : base(value, value2) {}
}

[JSExport]
public interface IBaseInterface
{
Expand Down

0 comments on commit 2d9c155

Please sign in to comment.