diff --git a/Directory.Packages.props b/Directory.Packages.props
index e56b9af..56e638b 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -9,6 +9,6 @@
-
+
\ No newline at end of file
diff --git a/README.md b/README.md
index 218b8d9..26a7951 100644
--- a/README.md
+++ b/README.md
@@ -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 |
diff --git a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
index 16760db..7c8e1cf 100644
--- a/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionBuilder.cs
@@ -16,6 +16,19 @@ public partial class ExpressionBuilder(Binder binder) : ExprVisitor
///
public Binder Binder { get; } = binder;
+ ///
+ ///
+ /// Throws a if the thread's stack is too small
+ /// to visit the expression safely.
+ ///
+ public override Expression Visit(Expr expr)
+ {
+ if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
+ Error.Throw("The expression is nested too deeply.");
+
+ return base.Visit(expr);
+ }
+
///
protected internal override Expression VisitReference(Expr.Reference expr)
{
diff --git a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
index 9c71eee..46bc185 100644
--- a/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
+++ b/src/Ramstack.ExpressionParser/ExpressionParser.Parser.cs
@@ -6,9 +6,27 @@ namespace Ramstack.Parsing;
partial class ExpressionParser
{
+ ///
+ /// The maximum depth of an expression tree produced by the parser.
+ ///
+ ///
+ /// The expression builder, the ToString 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.
+ ///
+ private const int MaxDepth = 256;
+
///
/// Gets the sub-expression parser, which serves as the base parser for expressions.
///
+ ///
+ /// 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 a + b + c counts as deeply as the nested expression ((a + b) + 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.
+ ///
public static Parser Subparser { get; } = CreateParser();
///
@@ -131,7 +149,12 @@ private static Parser 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 =
@@ -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();
- conditional_expression.Parser =
+ var conditional_expression =
Seq(
null_coalesce_expression,
Seq(
L('?'), S,
expression,
L(':').Or(Fail("Expected ':'")), S,
- conditional_expression.Or(Fail("Expected expression"))
+ expression.Or(Fail("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(conditional_expression);
+
+ return S.Then(expression).Do(EnsureDepth);
+ }
+
+ ///
+ /// Stops parsing with a fatal error if the specified expression tree is deeper than .
+ ///
+ /// The expression tree to check.
+ ///
+ /// The specified expression tree.
+ ///
+ 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) =>
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs
index c2f1561..210fd3c 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Binary.cs
@@ -5,7 +5,8 @@ partial class Expr
///
/// Represents a binary operation expression in an expression tree, consisting of an operator and two operands.
///
- 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)
{
///
/// Gets the operator of the binary expression.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs
index b1141e1..81282c7 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Call.cs
@@ -7,7 +7,8 @@ partial class Expr
///
[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 parameters) : Expr(ExprKind.Call)
+ public sealed class Call(Expr expression, IReadOnlyList parameters)
+ : Expr(ExprKind.Call, ComputeDepth(expression, parameters))
{
///
/// Gets the expression being called, such as a method or function reference.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs
index 077b210..057c15d 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Conditional.cs
@@ -5,7 +5,8 @@ partial class Expr
///
/// Represents a conditional (ternary) expression in an expression tree.
///
- 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)
{
///
/// Gets the condition expression evaluated to determine the outcome.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs
index 42df46c..810b30a 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Index.cs
@@ -5,7 +5,8 @@ partial class Expr
///
/// Represents an indexing operation in an expression tree, such as accessing an array or a parameterized property.
///
- public sealed class Indexer(Expr expression, IReadOnlyList parameters) : Expr(ExprKind.Index)
+ public sealed class Indexer(Expr expression, IReadOnlyList parameters)
+ : Expr(ExprKind.Index, ComputeDepth(expression, parameters))
{
///
/// Gets the expression being indexed, such as an array or object with an indexer.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs
index 4017429..3428cc2 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.MemberAccess.cs
@@ -6,7 +6,8 @@ partial class Expr
/// Represents a member access operation in an expression tree,
/// such as accessing a field or property like obj.Property.
///
- 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)
{
///
/// Gets the expression whose member is being accessed.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs
index 36ad1c2..bd21709 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Parenthesized.cs
@@ -6,7 +6,8 @@ partial class Expr
/// Represents a parenthesized expression in an expression tree, used to enforce precedence or grouping.
///
/// The enclosed within parentheses.
- public sealed class Parenthesized(Expr expression) : Expr(ExprKind.Parenthesized)
+ public sealed class Parenthesized(Expr expression)
+ : Expr(ExprKind.Parenthesized, expression.Depth + 1)
{
///
/// Gets the expression enclosed within parentheses.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs
index 37cf3e3..b779d61 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.Unary.cs
@@ -8,7 +8,8 @@ partial class Expr
/// The representing the unary operator, e.g., "-" or "int".
/// The specifying the kind of unary operation (e.g., arithmetic or conversion).
/// The on which the unary operation is applied.
- 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)
{
///
/// Gets the operator of the unary expression.
diff --git a/src/Ramstack.ExpressionParser/Expressions/Expr.cs b/src/Ramstack.ExpressionParser/Expressions/Expr.cs
index 59ad12a..50294f8 100644
--- a/src/Ramstack.ExpressionParser/Expressions/Expr.cs
+++ b/src/Ramstack.ExpressionParser/Expressions/Expr.cs
@@ -13,6 +13,45 @@ public abstract partial class Expr(ExprKind kind)
///
public ExprKind Kind { get; init; } = kind;
+ ///
+ /// Gets the depth of this expression node.
+ ///
+ ///
+ /// One for a node without child expressions; otherwise, one more than the depth of its deepest child.
+ ///
+ ///
+ /// The depth is computed from the depths of the children when the node is created,
+ /// so the tree is not traversed recursively.
+ ///
+ internal int Depth { get; } = 1;
+
+ ///
+ /// Initializes a new instance of the class with the specified kind and depth.
+ ///
+ /// The kind of this expression node.
+ /// The depth of this expression node.
+ private Expr(ExprKind kind, int depth) : this(kind) =>
+ Depth = depth;
+
+ ///
+ /// Computes the depth of a node whose children are the specified expression and the specified list of expressions.
+ ///
+ /// The first child expression.
+ /// The remaining child expressions.
+ ///
+ /// One more than the depth of the deepest child.
+ ///
+ private static int ComputeDepth(Expr expression, IReadOnlyList 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;
+ }
+
///
/// Deconstructs the expression into its kind.
///
diff --git a/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs b/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs
new file mode 100644
index 0000000..2b317c0
--- /dev/null
+++ b/src/Ramstack.ExpressionParser/Parsers/StackGuardParser.cs
@@ -0,0 +1,27 @@
+namespace Ramstack.Parsing.Parsers;
+
+///
+/// Represents a parser that stops parsing with a fatal error when the thread's stack
+/// is too small to run the underlying parser safely.
+///
+///
+/// Wrap the parser through which a recursive grammar re-enters itself, so that deeply nested input
+/// produces a parse error instead of a .
+///
+/// The type of the value produced by the underlying parser.
+/// The underlying parser.
+internal sealed class StackGuardParser(Parser parser) : Parser
+{
+ ///
+ 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.
+ //
+}
diff --git a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
index 0c99636..3b93928 100644
--- a/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
+++ b/tests/Ramstack.ExpressionParser.Tests/ExpressionParserTest.cs
@@ -1,5 +1,8 @@
using System.Globalization;
using System.Linq.Expressions;
+using System.Runtime.ExceptionServices;
+
+using Ramstack.Parsing.Expressions;
namespace Ramstack.Parsing;
@@ -34,6 +37,72 @@ private static List