diff --git a/src/Ramstack.ExpressionParser/DefaultBinder.cs b/src/Ramstack.ExpressionParser/DefaultBinder.cs index 888fcfa..a0bb40d 100644 --- a/src/Ramstack.ExpressionParser/DefaultBinder.cs +++ b/src/Ramstack.ExpressionParser/DefaultBinder.cs @@ -117,12 +117,18 @@ public void RegisterType(Type type, bool importAsStatic = false) /// public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic) { + var bindingFlags = isStatic + ? BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static + : BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance; + var q = type is not null - ? type.GetMemberLookupTypes().SelectMany(t => GetMethods(t, methodName.Name, isStatic)) + ? type + .GetMemberLookupTypes() + .SelectMany(t => GetMethods(t, methodName.Name, bindingFlags | BindingFlags.FlattenHierarchy)) : s_predefinedTypes .Concat(_types) .Where(t => t.Value.isStatic) - .SelectMany(t => GetMethods(t.Value.type, methodName.Name, isStatic)); + .SelectMany(t => GetMethods(t.Value.type, methodName.Name, bindingFlags)); var methods = q.ToArray(); if (methods.Length == 0) @@ -142,7 +148,8 @@ public void RegisterType(Type type, bool importAsStatic = false) ? BindingFlags.Public | BindingFlags.Static : BindingFlags.Public | BindingFlags.Instance; - var q = type?.GetMemberLookupTypes().SelectMany(t => t.GetMembers(bindingFlags)) + var q = type?.GetMemberLookupTypes() + .SelectMany(t => t.GetMembers(bindingFlags | BindingFlags.FlattenHierarchy)) ?? s_predefinedTypes .Concat(_types) .Where(t => t.Value.isStatic) @@ -176,15 +183,12 @@ public void RegisterType(Type type, bool importAsStatic = false) return null; } - private static IEnumerable GetMethods(Type type, string methodName, bool isStatic) + private static IEnumerable GetMethods(Type type, string methodName, BindingFlags bindingFlags) { - var bindingFlags = isStatic - ? BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static - : BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance; - return type .GetMethods(bindingFlags) - .Where(m => string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase)) + .Where(m => + string.Equals(m.Name, methodName, StringComparison.OrdinalIgnoreCase)) .Distinct(); } } diff --git a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs index 56f4ccc..11b5cdb 100644 --- a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs +++ b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs @@ -23,6 +23,11 @@ internal static class MethodResolver /// The method that best matches the argument types, or if no candidate /// accepts the argument types or none of them matches better than all the others. /// + /// + /// As in C#, the method is chosen only among the applicable methods of the most derived types: + /// an applicable method declared in a base type of the type that declares another applicable + /// method is not considered. + /// public static MethodBase? ResolveMethod(IReadOnlyList match, Type[] argumentTypes) { if (match.Count == 0) @@ -199,6 +204,8 @@ internal static class MethodResolver if (currentIndex == 1) return candidates[0]; + currentIndex = RemoveMethodsOfBaseTypes(candidates, parameterArrayTypes, currentIndex); + // // As in C#, the method to invoke must be more specific than every other candidate. // Such a method wins each comparison, so the walk below always ends on it. A candidate @@ -251,6 +258,114 @@ internal static class MethodResolver return candidates[min]; } + /// + /// Removes the candidates declared in a base type of the type that declares another candidate. + /// + /// The applicable candidate methods. + /// The element types of the parameter arrays of the candidates. + /// The number of candidates. + /// + /// The number of remaining candidates, which are moved to the start of both arrays. + /// + private static int RemoveMethodsOfBaseTypes(MethodBase[] candidates, Type?[] parameterArrayTypes, int count) + { + // + // As in C#, only the methods of the most derived types remain, even if a removed method + // matches the arguments better. + // + var declaringTypes = new Type[count]; + for (var i = 0; i < count; i++) + declaringTypes[i] = GetIntroducingType(candidates[i]); + + var remaining = 0; + for (var i = 0; i < count; i++) + { + if (IsHidden(declaringTypes[i], declaringTypes)) + continue; + + candidates[remaining] = candidates[i]; + parameterArrayTypes[remaining] = parameterArrayTypes[i]; + remaining++; + } + + return remaining; + + static bool IsHidden(Type type, Type[] declaringTypes) + { + foreach (var other in declaringTypes) + if (HidesMethodsOf(other, type)) + return true; + + return false; + } + + static bool HidesMethodsOf(Type other, Type type) + { + // + // The base types of an interface are its base interfaces and Object, while an interface + // is not a base type of a class or struct. As in C#, a method of a class other than Object + // also removes the methods declared in interfaces. Base types are found by inheritance: + // a variant interface can be assignable from another instantiation it does not inherit. + // + if (type.IsInterface) + return other.IsInterface + ? other.GetInterfaces().Contains(type) + : other.IsClass && other != typeof(object); + + return other.IsSubclassOf(type) + || other.IsInterface && type == typeof(object); + } + } + + /// + /// Returns the type that introduced the specified method. + /// + /// The method to get the introducing type for. + /// + /// The type that declares the method or, for an override, the type that declares + /// the overridden method. + /// + private static Type GetIntroducingType(MethodBase method) + { + if (method is MethodInfo mi) + { + var definition = mi.GetBaseDefinition(); + + // + // A covariant return override occupies a new slot, so GetBaseDefinition returns + // the override itself. The compiler marks such an override with PreserveBaseOverridesAttribute. + // + if (definition.IsDefined(typeof(PreserveBaseOverridesAttribute), inherit: false) + && FindOverriddenMethod(definition) is { } overridden) + return GetIntroducingType(overridden); + + method = definition; + } + + Debug.Assert(method.DeclaringType is not null); + return method.DeclaringType; + + static MethodInfo? FindOverriddenMethod(MethodInfo method) + { + // + // An override overrides the nearest virtual method with the same parameter types. + // + var parameters = method.GetParameters(); + + for (var type = method.DeclaringType!.BaseType; type is not null; type = type.BaseType) + { + var overridden = type + .GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .FirstOrDefault(m => m.IsVirtual && m.Name == method.Name && HasSameParameterTypes(m.GetParameters(), parameters)); + + if (overridden is not null) + return overridden; + } + + return null; + } + } + private static int FindMostSpecific( ParameterInfo[] p1, Type? paramArrayType1, ParameterInfo[] p2, Type? paramArrayType2, @@ -417,80 +532,42 @@ private static int FindMostSpecificMethod( MethodBase m2, Type? paramArrayType2, Type[] types) { - // Find the most specific method based on the parameters. - var res = FindMostSpecific( - m1.GetParameters(), paramArrayType1, - m2.GetParameters(), paramArrayType2, types); + var p1 = m1.GetParameters(); + var p2 = m2.GetParameters(); - // If the match was not ambiguous then return the result. - if (res != 0) - return res; + var result = FindMostSpecific(p1, paramArrayType1, p2, paramArrayType2, types); + if (result != 0) + return result; - // Check to see if the methods have the exact same name and signature. - if (CompareSignature(m1, m2)) + // + // Reflection lists a covariant return override along with the method it overrides. + // Both belong to the type that introduced the method, so neither removes the other, + // and the override is chosen for its more specific return type. + // + if (HasSameParameterTypes(p1, p2)) { Debug.Assert(m1.DeclaringType is not null); Debug.Assert(m2.DeclaringType is not null); - // Determine the depth of the declaring types for both methods. - var hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); - var hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); + if (m1.DeclaringType.IsSubclassOf(m2.DeclaringType)) + return 1; - // - // The most derived method is the most specific one. An interface has no base class, - // so its depth equals the depth of its base interfaces and Object. As in C#, a method - // of a derived interface hides the method with the same signature declared in a base - // interface or Object. - // - if (hierarchyDepth1 == hierarchyDepth2) - { - if (m1.DeclaringType != m2.DeclaringType) - { - if (m2.DeclaringType.IsAssignableFrom(m1.DeclaringType)) - return 1; - - if (m1.DeclaringType.IsAssignableFrom(m2.DeclaringType)) - return 2; - } - - return 0; - } - - if (hierarchyDepth1 < hierarchyDepth2) + if (m2.DeclaringType.IsSubclassOf(m1.DeclaringType)) return 2; - - return 1; } - // The match is ambiguous. return 0; } - private static bool CompareSignature(MethodBase m1, MethodBase m2) + private static bool HasSameParameterTypes(ParameterInfo[] p1, ParameterInfo[] p2) { - var params1 = m1.GetParameters(); - var params2 = m2.GetParameters(); - - if (params1.Length != params2.Length) + if (p1.Length != p2.Length) return false; - for (var i = 0; i < params1.Length; i++) - if (params1[i].ParameterType != params2[i].ParameterType) + for (var i = 0; i < p1.Length; i++) + if (p1[i].ParameterType != p2[i].ParameterType) return false; return true; } - - private static int GetHierarchyDepth(Type? type) - { - var depth = 0; - do - { - depth++; - type = type!.BaseType; - } - while (type is not null); - - return depth; - } } diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index 0a2a9b3..9206d73 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -232,6 +232,36 @@ public void Evaluate_MemberHiddenByDerivedClass_BindsMemberOfDerivedClass(string public void Evaluate_UnqualifiedMemberInDerivedContext_BindsMemberOfDerivedClass() => Assert.That(ExpressionParser.Evaluate("Field", new DerivedMembers()), Is.TypeOf().And.EqualTo(2)); + [TestCase("DerivedMembers.InheritedField", 3)] + [TestCase("DerivedMembers.InheritedProperty", 4)] + [TestCase("DerivedMembers.InheritedMethod()", 5)] + [TestCase("DerivedMembers.ImportedMember", 2)] + public void Parse_QualifiedStaticMemberOfDerivedClass_BindsMember(string expression, int expected) + { + var binder = new DefaultBinder(); + binder.RegisterType(typeof(DerivedMembers)); + + var result = ExpressionParser.Parse(expression, binder); + Assert.That(result.Success, Is.True, result.ErrorMessage); + + var value = Expression.Lambda>(result.Value!).Compile()(); + Assert.That(value, Is.EqualTo(expected)); + } + + [TestCase("InheritedField", "InheritedField")] + [TestCase("InheritedProperty", "InheritedProperty")] + [TestCase("InheritedMethod()", "InheritedMethod")] + public void Parse_InheritedStaticMemberOfImportedClass_ReturnsUnresolvedSymbol(string expression, string memberName) + { + var binder = new DefaultBinder(); + binder.RegisterType(typeof(DerivedMembers), importAsStatic: true); + + var result = ExpressionParser.Parse(expression, binder); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Is.EqualTo($"Cannot resolve symbol '{memberName}'.")); + } + [Test] public void Parse_SameMemberImportedFromBaseAndDerivedTypes_ReturnsAmbiguityError() { @@ -272,6 +302,82 @@ public void Evaluate_InterfaceContext_BindsMembersOfBaseInterfacesAndObject() Assert.That(ExpressionParser.Evaluate, string>("ToString()", list), Is.EqualTo(list.ToString())); } + [TestCase("Derived.Pick(1)", "DerivedOverloads.Pick(long)")] + [TestCase("Derived.Overridden(1)", "DerivedOverloads.Overridden(long)")] + [TestCase("Derived.Optional()", "DerivedOverloads.Optional(int)")] + [TestCase("Derived[1]", "DerivedOverloads.this[long]")] + public void Evaluate_ApplicableMethodOfDerivedClass_HidesMethodsOfBaseClass(string expression, string expected) => + Assert.That(ExpressionParser.Evaluate(expression, new { Derived = new DerivedOverloads() }), Is.EqualTo(expected)); + + [Test] + public void Evaluate_NoApplicableMethodOfDerivedClass_BindsMethodOfBaseClass() => + Assert.That(ExpressionParser.Evaluate("Derived.Pick(\"x\")", new { Derived = new DerivedOverloads() }), Is.EqualTo("BaseOverloads.Pick(string)")); + + [TestCase("Covariant(1)", "BaseOverloads.Covariant(int)")] + [TestCase("Covariant(1L)", "DerivedOverloads.Covariant(long)")] + public void Parse_CovariantReturnOverride_BindsAsOverrideOfBaseClassMethod(string expression, string expected) + { + var parameter = Expression.Parameter(typeof(DerivedOverloads), "d"); + + var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); + Assert.That(result.Success, Is.True, result.ErrorMessage); + Assert.That(result.Value!.Type, Is.EqualTo(typeof(string))); + + var value = Expression.Lambda>(result.Value!, parameter).Compile()(new DerivedOverloads()); + Assert.That(value, Is.EqualTo(expected)); + } + + [Test] + public void Evaluate_ApplicableMethodOfDerivedInterface_HidesMethodsOfBaseInterface() => + Assert.That(ExpressionParser.Evaluate("Derived.Pick(1)", new InterfaceContext()), Is.EqualTo("IDerivedInterface.Pick(long)")); + + [Test] + public void Evaluate_MethodsOfVariantBaseInterfaces_DoNotHideEachOther() => + Assert.That(ExpressionParser.Evaluate("Consumers.Pick(\"x\")", new InterfaceContext()), Is.EqualTo("IConsumer.Pick(string)")); + + [Test] + public void Parse_ApplicableStaticMethodOfDerivedClass_HidesMethodsOfBaseClass() + { + var binder = new DefaultBinder(); + binder.RegisterType(typeof(DerivedOverloads)); + + var result = ExpressionParser.Parse("DerivedOverloads.Create(1)", binder); + Assert.That(result.Success, Is.True, result.ErrorMessage); + + var value = Expression.Lambda>(result.Value!).Compile()(); + Assert.That(value, Is.EqualTo("DerivedOverloads.Create(long)")); + } + + [TestCase(typeof(BaseOverloads), typeof(DerivedOverloads), "DerivedOverloads.Create(long)")] + [TestCase(typeof(IStaticOverloads), typeof(ClassOverloads), "ClassOverloads.Create(long)")] + [TestCase(typeof(IStaticOverloads), typeof(StructOverloads), "IStaticOverloads.Create(int)")] + public void Parse_StaticMethodsImportedFromSeveralTypes_ChoosesFromMostDerivedTypes(Type first, Type second, string expected) + { + var binder = new DefaultBinder(); + binder.RegisterType(first, importAsStatic: true); + binder.RegisterType(second, importAsStatic: true); + + var result = ExpressionParser.Parse("Create(1)", binder); + Assert.That(result.Success, Is.True, result.ErrorMessage); + + var value = Expression.Lambda>(result.Value!).Compile()(); + Assert.That(value, Is.EqualTo(expected)); + } + + [Test] + public void Parse_SameStaticMethodImportedFromUnrelatedTypes_ReturnsAmbiguityError() + { + var binder = new DefaultBinder(); + binder.RegisterType(typeof(BaseOverloads), importAsStatic: true); + binder.RegisterType(typeof(UnrelatedOverloads), importAsStatic: true); + + var result = ExpressionParser.Parse("Create(1)", binder); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Does.StartWith("Ambiguous match found") + .And.Contain(nameof(BaseOverloads)).And.Contain(nameof(UnrelatedOverloads))); + } + [TestCase("Both.Count")] [TestCase("Both[0]")] public void Parse_MemberOfUnrelatedBaseInterfaces_ReturnsAmbiguityError(string expression) @@ -952,6 +1058,7 @@ public interface IBaseInterface int Value { get; } string this[int index] { get; } string Name(); + string Pick(int value); string Describe(); // @@ -967,10 +1074,28 @@ public interface IDerivedInterface : IBaseInterface { new string Value { get; } new string Name(); + string Pick(long value); } public interface IListAndReadOnlyList : IList, IReadOnlyList; + public interface IConsumer + { + string Pick(T value); + } + + // + // IConsumer is assignable from IConsumer by contravariance, + // but neither is a base interface of the other. + // + public interface IBothConsumers : IConsumer, IConsumer; + + public class BothConsumers : IBothConsumers + { + string IConsumer.Pick(object value) => "IConsumer.Pick(object)"; + string IConsumer.Pick(string value) => "IConsumer.Pick(string)"; + } + public class InterfaceImplementation : IDerivedInterface { int IBaseInterface.Value => 1; @@ -978,6 +1103,8 @@ public class InterfaceImplementation : IDerivedInterface public string this[int index] => $"item {index}"; string IBaseInterface.Name() => "IBaseInterface.Name"; string IDerivedInterface.Name() => "IDerivedInterface.Name"; + string IBaseInterface.Pick(int value) => "IBaseInterface.Pick(int)"; + string IDerivedInterface.Pick(long value) => "IDerivedInterface.Pick(long)"; public string Describe() => "InterfaceImplementation.Describe"; public override string ToString() => "InterfaceImplementation"; } @@ -988,13 +1115,18 @@ public class InterfaceContext public IReadOnlyList ReadOnly { get; } = new List { 1, 2, 3 }; public IDerivedInterface Derived { get; } = new InterfaceImplementation(); public IListAndReadOnlyList? Both { get; } + public IBothConsumers Consumers { get; } = new BothConsumers(); } private class BaseMembers { + public const int InheritedField = 3; public static int ImportedMember => 1; + public static int InheritedProperty => 4; public readonly int Field = 1; public int Property { get; } = 1; + + public static int InheritedMethod() => 5; } private sealed class DerivedMembers : BaseMembers @@ -1004,6 +1136,77 @@ private sealed class DerivedMembers : BaseMembers public new string Property { get; } = "derived"; } + [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "The tests resolve instance method overloads.")] + private class BaseOverloads + { + public string this[int index] => "BaseOverloads.this[int]"; + + public string Pick(int value) => "BaseOverloads.Pick(int)"; + public string Pick(string value) => "BaseOverloads.Pick(string)"; + public virtual string Overridden(int value) => "BaseOverloads.Overridden(int)"; + public string Optional() => "BaseOverloads.Optional()"; + public string Covariant(int value) => "BaseOverloads.Covariant(int)"; + public virtual object Covariant(long value) => "BaseOverloads.Covariant(long)"; + + public static string Create(int value) => "BaseOverloads.Create(int)"; + } + + [SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "The tests resolve instance method overloads.")] + private sealed class DerivedOverloads : BaseOverloads + { + public string this[long index] => "DerivedOverloads.this[long]"; + + public string Pick(long value) => "DerivedOverloads.Pick(long)"; + + // + // In C#, an override belongs to the class that introduced the method, + // so the overload declared here hides it. + // + public override string Overridden(int value) => "DerivedOverloads.Overridden(int)"; + public string Overridden(long value) => "DerivedOverloads.Overridden(long)"; + public string Optional(int value = 0) => "DerivedOverloads.Optional(int)"; + + // + // A covariant return override also belongs to the base class, so it does not hide + // Covariant(int), although reflection reports it as a new method of this class. + // + public override string Covariant(long value) => "DerivedOverloads.Covariant(long)"; + + public static string Create(long value) => "DerivedOverloads.Create(long)"; + } + + private interface IStaticOverloads + { + static string Create(int value) => "IStaticOverloads.Create(int)"; + } + + // + // Unrelated to IStaticOverloads: in C#, a method of a class other than Object + // hides the methods of every interface. + // + private sealed class ClassOverloads + { + public static string Create(long value) => "ClassOverloads.Create(long)"; + } + + // + // An interface is not a base type of a struct, so its methods are not hidden. + // + private struct StructOverloads : IStaticOverloads + { + public static string Create(long value) => "StructOverloads.Create(long)"; + } + + // + // The base class only makes the hierarchy deeper than that of BaseOverloads. + // + private class UnrelatedBase; + + private sealed class UnrelatedOverloads : UnrelatedBase + { + public static string Create(int value) => "UnrelatedOverloads.Create(int)"; + } + public class LogicalNotContext { public bool Flag { get; } = true;