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
29 changes: 28 additions & 1 deletion src/Ramstack.ExpressionParser/ExpressionBuilder.Helpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,34 @@ private object ResolveSymbol(Expr.Reference expr)
Debug.Assert(context is not null || member.IsStatic());
Debug.Assert(context is null || !member.IsStatic());

return Expression.MakeMemberAccess(context, member);
return CreateMemberAccess(context, member);
}

/// <summary>
/// Creates an expression that reads the specified field or property.
/// </summary>
/// <param name="expression">The expression of the instance, or <see langword="null" /> for a static member.</param>
/// <param name="member">The field or property to read.</param>
/// <returns>
/// The <see cref="MemberExpression"/> that reads the member.
/// </returns>
private static MemberExpression CreateMemberAccess(Expression? expression, MemberInfo member)
{
//
// As in C#, a property is read through its get accessor, so a property whose get accessor
// is missing or not public cannot be read, even if its set accessor is public.
//
if (member is PropertyInfo property)
{
var getter = property.GetMethod;
if (getter is null)
Error.MissingGetAccessor(property);

if (!getter.IsPublic)
Error.InaccessibleGetAccessor(property);
}

return Expression.MakeMemberAccess(expression, member);
}

private static Expression? ApplyImplicitConversion(Expression expression, Type conversionType)
Expand Down
20 changes: 14 additions & 6 deletions src/Ramstack.ExpressionParser/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,24 +220,32 @@ Expression ProcessArray()

Expression ProcessIndex()
{
var indexers = new List<PropertyInfo>();
var methods = new List<MethodBase>();

foreach (var pi in self.Type.GetProperties())
{
var mi = pi.GetMethod;
if (mi?.GetParameters().Length > 0)
{
indexers.Add(pi);
methods.Add(mi);
}
}

if (methods.Count == 0)
Error.NonIndexingType(self.Type);

var method = (MethodInfo?)MethodResolver.ResolveMethod(methods.ToArray(), parameterTypes);
if (method is null)
{
var list = self.Type.GetProperties().Where(p => p.GetMethod?.GetParameters().Length > 0);
Error.AmbiguousMatch(list);
}
Error.AmbiguousMatch(indexers);

//
// As in C#, an indexer whose get accessor is not public takes part in overload resolution,
// but cannot be read.
//
if (!method.IsPublic)
Error.InaccessibleGetAccessor(indexers[methods.IndexOf(method)]);

var injectingArguments = CreateInjectingArguments(method, parameters);
return Expression.Call(self, method, injectingArguments);
Expand Down Expand Up @@ -313,7 +321,7 @@ Expression ProcessMemberAccess(Expr.MemberAccess e)
//
// A member accessed through a type is static, so it is accessed without an instance.
//
expression = Expression.MakeMemberAccess(expression, memberInfo);
expression = CreateMemberAccess(expression, memberInfo);
return Invoke(expression, null);
}

Expand Down Expand Up @@ -377,7 +385,7 @@ protected internal override Expression VisitMemberAccess(Expr.MemberAccess expr)
if (expression?.Type.IsSZArray == true && memberInfo.DeclaringType == typeof(Array) && memberInfo.Name == nameof(Array.Length))
return Expression.ArrayLength(expression);

return Expression.MakeMemberAccess(expression, memberInfo);
return CreateMemberAccess(expression, memberInfo);
}

Error.IdentifierExpected(expr.Member);
Expand Down
41 changes: 41 additions & 0 deletions src/Ramstack.ExpressionParser/Internal/Error.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,30 @@ public static void NonIndexingType(Type type)
throw new ParseErrorException(message);
}

/// <summary>
/// Throws a <see cref="ParseErrorException"/> indicating a property or indexer cannot be read
/// because it has no get accessor.
/// </summary>
/// <param name="property">The <see cref="PropertyInfo"/> of the property or indexer.</param>
[DoesNotReturn]
public static void MissingGetAccessor(PropertyInfo property)
{
var message = $"The property or indexer '{FormatProperty(property)}' cannot be used in this context because it lacks the get accessor.";
throw new ParseErrorException(message);
}

/// <summary>
/// Throws a <see cref="ParseErrorException"/> indicating a property or indexer cannot be read
/// because its get accessor is not public.
/// </summary>
/// <param name="property">The <see cref="PropertyInfo"/> of the property or indexer.</param>
[DoesNotReturn]
public static void InaccessibleGetAccessor(PropertyInfo property)
{
var message = $"The property or indexer '{FormatProperty(property)}' cannot be used in this context because the get accessor is inaccessible.";
throw new ParseErrorException(message);
}

