Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/Ramstack.ExpressionParser/DefaultBinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/Ramstack.ExpressionParser/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ Expression ProcessIndex()
var indexers = new List<PropertyInfo>();
var methods = new List<MethodBase>();

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)
Expand Down
18 changes: 17 additions & 1 deletion src/Ramstack.ExpressionParser/Internal/MethodResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
19 changes: 19 additions & 0 deletions src/Ramstack.ExpressionParser/Internal/ReflectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,25 @@ public static Type MakeNullableType(this Type type) =>
public static bool IsStatic(this Type type) =>
type.IsClass && type.IsAbstract && type.IsSealed;

/// <summary>
/// Returns the types whose members are looked up when a member is accessed through the specified type.
/// </summary>
/// <param name="type">The type through which the member is accessed.</param>
/// <returns>
/// The specified type and, if it is an interface, its base interfaces and <see cref="object" />.
/// </returns>
/// <remarks>
/// For an interface, <see cref="Type.GetMembers()" /> returns only the members the interface declares,
/// while in C# member lookup in an interface also finds the members of its base interfaces and <see cref="object" />.
/// </remarks>
public static IEnumerable<Type> GetMemberLookupTypes(this Type type)
{
if (type.IsInterface)
return [type, ..type.GetInterfaces(), typeof(object)];

return [type];
}

/// <summary>
/// Determines whether the specified member is declared as static.
/// </summary>
Expand Down
97 changes: 97 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Func<InterfaceContext, object>>(body, parameter).Compile()(new InterfaceContext());
Assert.That(value, Is.TypeOf(expected.GetType()).And.EqualTo(expected));
}

[Test]
public void Evaluate_InterfaceContext_BindsMembersOfBaseInterfacesAndObject()
{
IList<int> list = [1, 2, 3];

Assert.That(ExpressionParser.Evaluate<IList<int>, int>("Count", list), Is.EqualTo(3));
Assert.That(ExpressionParser.Evaluate<IList<int>, bool>("Contains(2)", list), Is.True);
Assert.That(ExpressionParser.Evaluate<IList<int>, 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<object?> evaluate, string expected)
{
Expand Down Expand Up @@ -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<int>, IReadOnlyList<int>;

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<int> List { get; } = new List<int> { 1, 2, 3 };
public IReadOnlyList<int> ReadOnly { get; } = new List<int> { 1, 2, 3 };
public IDerivedInterface Derived { get; } = new InterfaceImplementation();
public IListAndReadOnlyList? Both { get; }
}

public class LogicalNotContext
{
public bool Flag { get; } = true;
Expand Down