DotGram.ExpressionLanguage 0.3.0

dotnet add package DotGram.ExpressionLanguage --version 0.3.0
                    
NuGet\Install-Package DotGram.ExpressionLanguage -Version 0.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DotGram.ExpressionLanguage" Version="0.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DotGram.ExpressionLanguage" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="DotGram.ExpressionLanguage" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DotGram.ExpressionLanguage --version 0.3.0
                    
#r "nuget: DotGram.ExpressionLanguage, 0.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DotGram.ExpressionLanguage@0.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DotGram.ExpressionLanguage&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=DotGram.ExpressionLanguage&version=0.3.0
                    
Install as a Cake Tool

DotGram.ExpressionLanguage

A C#-style expression language written in .gram, compiled into System.Linq.Expressions trees.

It is an ordinary C# library. .Gram generated the parser into this assembly when it was compiled, so nothing here carries a parser runtime, and neither does anything that references it.

using System;

using DotGram.ExpressionLanguage;

var square = ExpressionParser.Compile<Func<int, int>>("(int x) => x * x - 1");

square(3); // 8

It is not a sandbox: do not compile text you do not trust. See It is not a sandbox below.

It reads C#'s operators, at C#'s precedence, and its literals down to the digit separator and the verbatim string. Past expressions it has typed locals, blocks, if, while, do, for, switch — the statement and x switch { 1 or 2 => …, _ => … } — try/catch/finally, throw, break, continue and return, and past the keywords it has members, calls, indexers, new with initializers, tuples, generic types, nullable value types, is, as, casts and checked:

var calculate = ExpressionParser.Compile<Func<int, int, int>>(
    """
    (int x, int y) =>
    {
        int sum = x + y;
        return sum * sum;
    }
    """);

calculate(2, 3); // 25

Or keep the expression tree instead of compiling it:

var expression = ExpressionParser.Parse("(double x) => x / 2.0");

Console.WriteLine(expression);   // x => (x / 2)

Or ask, rather than catch: TryParse answers for everything Parse would throw for — text that is not this language, and text that is and means nothing, such as a name nothing declares or an operator its operands do not support.

var match = ExpressionParser.TryParse("(string s) => s - 1");

if (!match.IsSuccess)                    // there is no minus over a string
    Console.WriteLine(match.Error);      // what Expression.Subtract said about String and Int32

Compile, Parse and TryParse may all be called from any number of threads at once — the generated parser's own contract — and the member-resolution caches behind name and overload lookups are shared across every call and thread, kept in their own concurrent tables rather than per call.

A type named rather than spelled as a keyword is found the way C# finds one: written whole, or through a using at the top of the text. Five namespaces are there already — the set a new project gets: System, System.Collections.Generic, System.Linq, System.Text and System.Threading.Tasks — and a text's own usings are its own, so the next text starts with those five again and nothing more. ResolutionScope.DefaultImports names them, and ResolutionScope.WithoutDefaultImports() is a scope that leaves them out. A using may also give a name to one type or one namespace (using L = System.Collections.Generic.List<int>;), or bring a type's static members, nested types and extension methods into reach as bare names (using static System.Math; () => Abs(-2)). A name the text itself declares wins over one a using static gives, as in C#; and static is a keyword here, as it is in C#, so nothing may be named it. What a text can name is what C# written in the calling assembly could: public types, and that assembly's own internal types and members. A full name that two referenced assemblies declare as two different types is refused where it is used, naming both assemblies, as C# refuses it (CS0433). One type that several assemblies answer for, as a facade forwards System.Object, is one type; and the calling assembly's own type wins over a reference's, as the compilation's does in C#.

using System.Collections.Generic;

// `System.Collections.Generic` is one of the five, so the text needs no `using` of its own.
var count = ExpressionParser.Compile<Func<IList<int>, int>>("(IList<int> l) => l.Count");

