Table of Contents

Architecture

The entire process of evaluating an expression can be demonstrated at this flowchart:

flowchart TB

A["1+1"] -->|Parsing| B("new BinaryExpression(new ValueExpression(1), new ValueExpression(1), BinaryExpressionType.Plus)")
B --> |Evaluation|2

Domain

The NCalc.Domain assembly contains the expression tree model and the visitor contract:

Parsing

Parsing is the process of analyzing the input expression and converting it into a structured format that can be easily evaluated. We use Parlot to handle parsing, but you can use any parser you want if you implement the interface ILogicalExpressionFactory. For our example, "1+1", the parsing step converts the string into an abstract syntax tree (AST). This tree is made up of different types of expressions, such as binary expressions, value expressions, or even functions. Our AST is represented by the LogicalExpression class.

Parsing is isolated in the NCalc.Parser assembly. It contains the default Parlot parser, the parser context, parser options, and argument separator configuration. The parser depends only on the AST contracts from NCalc.Domain. NCalc.Core uses the parser through ILogicalExpressionFactory, so applications can keep using Expression without referencing parser internals directly.

Source-generated parser

NCalc defines its Fluent grammar in LogicalExpressionParser.parlot.cs, a build-only file. The Parlot source generator implements a direct partial parsing method and emits internal support code into NCalc.Parser. The grammar factory is not compiled into the application, and NCalc packages do not depend on the Parlot runtime or analyzer. No interceptor configuration or runtime parser compilation is needed.

The source generator and the benchmark-only Parlot runtime use the same preview version, pinned in Directory.Packages.props and restored from the Feedz source configured in nuget.config.

Parsing options are supplied through ExpressionConfiguration.Parsing when using Expression. The lower-level parser API accepts the same options directly:

using System.Globalization;
using NCalc;
var options = new LogicalExpressionParserOptions
{
    FloatingPointNumberType = FloatingPointNumberType.Decimal,
    ArgumentSeparator = ArgumentSeparator.Semicolon
};

var logicalExpression = LogicalExpressionParser.Parse(
    "Max(1.5; 2.5)", options, CultureInfo.InvariantCulture);
var expression = new Expression(logicalExpression, ExpressionOptions.DecimalAsDefault);
var result = expression.Evaluate(); // 2.5m

Culture, argument separators, numeric types, character handling, and DisallowSingleEquals are supplied on every parse. No parser instance, grammar construction, or parser-instance cache is needed. Custom cultures with the same name remain independent. If culture is omitted, the current culture is resolved at the time of the call. Do not mutate a culture concurrently with parsing.

Parse(LogicalExpressionParseContext, CultureInfo?) remains available as a convenience overload. The context is now an NCalc-owned holder for input, options, and cancellation, not a Parlot context. The Parlot-returning GetOrCreateExpressionParser API is removed; callers should use Parse instead. Cancellation is checked cooperatively during parsing and propagates as OperationCanceledException from the parser API. Grammar callbacks retain NCalc parser exceptions and error positions.

NCalc.Parser provides .NET Standard 2.0, .NET 8, and .NET 10 assets. NCalc's .NET Framework 4.6.2 target uses the .NET Standard 2.0 parser asset and its System.Memory compatibility dependency. The parser package includes Parlot's BSD license in THIRD-PARTY-NOTICES.txt for the generated support.

Debugging the parser

Major grammar nodes are named with Parlot's .Named(...), including RelationalOperator, Coalescing, Function, and the date/time parsers. Generated helper comments contain these names, making it easier to map a generated method to its grammar rule. Generated identifiers and support types remain implementation details.

Generated files are emitted below src/NCalc.Parser/obj/<configuration>/<framework>/Parlot.SourceGenerator/. Parlot emits #line mappings to .parlot.cs callbacks, and named conversion methods such as ParseDate, ParseTime, and ParseSingleQuotedString can be debugged in LogicalExpressionParser.Helpers.cs. These helpers use only BCL and NCalc types. IDE analysis receives generated partial-method stubs without executing the grammar; a normal build produces the actual parser implementation.

Evaluation

Evaluation refers to the process of determining the value of an expression. We use the visitor pattern at evaluation. This pattern allows you to add new operations to existing object structures without modifying those structures. With the method Accept<T>(ILogicalExpressionVisitor<T>) is possible to accept any kind of visitor that implements ILogicalExpressionVisitor<T>. Example implementations include EvaluationVisitor that returns a object and SerializationVisitor that converts the AST into a string.

If you are creating your custom implementation, beware it should be stateless to be easier to debug and read. This is enforced by the PureAttribute and generic return at the Accept<T>(ILogicalExpressionVisitor<T>) method.

Expression Class

This is the main class of NCalc. It abstracts the process of parsing and evaluating the string. The method Evaluate(CancellationToken) returns the actual value of its string representation.

Example:

var expression = new Expression("2 * 3");
var result = expression.Evaluate();
  
Console.WriteLine(result);

This example above first creates an instance of Expression using a valued constructor. This constructor takes a string as parameter. Then the method Evaluate(CancellationToken) is called to parse the string and returns the actual value represented by the string.

To create expressions you can combine several Operators and Values.

Learn More

For additional information on the technique we used to create this library please read this article.

Search NCalc

Find guides, language features, and API symbols.