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
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
<PackageVersion Include="MinVer" Version="6.0.0" />
<PackageVersion Include="NUnit" Version="4.3.2" />
<PackageVersion Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageVersion Include="Ramstack.Parsing" Version="1.0.1" />
<PackageVersion Include="Ramstack.Parsing" Version="1.1.0" />
</ItemGroup>
</Project>
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ public bool IsEnabled(LogEvent logEvent)

This makes it easy to create dynamic, human-readable expressions for filtering or evaluating objects at runtime.

### Limits

An expression tree can be at most 256 levels deep. Each operator, member access, call, indexer,
and pair of parentheses adds a level, so `a + b + c` counts as deeply as `((a + b) + c)`.
Parsing fails with an error rather than crashing the process when an expression is deeper than that,
or when it is nested too deeply to fit on the stack of the current thread.

Parsing an expression takes time and memory that grow with its length,
so limit the length of expressions that come from untrusted sources.

## Supported Versions

| | Version |
Expand Down
13 changes: 13 additions & 0 deletions src/Ramstack.ExpressionParser/ExpressionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@ public partial class ExpressionBuilder(Binder binder) : ExprVisitor<Expression>
/// </summary>
public Binder Binder { get; } = binder;

/// <inheritdoc />
/// <remarks>
/// Throws a <see cref="ParseErrorException"/> if the thread's stack is too small
/// to visit the expression safely.
/// </remarks>
public override Expression Visit(Expr expr)
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
Error.Throw("The expression is nested too deeply.");

return base.Visit(expr);
}

/// <inheritdoc />
protected internal override Expression VisitReference(Expr.Reference expr)
{
Expand Down
54 changes: 48 additions & 6 deletions src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,27 @@ namespace Ramstack.Parsing;

partial class ExpressionParser
{
/// <summary>
/// The maximum depth of an expression tree produced by the parser.
/// </summary>
/// <remarks>
/// The expression builder, the <c>ToString</c> methods of the expression nodes, and other visitors
/// process the tree recursively.
/// On a 1 MB stack, the expression builder runs out of stack at a depth of about 1,000 in a Debug build,
/// so the limit leaves room for the caller's own stack frames.
/// </remarks>
private const int MaxDepth = 256;

/// <summary>
/// Gets the sub-expression parser, which serves as the base parser for expressions.
/// </summary>
/// <remarks>
/// Parsing stops with a fatal error if the expression tree is deeper than 256 levels.
/// Each operator, member access, call, indexer, and pair of parentheses adds a level,
/// so a chain such as <c>a + b + c</c> counts as deeply as the nested expression <c>((a + b) + c)</c>.
/// Parsing also stops with a fatal error if the thread's stack runs short. On a small stack, this can happen
/// before the limit is reached for deeply nested parentheses, arguments, indexers, and conditional expressions.
/// </remarks>
public static Parser<Expr> Subparser { get; } = CreateParser();

/// <summary>
Expand Down Expand Up @@ -131,7 +149,12 @@ private static Parser<Expr> CreateParser()
expr = indexer
? new Expr.Indexer(expr, parameters)
: new Expr.Call(expr, parameters);
return expr;

//
// HijackMemberExpression processes this chain recursively during parsing,
// so check the depth before the chain reaches it.
//
return EnsureDepth(expr);
});

var member_expression =
Expand Down Expand Up @@ -241,25 +264,44 @@ static Expr HijackMemberExpression(Expr result, Expr value)
L("??").ThenIgnore(S).Do(CreateIdentifier),
(lhs, rhs, op) => new Expr.Binary(op, lhs, rhs));

var conditional_expression = Deferred<Expr>();
conditional_expression.Parser =
var conditional_expression =
Seq(
null_coalesce_expression,
Seq(
L('?'), S,
expression,
L(':').Or(Fail<char>("Expected ':'")), S,
conditional_expression.Or(Fail<Expr>("Expected expression"))
expression.Or(Fail<Expr>("Expected expression"))
).Optional()
).Do(Expr (Expr condition, OptionalValue<(char, Unit, Expr @true, char, Unit, Expr @false)> optional) =>
optional.HasValue
? new Expr.Conditional(condition, optional.Value.@true, optional.Value.@false)
: condition);

//
// Every recursion of the grammar (parentheses, arguments, indexers, and both branches
// of a conditional expression) re-enters it through this parser, so a single check
// protects the parser from a stack overflow on deeply nested input.
//
expression.Parser =
conditional_expression;
new StackGuardParser<Expr>(conditional_expression);

return S.Then(expression).Do(EnsureDepth);
}

/// <summary>
/// Stops parsing with a fatal error if the specified expression tree is deeper than <see cref="MaxDepth"/>.
/// </summary>
/// <param name="expr">The expression tree to check.</param>
/// <returns>
/// The specified expression tree.
/// </returns>
private static Expr EnsureDepth(Expr expr)
{
if (expr.Depth > MaxDepth)
FatalError($"The expression exceeds the maximum depth of {MaxDepth}.");

return S.Then(expression);
return expr;
}