// One it does not get, it says itself.
var named = ExpressionParser.Compile<Func<string>>(
    """
    using System.Globalization;

    () => CultureInfo.InvariantCulture.Name
    """);

Conversions, operators and overloads follow C#'s rules: x + 1.5 over an int is a double, byte b = 1 fits, and Math.Sqrt(x) finds the double overload. A generic method takes its type arguments from its arguments, an extension method is found through a using, and a lambda that says no types takes them from the overload it is handed to, so a.Where(n => n > 1).Sum() reads as it does in C#. The lambda a text IS takes them the same way from the delegate it is compiled to, so Compile<Func<int, int>>("x => x * x") reads with no types written at all. Where it is not C# — a method is never called with its type arguments written, and a constant is folded only across a minus — is written down, with the reason for each, at the top of the file below.

Where a name is looked for is the caller's to say. By default it is the calling assembly and what it references — what a compilation of that assembly would see — so the same text answers the same whatever else the process has loaded. ResolutionScope.Of(caller, plugin) widens that, WithoutInternals() reads as another assembly would, and what a name MEANS stays C#'s either way. A caller loaded into an AssemblyLoadContext of its own has its references found in that context, as the runtime finds them for its own code.

The grammar calls System.Linq.Expressions factories directly. There is no intermediate AST specific to .Gram that must later be translated into an expression tree — which also means a factory that does not exist, or one handed the wrong type, is a C# error on the line of the grammar that asked for it rather than an exception at run time.

The grammar and the C# it calls are one file, ExpressionParser.cs.

It is not a sandbox

Parse only text you would run as code. A text can name any type the reading can reach and call any member on it — the file system, the process, reflection — and what it compiles to runs with the host's permissions, in the host's process, for as long as the delegate is called. There is no allow-list, no timeout and no quota, and none is planned: this compiles expressions, it does not contain them. Reading a text can already run code: a constant converted through a user-defined implicit operator is converted while the text is read.

That is the same position System.Linq.Expressions itself takes, and the same one CSharpScript takes. It matters here because the input LOOKS like data — a formula in a configuration file, a rule typed into a form — and a formula from somewhere you do not control is code from somewhere you do not control.

If the text comes from a user, the answer is not to inspect it before parsing. It is to run it where it can do no harm: a process of its own, with the rights you are willing to lose.

Taking it

dotnet add package DotGram.ExpressionLanguage

There is no companion runtime package, and no generator to install alongside it: the parser was generated when this assembly was compiled.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

  • net10.0

    • No dependencies.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on DotGram.ExpressionLanguage:

Package Downloads
DotGram.Finance

FIX 4.2, 4.4 and 5.0 SP2 tag-value parsing and validation: the wire read by a DotGram grammar, and each version's typed messages and checks generated from the FIX repository.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0 118 11/15/2026
0.2.0 167 10/1/2026
0.1.0 120 9/15/2026

Since 0.2.0. The language reads more of C#'s initializers, with, target-typed new and nullable types, refuses what C# refuses in them, and parses faster.

BREAKING CHANGES, and what to do

- Initializers are read as C# reads them, so texts 0.2.0 accepted are refused: an entry of a member initializer that is not Name = … (CS0747); an assignment as an element of a collection initializer, { 1, x = 2 }, { b.Capacity = 2 }, { x += 1 } - 0.2.0 read x = … as an assignment to a variable and added it (write the assignment in parentheses, { (x = 1), 2 }, to keep it an element); a member set twice in one initializer (CS1912); an initializer of the members of a property of a value type (CS1918); a collection initializer on a type that is not IEnumerable (CS1922); an initializer that assigns through a setter the text cannot call or a property with none (CS0200) or a read-only field (CS0191); an object creation that leaves a required member unset (CS9035).
- A switch expression with no natural type as the operand of a plain operator (1 + (x switch { … }), !(x switch { … })) is refused, naming the two arms that meet in nothing (CS8506), where it reached the operator's factory with no type. String concatenation still takes it, boxed to object.
- A member's own initializer, Items = { 1, 2 }, reads the member once for each entry inside it, as C# does, where it read it once for all; the tree is then a block of assignments, not a MemberInit.
- The public type ExpressionParser.ParserInput<T> is removed; nothing public took or returned it.
- ExpressionParser.SourceSpan is no longer public; nothing public took or returned it.
- ExpressionParser.Scan, the scanner of its lexer, is no longer public: the kind it gave was the grammar's own numbering of its tokens, which changed with the grammar. Migration: none in the package; a caller that cut text into tokens with it has no replacement.

