-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add Operator Overloading Helpers
- Loading branch information
Showing
1 changed file
with
57 additions
and
0 deletions.
There are no files selected for viewing
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,57 @@ | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using DistIL.AsmIO; | ||
|
||
namespace Silverfly.Backend; | ||
|
||
public static class OperatorOverloading | ||
{ | ||
public static readonly Dictionary<string, string> BinMap = new() | ||
{ | ||
["+"] = "op_Addition", | ||
["/"] = "op_Division", | ||
["-"] = "op_Subtraction", | ||
["*"] = "op_Multiply", | ||
["%"] = "op_Modulus", | ||
|
||
["&"] = "op_BitwiseAnd", | ||
["|"] = "op_BitwiseOr", | ||
["^"] = "op_ExclusiveOr", | ||
["=="] = "op_Equality", | ||
["!="] = "op_Inequality", | ||
}; | ||
|
||
public static readonly Dictionary<string, string> UnMap = new() | ||
{ | ||
["!"] = "op_LogicalNot", | ||
["-"] = "op_UnaryNegation", | ||
["~"] = "op_OnesComplement", | ||
|
||
["implicit"] = "op_Implicit", | ||
["explicit"] = "op_Explicit", | ||
}; | ||
|
||
public static bool TryGetOperator(this TypeDesc type, string op, out MethodDesc opMethod, params TypeDesc[] args) | ||
{ | ||
var nameMap = args.Length switch | ||
{ | ||
1 => UnMap, | ||
2 => BinMap, | ||
_ => null | ||
}; | ||
|
||
if (nameMap!.TryGetValue(op, out var opMethodName)) | ||
{ | ||
var candidate = type.FindMethod(opMethodName, new MethodSig(new TypeSig(), args.Select(type=> new TypeSig(type)).ToList(), false), throwIfNotFound: false); | ||
|
||
if (candidate != null) | ||
{ | ||
opMethod = candidate; | ||
return true; | ||
} | ||
} | ||
|
||
opMethod = null; | ||
return false; | ||
} | ||
} |