private static Identifier CreateIdentifier(string v) =>
Expand Down
3 changes: 2 additions & 1 deletion src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ partial class Expr
/// <summary>
/// Represents a binary operation expression in an expression tree, consisting of an operator and two operands.
/// </summary>
public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs) : Expr(ExprKind.Binary)
public sealed class Binary(Identifier @operator, Expr lhs, Expr rhs)
: Expr(ExprKind.Binary, Math.Max(lhs.Depth, rhs.Depth) + 1)
{
/// <summary>
/// Gets the operator of the binary expression.
Expand Down
3 changes: 2 additions & 1 deletion src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ partial class Expr
/// </summary>
[SuppressMessage("Naming", "CA1716:Identifiers should not match keywords",
Justification = "The type is named after the ExprKind.Call expression kind, and renaming it would break the public API.")]
public sealed class Call(Expr expression, IReadOnlyList<Expr> parameters) : Expr(ExprKind.Call)
public sealed class Call(Expr expression, IReadOnlyList<Expr> parameters)
: Expr(ExprKind.Call, ComputeDepth(expression, parameters))
{
/// <summary>
/// Gets the expression being called, such as a method or function reference.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ partial class Expr
/// <summary>
/// Represents a conditional (ternary) expression in an expression tree.
/// </summary>
public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse) : Expr(ExprKind.Conditional)
public sealed class Conditional(Expr test, Expr ifTrue, Expr ifFalse)
: Expr(ExprKind.Conditional, Math.Max(test.Depth, Math.Max(ifTrue.Depth, ifFalse.Depth)) + 1)
{
/// <summary>
/// Gets the condition expression evaluated to determine the outcome.
Expand Down
3 changes: 2 additions & 1 deletion src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ partial class Expr
/// <summary>
/// Represents an indexing operation in an expression tree, such as accessing an array or a parameterized property.
/// </summary>
public sealed class Indexer(Expr expression, IReadOnlyList<Expr> parameters) : Expr(ExprKind.Index)
public sealed class Indexer(Expr expression, IReadOnlyList<Expr> parameters)
: Expr(ExprKind.Index, ComputeDepth(expression, parameters))
{
/// <summary>
/// Gets the expression being indexed, such as an array or object with an indexer.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ partial class Expr
/// Represents a member access operation in an expression tree,
/// such as accessing a field or property like <c>obj.Property</c>.
/// </summary>
public sealed class MemberAccess(Expr expression, Expr member) : Expr(ExprKind.MemberAccess)
public sealed class MemberAccess(Expr expression, Expr member)
: Expr(ExprKind.MemberAccess, Math.Max(expression.Depth, member.Depth) + 1)
{
/// <summary>
/// Gets the expression whose member is being accessed.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ partial class Expr
/// Represents a parenthesized expression in an expression tree, used to enforce precedence or grouping.
/// </summary>
/// <param name="expression">The <see cref="Expr"/> enclosed within parentheses.</param>
public sealed class Parenthesized(Expr expression) : Expr(ExprKind.Parenthesized)
public sealed class Parenthesized(Expr expression)
: Expr(ExprKind.Parenthesized, expression.Depth + 1)
{
/// <summary>
/// Gets the expression enclosed within parentheses.
Expand Down
3 changes: 2 additions & 1 deletion src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ partial class Expr
/// <param name="operator">The <see cref="Identifier"/> representing the unary operator, e.g., <c>"-"</c> or <c>"int"</c>.</param>
/// <param name="unaryType">The <see cref="UnaryType"/> specifying the kind of unary operation (e.g., arithmetic or conversion).</param>
/// <param name="operand">The <see cref="Expr"/> on which the unary operation is applied.</param>
public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand) : Expr(ExprKind.Unary)
public sealed class Unary(Identifier @operator, UnaryType unaryType, Expr operand)
: Expr(ExprKind.Unary, operand.Depth + 1)
{
/// <summary>
/// Gets the operator of the unary expression.
Expand Down
39 changes: 39 additions & 0 deletions src/Ramstack.ExpressionParser/Expressions/Expr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,45 @@ public abstract partial class Expr(ExprKind kind)
/// </value>
public ExprKind Kind { get; init; } = kind;

/// <summary>
/// Gets the depth of this expression node.
/// </summary>
/// <value>
/// One for a node without child expressions; otherwise, one more than the depth of its deepest child.
/// </value>
/// <remarks>
/// The depth is computed from the depths of the children when the node is created,
/// so the tree is not traversed recursively.
/// </remarks>
internal int Depth { get; } = 1;

/// <summary>
/// Initializes a new instance of the <see cref="Expr"/> class with the specified kind and depth.
/// </summary>
/// <param name="kind">The kind of this expression node.</param>
/// <param name="depth">The depth of this expression node.</param>
private Expr(ExprKind kind, int depth) : this(kind) =>
Depth = depth;

/// <summary>
/// Computes the depth of a node whose children are the specified expression and the specified list of expressions.
/// </summary>
/// <param name="expression">The first child expression.</param>
/// <param name="list">The remaining child expressions.</param>
/// <returns>
/// One more than the depth of the deepest child.
/// </returns>
private static int ComputeDepth(Expr expression, IReadOnlyList<Expr> list)
{
var depth = expression.Depth;
var count = list.Count;

for (var i = 0; i < count; i++)
depth = Math.Max(depth, list[i].Depth);

return depth + 1;
}

/// <summary>
/// Deconstructs the expression into its kind.
/// </summary>
Expand Down
27 changes: 27 additions & 0 deletions src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
namespace Ramstack.Parsing.Parsers;

/// <summary>
/// Represents a parser that stops parsing with a fatal error when the thread's stack
/// is too small to run the underlying parser safely.
/// </summary>
/// <remarks>
/// Wrap the parser through which a recursive grammar re-enters itself, so that deeply nested input
/// produces a parse error instead of a <see cref="StackOverflowException"/>.
/// </remarks>
/// <typeparam name="T">The type of the value produced by the underlying parser.</typeparam>
/// <param name="parser">The underlying parser.</param>
internal sealed class StackGuardParser<T>(Parser<T> parser) : Parser<T>
{
/// <inheritdoc />
public override bool TryParse(ref ParseContext context, [NotNullWhen(true)] out T? value)
{
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
Parser.FatalError("The expression is nested too deeply.");

return parser.TryParse(ref context, out value);
}

//
// NOTE: The default void wrapper calls TryParse, so the check also runs when the value is discarded.
//
}
Loading
Loading