-
-
Notifications
You must be signed in to change notification settings - Fork 204
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add ContextToMethodDescriptor extension class (#376)
- Loading branch information
Showing
1 changed file
with
52 additions
and
0 deletions.
There are no files selected for viewing
52 changes: 52 additions & 0 deletions
52
Cpp2IL.Core/Utils/AsmResolver/ContextToMethodDescriptor.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
using System.Linq; | ||
using AsmResolver.DotNet; | ||
using AsmResolver.DotNet.Signatures; | ||
using Cpp2IL.Core.Model.Contexts; | ||
|
||
namespace Cpp2IL.Core.Utils.AsmResolver; | ||
|
||
public static class ContextToMethodDescriptor | ||
{ | ||
private static MethodDefinition GetMethodDefinition(this MethodAnalysisContext context) | ||
{ | ||
return context.GetExtraData<MethodDefinition>("AsmResolverMethod") ?? throw new($"AsmResolver method not found in method analysis context for {context}"); | ||
} | ||
|
||
private static MethodSignature ToMethodSignature(this MethodAnalysisContext context, ModuleDefinition parentModule) | ||
{ | ||
var returnType = context.ReturnTypeContext.ToTypeSignature(parentModule); | ||
var parameters = context.Parameters.Select(p => p.ToTypeSignature(parentModule)); | ||
|
||
var genericParameterCount = context.Definition?.GenericContainer?.genericParameterCount ?? 0; | ||
|
||
return context.IsStatic | ||
? MethodSignature.CreateStatic(returnType, genericParameterCount, parameters) | ||
: MethodSignature.CreateInstance(returnType, genericParameterCount, parameters); | ||
} | ||
|
||
public static IMethodDescriptor ToMethodDescriptor(this MethodAnalysisContext context, ModuleDefinition parentModule) | ||
{ | ||
if (context is ConcreteGenericMethodAnalysisContext concreteMethod) | ||
{ | ||
var memberReference = new MemberReference( | ||
concreteMethod.DeclaringType?.ToTypeSignature(parentModule).ToTypeDefOrRef(), | ||
concreteMethod.Name, | ||
concreteMethod.BaseMethodContext.ToMethodSignature(parentModule)); | ||
|
||
var methodGenericParameters = concreteMethod.ResolveMethodGenericParameters(); | ||
if (methodGenericParameters.Length == 0) | ||
{ | ||
return parentModule.DefaultImporter.ImportMethod(memberReference); | ||
} | ||
else | ||
{ | ||
var typeSignatures = methodGenericParameters.Select(p => p.ToTypeSignature(parentModule)).ToArray(); | ||
return parentModule.DefaultImporter.ImportMethod(memberReference.MakeGenericInstanceMethod(typeSignatures)); | ||
} | ||
} | ||
else | ||
{ | ||
return parentModule.DefaultImporter.ImportMethod(context.GetMethodDefinition()); | ||
} | ||
} | ||
} |