From e1e8c9879af0afc3159ac429c4bafb117faef9ee Mon Sep 17 00:00:00 2001 From: Chris Anders Date: Wed, 6 Nov 2024 18:16:44 +0100 Subject: [PATCH] feat: Add Operator Overloading Helpers --- .../Silverfly.Backend/OperatorOverloading.cs | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Source/Silverfly.Backend/OperatorOverloading.cs diff --git a/Source/Silverfly.Backend/OperatorOverloading.cs b/Source/Silverfly.Backend/OperatorOverloading.cs new file mode 100644 index 0000000..d5cac47 --- /dev/null +++ b/Source/Silverfly.Backend/OperatorOverloading.cs @@ -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 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 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; + } +}