NEW

- A trailing comma after the last entry of an object, collection or array initializer; empty braces as an object initializer that sets nothing (new List<int> { }, Items = { }); indexers among members (new Dictionary<int, int> { [1] = 2 }), built as a block of assignments in C#'s order.
- new[] { 1, 2L }, typed by the one type its elements convert to (CS0826 where there is none).
- x with { Name = value, … } over a record class or a struct (CS8858 for any other type); with stays a name a variable may have.
- new(…) with its type left out, wherever the place it stands in says the type: a declaration, a member or element of an initializer, an argument, a return, a cast, a throw, a ?: typed by its place.
- T? as System.Nullable<T> in every type position; string? is string; int?? is refused (CS8629). After is and as, a bare ? is read as nullable only where what follows could not begin an expression, as C# reads it.
- A switch with no natural type converts to object as to any other target.

FASTER

- The parser reads with the immediate carrier, building the tree as it reads: against 0.2.0 on the release benchmark, accepted text parses about 40% faster (deeply nested text the most), and DotGram.ExpressionLanguage.dll carries 68% less IL. A text refused late is 38 to 71% slower, with about 4.3 times the bytes; one refused early takes about the time it did. The answers - tree, refusal, message, exception - are unchanged.
- Member initializers nested and never closed are read once at every level, where they were read twice (three quarters of a second at seventeen levels). A string left unclosed inside an interpolated string's hole, $"{x", is refused at once, where the time doubled with every further character.
- Interpolated strings nested in one another's holes allocate the same at every level, where every level held room for a quarter of all the text nested in it: 3,200 levels allocated 76 MB and now allocate 14 MB. The time still grows with the square of the depth.

FIXED

- A dotted name with more parts than any type in reach, generic or not, is refused in time and bytes proportional to its length, where it was quadratic, and worse on names new to the caches: a parameter typed by 800 parts after an unknown root took 59 GB and 143 seconds, a generic one of 1,600 parts 3.2 GB. The first such name in a scope counts how deep the types in reach go, once an assembly; a member chain on a declared name never does. A long member chain on a parameter is read in linear time as well.
- Generic arguments nested n levels deep, closed or not, allocate in proportion to n, where every level copied the text of the levels inside it (2.6 GB at 6,400 levels).
- A chain of conditionals whose branches meet in no type, b ? 1 : b ? 1 : … : b, and nests of switches and new() of that kind are typed in linear time, where every level asked the whole nest below it (1.9 seconds for 12,800 levels).

KNOWN ISSUES

- A lambda is never converted to an expression-tree type (Expression<TDelegate>): over an IQueryable, LINQ operators that take a lambda bind to Enumerable and run in memory, and Queryable's methods written out are refused.
- Interpolated strings nested in one another's holes, $"{$"{$"{x}"}"}", are read in time that grows with the square of the depth: 1,100 levels (about 5 KB of text) take about half a second, 3,200 levels about four seconds. The memory is linear. Bound the size of untrusted input.
- A chain of comparisons written as generics, a < a < a < … > b, is read in time that grows with the square of its length, because every a is tried as the start of a generic type's arguments first: 4,500 operands (about 18 KB) take about half a second, 6,400 about one second. Bound the size of untrusted input.