Skip to content

Commit

Permalink
feat: Add Operator Overloading Helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
furesoft committed Nov 6, 2024
1 parent b0580e1 commit e1e8c98
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions Source/Silverfly.Backend/OperatorOverloading.cs
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;
}
}

0 comments on commit e1e8c98

Please sign in to comment.