From da08a092cc2b8a891ade5164ce60ce7f3e7c1e86 Mon Sep 17 00:00:00 2001 From: rameel Date: Fri, 20 Nov 2026 22:54:39 +0500 Subject: [PATCH] binding: look up members of base interfaces and Object for interfaces For an interface, Type.GetMembers and Type.GetMethods return only the members the interface declares. A context member of type IList had no Count, Contains, or GetEnumerator, no interface-typed value had ToString or GetHashCode, and an indexer declared in a base interface was not found. As in C#, also look up the members of the base interfaces and Object. A field or property of a derived interface hides the members with the same name of its base interfaces, and a method hides the method with the same signature of a base interface or Object. A member declared in two unrelated base interfaces, such as Count of an interface that extends both IList and IReadOnlyList, is reported as an ambiguous match. Static members of base interfaces and Object are also found through the interface name. Unqualified names still use only the static members declared by the imported types, as with using static in C#. --- .../DefaultBinder.cs | 15 ++- .../ExpressionBuilder.cs | 2 +- .../Internal/MethodResolver.cs | 18 +++- .../Internal/ReflectionExtensions.cs | 19 ++++ .../ExpressionParserTest.cs | 97 +++++++++++++++++++ 5 files changed, 147 insertions(+), 4 deletions(-) diff --git a/src/Ramstack.ExpressionParser/DefaultBinder.cs b/src/Ramstack.ExpressionParser/DefaultBinder.cs index dbd8b0d..1d0a4b1 100644 --- a/src/Ramstack.ExpressionParser/DefaultBinder.cs +++ b/src/Ramstack.ExpressionParser/DefaultBinder.cs @@ -118,7 +118,7 @@ public void RegisterType(Type type, bool importAsStatic = false) public override MethodInfo? BindToMethod(Type? type, Identifier methodName, Type[] parameterTypes, bool isStatic) { var q = type is not null - ? GetMethods(type, methodName.Name, isStatic) + ? type.GetMemberLookupTypes().SelectMany(t => GetMethods(t, methodName.Name, isStatic)) : s_predefinedTypes .Concat(_types) .Where(t => t.Value.isStatic) @@ -142,7 +142,7 @@ public void RegisterType(Type type, bool importAsStatic = false) ? BindingFlags.Public | BindingFlags.Static : BindingFlags.Public | BindingFlags.Instance; - var q = type?.GetMembers(bindingFlags) + var q = type?.GetMemberLookupTypes().SelectMany(t => t.GetMembers(bindingFlags)) ?? s_predefinedTypes .Concat(_types) .Where(t => t.Value.isStatic) @@ -154,6 +154,17 @@ public void RegisterType(Type type, bool importAsStatic = false) && m.MemberType is MemberTypes.Field or MemberTypes.Property) .ToArray(); + // + // The lookup in an interface includes its base interfaces, so, as in C#, a member + // of a derived interface hides the members with the same name of its base interfaces. + // + if (type?.IsInterface == true && candidates.Length > 1) + candidates = candidates + .Where(m => !candidates.Any(c => + c.DeclaringType != m.DeclaringType + && m.DeclaringType!.IsAssignableFrom(c.DeclaringType))) + .ToArray(); + switch (candidates.Length) { case 0: return null; diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs index 9771f46..d766052 100644 --- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs +++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs @@ -226,7 +226,7 @@ Expression ProcessIndex() var indexers = new List(); var methods = new List(); - foreach (var pi in self.Type.GetProperties()) + foreach (var pi in self.Type.GetMemberLookupTypes().SelectMany(t => t.GetProperties())) { var mi = pi.GetMethod; if (mi?.GetParameters().Length > 0) diff --git a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs index cd916b9..56f4ccc 100644 --- a/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs +++ b/src/Ramstack.ExpressionParser/Internal/MethodResolver.cs @@ -436,9 +436,25 @@ private static int FindMostSpecificMethod( var hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType); var hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); - // The most derived method is the most specific one. + // + // 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) return 2; diff --git a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs index ed7e2fd..6c6907e 100644 --- a/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs +++ b/src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs @@ -48,6 +48,25 @@ public static Type MakeNullableType(this Type type) => public static bool IsStatic(this Type type) => type.IsClass && type.IsAbstract && type.IsSealed; + /// + /// Returns the types whose members are looked up when a member is accessed through the specified type. + /// + /// The type through which the member is accessed. + /// + /// The specified type and, if it is an interface, its base interfaces and . + /// + /// + /// For an interface, returns only the members the interface declares, + /// while in C# member lookup in an interface also finds the members of its base interfaces and . + /// + public static IEnumerable GetMemberLookupTypes(this Type type) + { + if (type.IsInterface) + return [type, ..type.GetInterfaces(), typeof(object)]; + + return [type]; + } + /// /// Determines whether the specified member is declared as static. /// diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs index 1acb1fd..27ec403 100644 --- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs +++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs @@ -206,6 +206,60 @@ public void Evaluate_MemberOfRuntimeContextTypeOnly_Throws() Assert.That(exception!.Message, Is.EqualTo("Cannot resolve symbol 'Extra'.")); } + [TestCase("List.Count", 3)] + [TestCase("List.Contains(2)", true)] + [TestCase("List.GetEnumerator().MoveNext()", true)] + [TestCase("List.GetHashCode() == List.GetHashCode()", true)] + [TestCase("ReadOnly.Count", 3)] + [TestCase("Derived[1]", "item 1")] + [TestCase("Derived.Describe()", "InterfaceImplementation.Describe")] + [TestCase("Derived.ToString()", "InterfaceImplementation")] + [TestCase("Derived.Equals(Derived)", true)] + public void Evaluate_MemberOfBaseInterfaceOrObject_BindsMember(string expression, object expected) => + Assert.That(ExpressionParser.Evaluate(expression, new InterfaceContext()), Is.TypeOf(expected.GetType()).And.EqualTo(expected)); + + [TestCase("Derived.Value", "IDerivedInterface.Value")] + [TestCase("Derived.Name()", "IDerivedInterface.Name")] + public void Evaluate_MemberHiddenByDerivedInterface_BindsMemberOfDerivedInterface(string expression, string expected) => + Assert.That(ExpressionParser.Evaluate(expression, new InterfaceContext()), Is.EqualTo(expected)); + + [TestCase("IDerivedInterface.Create()", "IBaseInterface.Create")] + [TestCase("IDerivedInterface.ReferenceEquals(Derived, Derived)", true)] + public void Evaluate_StaticMemberOfBaseInterfaceOrObject_BindsMember(string expression, object expected) + { + var parameter = Expression.Parameter(typeof(InterfaceContext), "c"); + var binder = new ContextAwareBinder(parameter); + binder.RegisterType(typeof(IDerivedInterface)); + + var result = ExpressionParser.Parse(expression, binder); + Assert.That(result.Success, Is.True, result.ErrorMessage); + + var body = Expression.Convert(result.Value!, typeof(object)); + var value = Expression.Lambda>(body, parameter).Compile()(new InterfaceContext()); + Assert.That(value, Is.TypeOf(expected.GetType()).And.EqualTo(expected)); + } + + [Test] + public void Evaluate_InterfaceContext_BindsMembersOfBaseInterfacesAndObject() + { + IList list = [1, 2, 3]; + + Assert.That(ExpressionParser.Evaluate, int>("Count", list), Is.EqualTo(3)); + Assert.That(ExpressionParser.Evaluate, bool>("Contains(2)", list), Is.True); + Assert.That(ExpressionParser.Evaluate, string>("ToString()", list), Is.EqualTo(list.ToString())); + } + + [TestCase("Both.Count")] + [TestCase("Both[0]")] + public void Parse_MemberOfUnrelatedBaseInterfaces_ReturnsAmbiguityError(string expression) + { + var parameter = Expression.Parameter(typeof(InterfaceContext), "c"); + var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter)); + + Assert.That(result.Success, Is.False); + Assert.That(result.ErrorMessage, Does.StartWith("Ambiguous match found")); + } + [TestCaseSource(nameof(InconvertibleResultSource))] public void Evaluate_ResultNotConvertibleToResultType_ThrowsArgumentException(Func evaluate, string expected) { @@ -834,6 +888,49 @@ public class ValueContext : IValueContext public int Extra { get; } = 2; } + public interface IBaseInterface + { + int Value { get; } + string this[int index] { get; } + string Name(); + string Describe(); + + // + // Declaring ToString in the interface makes the call 'Derived.ToString()' choose between + // this method and Object.ToString, which have the same signature. + // + string ToString(); + + static string Create() => "IBaseInterface.Create"; + } + + public interface IDerivedInterface : IBaseInterface + { + new string Value { get; } + new string Name(); + } + + public interface IListAndReadOnlyList : IList, IReadOnlyList; + + public class InterfaceImplementation : IDerivedInterface + { + int IBaseInterface.Value => 1; + string IDerivedInterface.Value => "IDerivedInterface.Value"; + public string this[int index] => $"item {index}"; + string IBaseInterface.Name() => "IBaseInterface.Name"; + string IDerivedInterface.Name() => "IDerivedInterface.Name"; + public string Describe() => "InterfaceImplementation.Describe"; + public override string ToString() => "InterfaceImplementation"; + } + + public class InterfaceContext + { + public IList List { get; } = new List { 1, 2, 3 }; + public IReadOnlyList ReadOnly { get; } = new List { 1, 2, 3 }; + public IDerivedInterface Derived { get; } = new InterfaceImplementation(); + public IListAndReadOnlyList? Both { get; } + } + public class LogicalNotContext { public bool Flag { get; } = true;