/// <summary>
/// Throws a <see cref="ParseErrorException"/> indicating an ambiguous match among multiple candidates.
/// </summary>
Expand All @@ -119,4 +143,21 @@ public static void AmbiguousMatch(IEnumerable<MemberInfo> candidates)
[DoesNotReturn]
public static void Throw(string? message) =>
throw new ParseErrorException(message);

/// <summary>
/// Formats a property as its declaring type and name, or an indexer as its declaring type and parameter types,
/// as in <c>T.Name</c> or <c>T.this[System.Int32]</c>.
/// </summary>
/// <param name="property">The <see cref="PropertyInfo"/> of the property or indexer.</param>
/// <returns>
/// The formatted name.
/// </returns>
private static string FormatProperty(PropertyInfo property)
{
var parameters = property.GetIndexParameters();

return parameters.Length == 0
? $"{property.DeclaringType}.{property.Name}"
: $"{property.DeclaringType}.this[{string.Join(", ", parameters.Select(p => p.ParameterType))}]";
}
}
65 changes: 65 additions & 0 deletions tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,44 @@ public void Parse_TypeWithWriteOnlyIndexer_ReturnsNonIndexingError()
$"Cannot apply indexing with [] to an expression of type '{typeof(WriteOnlyIndexer)}'."));
}

[TestCase("PrivateGetter", "AccessorContext.PrivateGetter")]
[TestCase("ProtectedGetter", "AccessorContext.ProtectedGetter")]
[TestCase("InternalGetter", "AccessorContext.InternalGetter")]
[TestCase("Self.PrivateGetter", "AccessorContext.PrivateGetter")]
[TestCase("PrivateGetter.Length", "AccessorContext.PrivateGetter")]
[TestCase("StaticPrivateGetter", "AccessorContext.StaticPrivateGetter")]
[TestCase("AccessorContext.StaticPrivateGetter", "AccessorContext.StaticPrivateGetter")]
[TestCase("PrivateDelegate(1)", "AccessorContext.PrivateDelegate")]
[TestCase("PrivateIndexer[1]", "PrivateGetterIndexer.this[System.Int32]")]
[TestCase("Overloaded[1]", "OverloadedIndexer.this[System.Int32]")]
public void Parse_NonPublicGetAccessor_ReturnsError(string expression, string property)
{
var parameter = Expression.Parameter(typeof(AccessorContext), "c");
var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter));

Assert.That(result.Success, Is.False);
Assert.That(result.ErrorMessage, Is.EqualTo(
$"The property or indexer '{typeof(ExpressionParserTest)}+{property}' "
+ "cannot be used in this context because the get accessor is inaccessible."));
}

[TestCase("WriteOnly")]
[TestCase("WriteOnly.Length")]
[TestCase("Self.WriteOnly")]
public void Parse_PropertyWithoutGetAccessor_ReturnsError(string expression)
{
var parameter = Expression.Parameter(typeof(AccessorContext), "c");
var result = ExpressionParser.Parse(expression, new ContextAwareBinder(parameter));

Assert.That(result.Success, Is.False);
Assert.That(result.ErrorMessage, Is.EqualTo(
$"The property or indexer '{typeof(AccessorContext)}.WriteOnly' cannot be used in this context because it lacks the get accessor."));
}

[Test]
public void Evaluate_IndexerWithPublicGetAccessor_ReturnsValue() =>
Assert.That(ExpressionParser.Evaluate("Overloaded[1L]", new AccessorContext()), Is.EqualTo("long 1"));

[TestCase("NullInt ?? 1", typeof(int), 1)]
[TestCase("NullableInt ?? 1", typeof(int), 5)]
[TestCase("NullInt ?? NullableInt", typeof(int?), 5)]
Expand Down Expand Up @@ -755,6 +793,33 @@ public class WriteOnlyIndexer
public string this[int index] { set { } }
}

public class AccessorContext
{
private string _value = "value";
private Func<int, int> _delegate = x => x;

public string PrivateGetter { private get => _value; set => _value = value; }
public string ProtectedGetter { protected get => _value; set => _value = value; }
public string InternalGetter { internal get => _value; set => _value = value; }
public string WriteOnly { set => _value = value; }
public static string StaticPrivateGetter { private get => "static"; set { } }
public Func<int, int> PrivateDelegate { private get => _delegate; set => _delegate = value; }
public PrivateGetterIndexer PrivateIndexer { get; } = new();
public OverloadedIndexer Overloaded { get; } = new();
public AccessorContext Self => this;
}

public class PrivateGetterIndexer
{
public string this[int index] { private get => "private"; set { } }
}

public class OverloadedIndexer
{
public string this[int index] { private get => "private"; set { } }
public string this[long index] => $"long {index}";
}

public class ParamArrayContext
{
public string[] Words { get; } = ["a", "b"];
Expand Down
Loading