DotGram 0.3.0
dotnet add package DotGram --version 0.3.0
NuGet\Install-Package DotGram -Version 0.3.0
<PackageReference Include="DotGram" Version="0.3.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
<PackageVersion Include="DotGram" Version="0.3.0" />
<PackageReference Include="DotGram"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets> </PackageReference>
paket add DotGram --version 0.3.0
#r "nuget: DotGram, 0.3.0"
#:package DotGram@0.3.0
#addin nuget:?package=DotGram&version=0.3.0
#tool nuget:?package=DotGram&version=0.3.0
.Gram
.Gram is a source generator that compiles grammars into strongly typed C# parsers, from single-character rules and hand-written feeds to the SQL standard.
The grammar is known at compile time. The generated parser is ordinary C# in your own assembly — there is no parser engine, grammar graph, or runtime library to interpret, and nothing to deploy beside your application.
A grammar is read in one of two modes. Character-level parsing has no separate tokenizer: rules match characters directly, and bytes are the same mode over bytes. Lexical parsing (Lexical = true) cuts the grammar in two: a lexer makes tokens and the syntax above it reads them. The input is chosen at the call site, and the generator offers an overload only where it provably works.
| Input | Types | Character-level | Lexical |
|---|---|---|---|
| Text in memory | string (whole or a slice by start and length) |
regex-like matching and search, configs, expressions, formats, queries | SQL and languages with keywords and trivia |
| Text stream | TextReader |
feed and log files, sockets — read through a bounded buffer, so a file of tens of gigabytes takes no more memory than one record | — memory only |
| Bytes | byte[], ReadOnlyMemory<byte>, Stream |
binary protocols, FIX wire, byte feeds of any size | — memory only |
| Segments | IEnumerable<string>, IReadOnlyList<string>, TextReader (as lines) |
feed files line by line, CSV, argv; a reader over a file or socket is read a line at a time, each line end a segment boundary | — |
Getting started
<PackageReference Include="DotGram" Version="0.3.0"
PrivateAssets="all" ExcludeAssets="runtime" />
The generator runs in the C# compiler of .NET SDK 9.0.300 or newer (Roslyn 4.14; Visual Studio 17.14).
The project may still target net8.0 or older, but an SDK 8 build skips the generator with warning
CS9057 and generates no parser, so the code that calls it does not compile.
A grammar lives in the [Gram] attribute of the class the parser is generated into, or in
a .gram file listed as <AdditionalFiles Include="Name.gram" />. An inline grammar is a
raw string literal, so it needs C# 11; a .gram file needs C# 8, which netstandard2.0 and
net472 do not default to (Compatibility, below).
Generation summary in Build Output
Enable a per-parser build message in the consuming project:
<PropertyGroup>
<DotGramReportGeneration>summary</DotGramReportGeneration>
</PropertyGroup>
Or run dotnet build -p:DotGramReportGeneration=summary. The NuGet package imports
its MSBuild target automatically; direct analyzer references need to import
build/DotGram.targets from the source project.
The property takes three values. none is the default and says nothing at all.
summary prints one line per parser, at an importance a minimal build shows: the host
(and named variant), the normalized rule count, the generated C# size in UTF-8 bytes,
and the generation time — or cached, where the compiler server had compiled the same input
in an earlier build and the parser was taken from there (DotGramNoCache=true turns that off; see
the notation).
full prints, beside each of those, the actual lexical/character mode, the requested
strategy options and the carrier of every machine in the grammar — at an importance -v:normal and above show, so a quiet build stays
quiet whichever is set. true and false are the older spellings of full and none.
Rule counts include normalized specializations and library rules. Individual publications may fall back from the requested options; their existing diagnostics remain authoritative.
Time measures grammar compilation and emission, excluding C# compilation, host discovery and symbol queries. A cached generator result retains its original timing. A build that skips compilation prints no summary. Design-time builds do not report.
Anything above none enables compiler-generated files on disk and adds a comment-only
report file; full also costs the analysis that decides the carriers, which is worked
out for the report and for nothing else. Keep the default for reproducible artifacts.
No value changes parser behavior or turns messages into warnings.
Large grammars and build time
A project either references the DotGram package and generates in its build, or has its parsers
generated by DotGram.Cli and committed — never both: the build would generate the same types again
(CS0102/CS0111 on every member).
A grammar of hundreds of rules takes seconds to generate, and a cold build or a CI run pays that every time. Keep a large grammar in a project of its own first, so that only the projects that change it pay. When that is not enough, the same generator can run outside the build:
dotnet new tool-manifest
dotnet tool install DotGram.Cli
dotnet dotgram generate src/Grammars/Grammars.csproj -o src/Grammars/Generated
The project then compiles the files in Generated/ like any other C# and drops its DotGram reference.
A single grammar needs no project: dotnet dotgram generate calc.gram -o out --namespace Demo --option Lexical=true
writes the host class from the options, the [Gram] properties being --option Name=value.
In a cold build of DotGram.Sql, generating its three grammars is a large part of the compiler's time; with the files committed, the build compiles them and skips the generation.
What it promises. generate writes the files DotGram would generate in dotnet build of the project
(configuration Release unless --configuration says otherwise), byte for byte, in the encoding the compiler
writes them (UTF-8 with a byte order mark), with the tool's DotGram, for a restored project, built with the
same SDK, whose own targets do not change the compiler's inputs outside the IDE's design-time pass. A
difference on a project inside that condition, which every ordinary SDK-style project is, is a defect in
the tool: report it. Two differences are by design: #line paths are relative to the output folder
(--line-paths absolute gives the build's text), and the generation report files
(DotGramReportGeneration) are not written. The EmbeddedAttribute definition is the compiler's text and
may differ in line endings from your SDK's. The diagnostics of DotGram itself are shown at the severities the
build gives them, and an error among them stops the run.
What it does not do. It does not compile your project and does not tell you whether it builds: errors in
grammar actions, in the generated parser or anywhere else in the project show when your build compiles the
files. It reports the errors in your own sources that it sees, at the compiler's default severities, and does
not check the project as a whole. It runs what an IDE runs when it opens the project — MSBuild's Compile
target with the compiler skipped, as a design-time build — so a custom target that does not skip
design-time builds runs too, and one that follows the compiler finds no new assembly. It does not restore:
after changing package references, run dotnet restore first. When this is not good enough, build with
EmitCompilerGeneratedFiles=true and copy the generated files.
It reads a project with .NET SDK 8.0.100 or newer, and generates only where that SDK's compiler
can run DotGram (SDK 9.0.300 or newer for this version); a .gram input needs no SDK compiler.
Keeping it current. Nothing in the build notices that a grammar changed: run the command again after
editing a grammar, or a type it builds. Keep the arguments in a response file (dotnet dotgram generate @grammars.rsp) so that every run uses the same ones, and check in CI that the committed files are current:
run the command, then fail if git status --porcelain -- src/Grammars/Generated prints anything. A
src/Grammars/Generated/** -text line in the repository's .gitattributes keeps the files as the generator
writes them: the folder's path from the root, since a bare Generated/** matches only a folder beside the
.gitattributes (the tool prints the line for its folder). It prints
the GRAM diagnostics; the editor does not show them for a project that no longer references the package, so
write the grammar with the package and move to the tool when it is done.
dotnet dotgram --help lists every option and exit code, and dotnet dotgram --skill prints the guide for
coding agents. The reference is docs/cli.md.
One grammar, three parsers
A grammar does not have to describe only one parser. The arithmetic below is written once
and published three times: over int, over decimal, and as a tree.
using System;
using DotGram;
[Gram("""
@using System.Globalization;
trivia = { Std.Spacing? }
Value : @int = d: Std.Digits => @(int.Parse(d))
Point = { Std.Digits ~ ('.' ~ Std.Digits)? }
Expr : Value = left: Expr & '+' & right: Expr << 1 => @(left + right)
| left: Expr & '-' & right: Expr << 1 => @(left - right)
| left: Expr & '*' & right: Expr << 2 => @(left * right)
| left: Expr & '/' & right: Expr << 2 => @(left / right)
| left: Expr & '^' & right: Expr >> 3 => @(Raise(left, right))
| '-' & operand: Expr >> 3 => @(-operand)
| '(' & inner: Expr & ')' => @(inner)
| value: Value => @(value)
IntNumber : @int = d: Std.Digits => @(int.Parse(d))
DecimalNumber : @decimal = d: Point => @(decimal.Parse(d, CultureInfo.InvariantCulture))
NodeNumber : @Node = d: Point => @(new Node.Number(decimal.Parse(d, CultureInfo.InvariantCulture)))
parse Expr with (Value = IntNumber) as EvaluateInt
parse Expr with (Value = DecimalNumber) as EvaluateDecimal
parse Expr with (Value = NodeNumber) as BuildTree
""")]
public static partial class Calculator
{
/// <summary>The tree the third parser builds, and the operators that build it.</summary>
public abstract record Node
{
public sealed record Number(decimal Of) : Node;
public sealed record Binary(char Op, Node Left, Node Right) : Node;
public sealed record Negate(Node Of) : Node;
public static Node operator +(Node left, Node right) => new Binary('+', left, right);
public static Node operator -(Node left, Node right) => new Binary('-', left, right);
public static Node operator *(Node left, Node right) => new Binary('*', left, right);
public static Node operator /(Node left, Node right) => new Binary('/', left, right);
public static Node operator -(Node of) => new Negate(of);
}
static int Raise(int left, int right) => (int)Math.Pow(left, right);
static decimal Raise(decimal left, decimal right) => (decimal)Math.Pow((double)left, (double)right);
static Node Raise(Node left, Node right) => new Node.Binary('^', left, right);
}
Three parsers come out of it:
int half = Calculator.EvaluateInt("7 / 2"); // 3
decimal exact = Calculator.EvaluateDecimal("7 / 2"); // 3.5
int tower = Calculator.EvaluateInt("2 ^ 3 ^ 2"); // 512, since `^` groups to the right
int negated = Calculator.EvaluateInt("-2 ^ 2"); // -4, since a prefix is where an expression starts
var refused = Calculator.TryEvaluateInt("1.5"); // no match: `Value` is `IntNumber` there
var tree = Calculator.BuildTree("1 - 2 - 3");
// case Binary(-, Binary(-, Number(1), Number(2)), Number(3)) :
The whole language is one rule. << n reads the operand on its right one strength
tighter, so the operator groups to the left; >> n reads it at n, so it groups to the
right. What separates the three parsers is the publication:
parse Expr with (Value = IntNumber) as EvaluateInt
parse Expr with (Value = DecimalNumber) as EvaluateDecimal
parse Expr with (Value = NodeNumber) as BuildTree
with substitutes a rule through the grammar reachable from that publication, and the
result type follows it: Expr : Value means "the type produced by Value". The actions
do not change either — left + right is C#, and over Node it is the operator declared
beside the grammar, which builds a node instead of adding anything.
Named captures become the result
using DotGram;
[Gram("""
Feed = header: Header & rows: Row* & trailer: Trailer & eof
Header = "H" & '|' & date: Date & eol
Row = "R" & '|' & symbol: Text & '|' & quantity: Digit+ & eol
Trailer = "T" & '|' & count: Digit+ & eol
Date = year: Digit{4} & '-' & month: Digit{2} & '-' & day: Digit{2}
Text = [^ '|' | '\r' | '\n']+
Digit = ['0'..'9']
parse Feed
find Row as AllRows
""")]
public static partial class FeedParser;
The parser returns that structure directly:
var text = """
H|2026-09-20
R|ABC|100
T|1
""";
var feed = FeedParser.ParseFeed(text);
var year = feed.Header.Date.Year; // 2026
var symbol = feed.Rows[0].Symbol; // ABC
var count = feed.Trailer.Count; // 1
foreach (var row in FeedParser.AllRows(text))
Console.WriteLine(row.Value.Symbol);
There is no generic parse tree and no visitor required to turn it into application data.
Captures can also be matched straight to a constructor or to the required properties of
a type you already have, in which case the grammar contains no construction code at all.
C# where a grammar cannot go
@ is the boundary. A rule declares its result as a C# type and builds it with an action;
a guard asks a C# question in the middle of a parse:
using DotGram;
[Gram("""
Name = ['a'..'z' | 'A'..'Z']+
Tag
= '<' & open: Name & '>'
& "</" & close: Name & '>'
& when @(open == close)
parse Tag
""")]
public static partial class Tags;
The same boundary calls predicates, external recognizers and constructors.
Versions of one language
A language changes between releases. SQL Server took the *= outer join out after 2000 and
put IS DISTINCT FROM in with 2022. A grammar says that once, and each version is a parser
generated from it:
using DotGram;
[Gram("""
trivia = { ' '* }
wordboundary = ['a'..'z']
Version = "2000" | "2008" | "2022"
Name = { ['a'..'z']+ }
Test : @string
= l: Name & "*=" & r: Name & when Version is "2000"
=> @($"{l} left-joined to {r}")
| l: Name & "is" & "distinct" & "from" & r: Name & when Version is "2022"
=> @($"{l} differs from {r}")
| l: Name & "=" & r: Name
=> @($"{l} equals {r}")
parse Test with (Version = "2000") as ParseOld
parse Test with (Version = "2022") as ParseNew
parse Test as ParseAny
""")]
public static partial class SqlDialect;
var joined = SqlDialect.ParseOld("a *= b"); // a left-joined to b
var refused = SqlDialect.TryParseNew("a *= b"); // IsSuccess is false
var differs = SqlDialect.ParseAny("a is distinct from b"); // a differs from b
when Version is "2000" is decided when the parser is generated, not while it runs:
with (Version = "2000") substitutes the rule for that one publication, and an alternative
whose condition is false is not in that parser at all. ParseAny names no version, so it
keeps every one and reads them all.
What .Gram supports
- literals, element sets, ranges and Unicode categories;
- sequence, ordered choice,
?,*,+and bounded repetition; - lookahead and atomic groups;
- named captures and generated result types;
- back-references —
$q: Xbinds the textXmatched,$qmatches it again, andX{#q}repeats by its length — for raw strings, heredocs, Lua long brackets and the like, over a string, a span, aTextReaderor a stream, and in an atomic terminal the lexer begins; - existing C# result types, filled by constructor or by
requiredproperties; - semantic actions, guards, external C# predicates and recognizers;
- parameterized rules, rule rebinding and parser specialization;
- conditions about the grammar —
when Version is "2022"— decided when a parser is generated, which is how one grammar is several versions of a language; - left recursion — direct, and indirect through rules that only forward — with binding powers for expression grammars;
- grammar namespaces, and grammar libraries that cross a project reference;
- a lexical split: the same notation read over tokens instead of characters;
Parse,TryParse— a match, orboolwith the value in anout— andFind; describing a refusal can cost reading the refused input a second time, which theoutform never does;- streaming from a
TextReader, and recovery inside repetitions.
No runtime parser library
Everything a generated parser needs is emitted into the consuming assembly as internal C#. There is no runtime assembly to deploy, and no generator/runtime version pair that can drift apart.
Why an input was refused
A trace build of a grammar — <DotGramTrace>true</DotGramTrace> for every grammar of a project,
or Trace = true on one [Gram] or [GramParserVariant] — reports what its parser reads to a sink, and
carries three ready-made ones in the generated class:
<PropertyGroup>
<DotGramTrace Condition="'$(Configuration)' == 'Debug'">true</DotGramTrace>
</PropertyGroup>
using System;
using DotGram;
[Gram("""
Value : @int = '(' & inner: Value & ')' => @(inner) | digits: ['0'..'9']+ => @(int.Parse(digits))
parse Value
""")]
public static partial class Nested;
var why = new Nested.GramWhy();
using (Nested.Tracing(why))
Nested.TryParseValue("((1");
Console.WriteLine(why);
// Expected ')'. (line 1, column 4)
// The rules below were reading there, each wanting what it names.
// wanted ')' in Value 1:1 > Value 1:2
GramWhy prints the match's own message and, under it, the rules that were open where the input
was followed furthest, each with what it wanted there. GramTraceLog writes every rule entered and
left to a TextWriter, and GramProfile counts and times each rule. The parser answers what it
answers untraced, and without the option nothing of this is generated. A subclass of GramTrace
receives the same events; see
the notation.
Threads
A generated parser's static methods may be called from any number of threads at once, and a parse reached from inside another's action or guard is safe the same way. What one call needs while it runs is kept per thread and handed back when the call returns; a nested call takes a spare of its own rather than contending with the call that reached it. What is shared between threads is only what the grammar never changes once generated. A thread whose one large parse needed an oversized buffer is not charged for it forever: the buffer is let go once a few calls in a row stop needing it that size.
None of this reaches your own C#. A =>, a when, a recovery hook or an external
recognizer that keeps state of its own — a static field, a cache — is your code, and
making it safe under concurrency is your job there the same as anywhere else you write
it: see §7.7
on why a when should not simply write one.
A parse from memory deep enough to run low on stack does not fail: it is carried onto a
fresh thread with room of its own and continues there, deeper still if that is not
enough, while the thread that made the call waits (the attribute's MaxExtraStacks bounds how
many). This is a hand-off, not concurrency, but an action, guard or external recognizer
reached past that point is not running on the thread the call came in on: code that
depends on which thread it runs on cannot assume it stays the one that started the parse.
A reader over a TextReader or a Stream does not do this, and keeps none of the pool
above either: each call leases its buffer from .NET's shared array pool and gives it back
when the call ends.
Compatibility
The generated parser is C# 8 and targets whatever the project around it targets.
netstandard2.0, net472 and net8.0 all compile it.
- A grammar written inside
[Gram]is a raw string literal, which is C# 11. Onnetstandard2.0andnet472the default is C# 7.3, so<LangVersion>has to be set. A grammar in a.gramfile still needs C# 8: below it the build reports GRAM0010 and generates no parser. netstandard2.0andnet472needSystem.Memory, for theReadOnlySpan<char>the generated methods take.- A
recordonnetstandard2.0ornet472needsSystem.Runtime.CompilerServices.IsExternalInit, a type those frameworks lack (CS0518). Declare it once in the project:namespace System.Runtime.CompilerServices { internal static class IsExternalInit { } }.
The generator is a Roslyn analyzer built against Microsoft.CodeAnalysis 4.14 and needs a
compiler at least that new.
Documentation
Everything else is at github.com/dotgram/dotgram: the notation in full, the diagnostics, whole parsers to copy, and the benchmarks.
DotGram.Web is a
package of its own — RFC 3986 URIs, RFC 5646 language tags, RFC 6570 URI templates,
RFC 9651 structured field values and the rest of the formats of the web —
DotGram.Sql another —
Microsoft's T-SQL, SQL-92 and ISO SQL:2023, three grammars that build one tree of
records —
DotGram.ExpressionLanguage
a third — a C#-style expression language that builds System.Linq.Expressions trees — and
DotGram.Finance a
fourth: FIX 4.2, 4.4 and 5.0 SP2 tag-value messages. Two of them
hold the largest grammars there are to read —
T-SQL in over 1,000
rules, and the
expression language in
over 80. Each of the four ships its own README.md and SKILL.md, which say what its
parsers publish and what is easy to get wrong.
MIT. The code the generator writes into
your compilation may be used under terms of your choice, without carrying the notice: the grant is
in licenses/LICENSE-GENERATED-CODE,
and the same file is in this package.
Learn more about Target Frameworks and .NET Standard.
-
.NETStandard 2.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Since 0.2.0. The documentation, with a guide to the language and one to the generator, is at https://dotgram.github.io/dotgram/; docs/syntax.md is the language, docs/diagnostics.md every message by its identifier; docs/status.md says what this version does and does not do yet.
BREAKING CHANGES, and what to do about each. Regenerate the parser to take any of them.
- Renamed attributes and options; the old names are gone from source, with no obsolete aliases. Rename them where you wrote them:
[GramOptions(Suffix = "X", ...)] -> [GramParserVariant("X", ...)] (the name is the required argument)
[Gram(..., Suffix = "X")] -> [Gram(..., Name = "X")]
[Gram] IncludedAs -> DefaultAlias
[GramInclude] As -> Alias
BufferedInput -> BufferedText
SpanCaptures -> UseSpanCaptures
BufferSize -> InitialBufferSize
MaxRetained -> MaxBufferedInputLength
Stacks -> MaxExtraStacks
PartSize -> TargetMethodPartSize
PerCall -> UsePerCallLocations
Portable -> ExportGrammar
GramCarrier.Tape -> GramCarrier.Deferred
A project still written with an old name gets GRAM0012 (error) at it, saying what it is called now.
[Gram] and [GramParserVariant] now derive from an abstract GramReadingAttribute that holds the options they share. UsePerCallLocations is on [GramParserVariant] only, and Source, DefaultAlias and the settable Name on [Gram] only: an option that meant nothing on one of them can no longer be written there. ExportGrammar not set means what Portable unset meant: the grammar is exported where the class and every class around it are public. A grammar is still included from an assembly built by 0.2, whose attributes carry the old names; that goes in 0.4.
- LocationType: a located value is now told through the interface, ((ILocated)made).Locate(…) as a constrained call, so an explicit implementation works and a struct is told in place. A class named as LocationType goes on working. GRAM0011 (error) refuses a LocationType that is neither an interface nor a class declaring Locate(int at, int length), or the three-argument form with UsePerCallLocations, where a build used to fail with CS1061 in generated code.
- [GramSource], [GramLanguageDescriptor], [GramToolingGuard] and [GramToolingExternal] are hidden from IntelliSense (EditorBrowsable(Never)); the tooling two are experimental and may change in any release.
- The default carrier. GramCarrier.Auto now compiles every grammar it can with the immediate carrier, where it used to only where no construction could run for an abandoned reading. Constructions (=>) then run as their alternative is read, also for alternatives the parse abandons: a factory with side effects, or one that throws, behaves differently, and an exception thrown there escapes the Try methods; in a grammar with a context, what is accepted and what is built can differ. Accepted parses are faster (15 to 54% on the expression language against 0.2.0) and the code smaller; refused input is slower and allocates more. New warning GRAM5016 names a grammar where the deferred carrier (GramCarrier.Deferred) is the safer choice. To keep the old behaviour, set Carrier = GramCarrier.Deferred; naming either carrier silences both. GRAM5015 is no longer reported; GRAM5007 warns only where Carrier = Immediate was named.
- Ignore-case literals ('x'i, "text"i) mean one thing everywhere: a character matches itself and its simple upper and lower case as Unicode 16.0 gives them, and a case partner on the other side of ASCII is not taken. 's'i no longer accepts U+017F, 'μ'i no longer accepts U+00B5, 'σ'i no longer accepts ς. To accept such a character, write it as an alternative of its own.
- \p{…} reads Unicode 16.0's general categories on every runtime, from a table the generator carries. On .NET Framework and .NET 8 and 9 a character assigned or recategorised since their tables is read as 16.0 says; on .NET 10 nothing changes.
- New warnings, which break a build with warnings as errors until the grammar is changed: GRAM4043, a rule spelled from single characters where trivia is not empty (Std.Digit+ & ('.' & Std.Digit+)? reads "1 . 5") - join its parts with ~, declare it where trivia = none, or name trivia where a space is meant; GRAM4051, trivia not written in braces beside a class that reads the same characters - write trivia = { … }; GRAM4042, a binding power that cannot reach its operand; GRAM4052, a repetition that can read one run of text in two ways ((X+)*, ('a' | 'a' & 'a')+) - put braces around the repetition or what it repeats, or rewrite it (docs/diagnostics.md).
- New warning GRAM4059, which also breaks a build with warnings as errors: a grammar that publishes nothing (no parse, find or yield of any visibility) and that no [Gram] class in the compilation includes or is derived from - most often a forgotten parse. A library grammar written for other assemblies to include must now say so: write [Gram(..., ExportGrammar = true)] on it, even on a public class. A [GramParserVariant] is never warned.
- New build warnings GRAM6001-GRAM6005, about what a [GramClassify] names, which also break a build with warnings as errors: before, only the Visual Studio extension showed them. Fix the target, or suppress the identifier.
- New errors for grammars 0.2.0 compiled and then read wrongly: GRAM3011, GRAM4040 and GRAM4041 (with expressions and calls into a namespace with a rebinding header, docs/syntax.md section 5.1); GRAM4036, a with inside an instance of a parameterized rule made only under another rebinding; GRAM4038, a recover inside a lookahead; GRAM4044 and GRAM4045, a recover the reading could not carry; GRAM4046, a located rule whose value is a Nullable of a struct; GRAM4039, a capture in a step of a left-recursive rule with no =>; GRAM2005, a binding power above 9999; GRAM3022, two imports at one scope that both declare trivia. Each message says what to write instead.
- A range with nothing after its .. is refused, GRAM2014: ['a'..] was read as ['a']. Write the upper bound, or ['a'] for one character.
- Type arguments after a rule, a parameter or a capture are refused, GRAM2016: B<int> was read as B. Only a C# name, written with @, is generic.
- The names the generated parser gives parameters of its own (parserSource, parserStarts, parserLengths, parserReading, parserLocating, parserWhole) are reserved beside the supplied ones: a capture, or a rule's parameter of any kind, with one of them or with a supplied name is refused, GRAM4012, where it was accepted; C# in a grammar that names one of the parser's own is GRAM4053. Rename it.
- A rule typed by a rule the grammar generates a type for, B : A where A captures, gives back A's generated type, where it gave back the text it matched as a string: B : A = x: 'b' => x is now GRAM4056, the string not being an A. Hand back an A (=> A(…), the operand that produces one, or captures filling it by name), or type the rule : string.
- A repetition that recovers without a => under a trivia that reads something (Let* recover ';' beside trivia = { ' '* }) hands OnRecovered the name of its element's rule, "Let", where it handed "an element". Without trivia it was "Let" already. Code that compares the rule argument follows the new name.
- GRAM4033 is split by what it says. GRAM4033 is now only a binding's text read where a value goes (in C# after => or when, in when … is …, in a call's argument); a binding inside a lookahead is GRAM4060, one name bound twice on one route GRAM4061, a reference or a length inside its own binding GRAM4062, a binding and its reference on two sides of a constructing group GRAM4063, a binding in a left-recursion step or around its leading call GRAM4064. A suppression of GRAM4033 written for one of these follows its new number.
- A name two imports supply (using A; using B; both declaring W) is GRAM3023 where it is read unqualified, naming both; the first using was read without a word. Write the one meant in full, A.W. A rule the scope declares itself still wins over its imports.
- A qualified name looks only its first part up outward; each namespace after it must be declared inside the one before. A.B.X where A declares no B reached a B declared beside A; it is now unknown (on a rebinding's left side, GRAM3006). Write the path that declares it.
- A name a namespace's header binds (namespace N with (X = Y)) and its block declares again is GRAM3010 wherever X came from; where X was declared in an enclosing namespace it was GRAM3012. A suppression of GRAM3012 written for this case follows GRAM3010.
- A switch's parse errors have identifiers of their own, where all were GRAM2003: GRAM2020, something in its braces that is not a case, a default or a body, or a label that is not a whole number or a string; GRAM2021, a label or default written twice; GRAM2022, numbers and strings mixed; GRAM2023, no label, or a label with no body. A case-insensitive character in an element set is GRAM2015. A suppression of GRAM2003 written for one of them follows the new number.
- Rebindings stack: where several reach one call, the one written closer to where the reading starts applies on top of the others ((X with (D = Y)) with (Y = P) reads P, as X with (D = Y, Y = P)); a caller's with or namespace header applies on top of the header of a namespace it calls into.
- GRAM0010: a project that compiles C# below 8 (the default for netstandard2.0 and .NET Framework) and has a [Gram] is told once to set <LangVersion>8.0</LangVersion> or later, and no parser is generated. The attributes file every referencing project gets is now C# 7.3.
- Names. GRAM5018 refuses a name that would be written twice into the generated class (a publication called Match or Failure, parse Q as TryParseT beside parse T). GRAM1012 refuses a name in a grammar that contains _DotGram. The class's own helper types and pool members now carry _DotGram in their names (Lines_DotGram, Parser_DotGram, …), and a rule named like a member the class writes takes Value after its name. Code that named a generated helper type by its old name follows the new one. Helper members with _DotGram in their name are never public.
- Binding powers (<< and >>): after an operand read at strength k, the operator loop takes only operators weaker than k. A grouping the strengths exclude, which a when in an operator step used to accept (1+2*3 as (1+2)*3), is refused. A grammar read over tokens with no when in an operator step is generated as before.
- Text captures and lookaheads. A text capture of a repetition that may take no turn ('a'{0,2}) is "" where it took none, not null; only ? is an option. A captured lookahead at a rule that builds a value (n: ?=Number with Number : @int) holds that value, as section 3.4 says, not the text it saw.
- Refusal positions. A literal of two or more characters the input ends inside is refused as NoMatch at the first character that does not fit it, and as Starved at the end of the input only where every character there agrees: T = "/*" & ';' refuses "/x" as NoMatch at 1 and "/" as Starved at 1, where both were Starved at 0. A refusal's message now names that place.
- Reader forms. A parse read from a TextReader or a sequence of lines now reads what the same parse reads over a string, and a rule a reader cannot read the same way gets no reader overload, with GRAM5001 saying why: a value collected inside a part that is not a rule call, a part that holds a repetition marked recover, a recovery that synchronizes on a recognizer of the host, a choice of literals that can end in two places (("a" | "ab") & "b"), a bounded repetition that can begin what follows it (A? & A+). To keep a reader overload, give the part a rule of its own.
- Trivia is looked up in the namespace chain first, then in its imports, nearest scope first, wherever the using stands. A using at the top of a namespace block used to bring in no trivia.
- The engine's step trace for generator work is compiled where the build defines DOTGRAM_STEPS; DOTGRAM_TRACE now means nothing.
- The names a trace build declares (GramTrace, GramRead, GramWhy, GramTraceLog, GramProfile, Tracing) are reserved in every build, so that a project that traces its Debug build alone compiles one grammar to the same names in both. A publication called one of them is GRAM5018, and a rule whose type would take one is given the name with Value after it. Rename the publication with as; code that named such a rule's type follows the new name.
- GramRead.Forwards(rule), which no sink read, is no longer generated.
- The constructor of a rule's generated result type (a rule with captures and no : @T) is internal: swapping two captures of one type silently swapped what a caller in another assembly passed. Code beside the grammar still builds it; a value to be built elsewhere is a type of the host's own, named with : @T.
- A rule's generated type is named alike in every reading of a host ([GramParserVariant("...")]): a rule Url in a host Url builds Url.UrlValue in every reading; Url.Traced.Url is now Url.Traced.UrlValue. A publication named after a reading's class (parse Body as Traced beside a reading Traced) is GRAM5018, and a rule of that name builds a type with Value after it. Code that named such a type in a second reading follows the new name.
- SourceSpan is internal unless a public signature the generator writes names it (a public publication whose value is a span, a property of a rule's generated type). It is now a readonly partial struct: a host whose own public API hands one out declares public partial struct SourceSpan { } in the host class, and the generated part takes that accessibility.
- Scan, the scanner of a grammar read over tokens, is internal: the kind it gave is the grammar's own numbering of its tokens, which changes with the grammar. A host that wants token boundaries writes a method of its own, under another name, that calls Scan.
- The forms read from a position, TryParseX(input, at), TryParseX(input, at, length) and their bool forms with ref int at, are written only for a parse whose directive says positional (positional parse X). They used to come and go with what the optimizer chose. Write positional before parse (after the access) where the forms are called. positional on a find or with yield is GRAM2012, the words before the verb out of order or repeated GRAM2013, positional in a grammar that names eos GRAM4055 (docs/syntax.md sections 6 and 6.3).
- A host with several readings ([GramParserVariant("...")]) has SourceSpan, Match<T>, Outcome and ParserInput<T> written once, in a file of its own (Host.gram-shared.g.cs), each only where a reading needs it. A host with one reading keeps these types in that reading's class: [Gram(..., Name = "Fast")] alone answers with Host.Fast.Match<T>, and a second reading moves it to Host.Match<T>.
- Std.Integer, Std.Long, Std.Decimal and Std.Double: a number too wide for its type is now a refusal instead of an exception (Std.Integer on 2147483648 threw OverflowException; TryParseX now returns false, ParseX throws the FormatException every refusal throws); likewise a Double that overflows (1e309). Such a number is refused whole, never read shorter: 1e999 is not 1 before an e999. A grammar that caught OverflowException should check the refusal instead; one that wants its own message declares the rule.
- The runs of the standard library are atomic: Std.Digits, Std.HexDigits, Std.Blank, Std.Spacing, Std.Identifier and the text of Std.LineComment never hand a character back. A grammar that relied on one giving characters back (Std.Digits & '5' reading 15) now refuses it; write the repetition in the grammar for that.
NEW
- The left side of a rebinding may be qualified: X with (Std.Digit = HexDigit), namespace N with (A.B = C). It means the rule the name resolves to, as the unqualified name does where it is in view; it was GRAM2001, "Expected '='". docs/syntax.md section 5.1.
- Every diagnostic has a title of its own, the "What it says" of docs/diagnostics.md, and a help link to its row of that file at this version's tag.
- Bindings and back-references: $q: X binds the text X matched, $q matches that text again, X{#q} repeats X by its length - for constructs closed by the text that opened them (Lua long brackets, raw strings, heredocs, Markdown fences). Read over characters, through a reader and a stream; refused over tokens (GRAM4035). docs/syntax.md section 3.5.1; GRAM1011, GRAM2010, GRAM3021, GRAM4032-GRAM4035.
- A trace build: Trace = true on [Gram] or [GramParserVariant], or the build property DotGramTrace, compiles a parser that reports what it reads to a sink set with Tracing(sink). Three sinks come with it: GramWhy, GramTraceLog and GramProfile. Every position it tells is a long, counted from the beginning of the input, as Match.Position is. docs/syntax.md section 6.9.
- eos, the end of a segment: a grammar that names it reads a sequence of segments (lines), from a sequence or a TextReader, as the segments are asked for wherever a record fits one segment. GRAM4047-GRAM4050 say what such a grammar refuses. The feeds of docs/feeds.md and the README end their records with eos.
- Std.Nested(open, close), a pair that holds others to any depth: Std.Nested("/*", "*/") reads /* a /* b */ c */ whole, by a counter in braced trivia and in tokens. GRAM4037 refuses arguments a counter cannot tell apart.
- ConstructionsMayThrow = true on [Gram] or [GramParserVariant]: on the immediate carrier, what a construction throws on a reading the parse gives up is held and thrown only where the deferred carrier would have thrown it. Off by default; it costs every construction a handler. docs/syntax.md section 7.5.
- UsePerCallLocations = true on a [GramParserVariant] that names a LocationType: the grammar is compiled once, and the nested class it names holds the same published methods with locations on. DotGram.Sql's TransactSqlParser.Located is built this way. docs/syntax.md section 6.8.
- A command-line build keeps the parsers it compiled in the compiler server, so the next build after an edit to C# alone does not compile the grammars again; DotGramNoCache turns it off. docs/syntax.md section 6.8.
- DotGramPositionalFollow, an experimental build property for the forms that begin at a position (docs/syntax.md section 6.8).
- The memo of successes: an ordered choice whose alternatives read a nested instance of their own recursion before either can be refused used to read every level of a nest once per alternative, two to the depth, on accepted input. The generator now finds the shape (GRAM4054, information) and, over tokens on the immediate carrier, remembers where the rules of that recursion succeed, so every level is read once (docs/syntax.md section 4.7).
- New information GRAM5017: a construction of a publication with a reader overload changes the context, and may run a different number of times there than over a string.
- A recover factory is told where reading the bad element stopped and what would have fit there (parserExpected, parserFailureLine, parserFailureColumn, parserFailurePosition), and parserMessage says both.
- LICENSE is plain MIT. The grant for the code the generator writes, which LICENSE carried at its end, is licenses/LICENSE-GENERATED-CODE, in this package, on the same terms.
- DotGram.Cli, a new .NET tool (dotnet tool install DotGram.Cli): dotnet dotgram generate writes the parsers a build would generate, for a project that then compiles them without referencing this package. docs/cli.md.
FASTER
- A run read up to a delimiter, (?!X & any)* & X, searches for where the delimiter may begin rather than trying it at every character.
- A refused input on the immediate carrier no longer builds the standing turns of a loop again on every attempt (a refused list of a thousand members allocated 24 MB, now 96 KB); a refused text over characters under binding powers no longer costs two to the power of its operators; a grammar of several hundred rules read from a buffer no longer takes minutes to generate.
FIXED (each takes effect once the parser is generated again)
- A grammar included from a referenced assembly that carries it ([GramSource]) is read from the assembly, which is the grammar it was compiled from. A .gram file of the same name in the including project used to take its place silently; it is now left alone, and GRAM0017 (information) says so where the two differ.
- Editing a .gram file reads again only the grammars that can read that file.
- Generated code that did not compile: a located rule built from its own captures (CS7036); a publication named input or context (CS0149); a reader form of a recovering rule in a grammar with a context (CS7036); an external recognizer or predicate named text, p, c, value and the like (CS0149); a lambda, pattern or query in a when or => hiding a capture of the same name (CS0103); a recovery in a rule no publication reaches (CS1061, CS0649); a fold with no construction (CS1522); a struct nested in the host shadowing an imported class (CS1503); a recognizer of the host met only in a recovery's synchronization (CS0103); a lexical grammar whose trivia holds an element set beside a Std.Nested pair (CS0103).
- A grammar read over tokens (Lexical = true) whose terminals name context, or hold a when … is … the publications answer differently, did not compile (CS7036), nor one with UsePerCallLocations beside a terminal that binds text: the lexer now hands the context, the reading and the located argument on. A guard of such a terminal sees the context as the publication was handed it, since the tokens are cut before the syntax reads anything, and has to give the same answer throughout the parse; a grammar whose terminals depend on what the syntax has read is one for Lexical = false. New warning GRAM5019 names a guard that names context in a terminal whose value is built by reading its token again; where that reading refuses the token, the parser throws InvalidOperationException naming the terminal, where it used to answer with a null value (docs/syntax.md section 7.1).
- A guard that reads a captured value (when @(n < 100) after n: Num) inside a terminal of a grammar read over tokens did not compile (CS1061); it does now.
- The generator stopped with an exception on: a left-recursive rule that builds nothing on the immediate carrier; a guard or a capture written in a recover's synchronization; wordboundary that can match nothing (now GRAM4001); a recovery's => on a repetition captured whole as text (now GRAM4010); a parameterized rule named without its arguments, Q = P beside P(x) (now GRAM4013 at the name).
- An external recognizer is looked up where the generated call stands, as the compiler binds it, rather than by every method of that name in the compilation (GRAM4015 and code that did not compile). A host recognizer that refuses inside a negative lookahead or an atomic group goes on to the group's next alternative.
- A rule's generated type named by the rule (docs/syntax.md sections 3.7 and 4.1): => Pair(right, left) builds the type generated for Pair, where it was written as a call of a type (CS1955); a rule declared Swapped : Pair takes that type, where it was declared to give back a string (CS0029), and gets its value from its =>, from the one operand that produces a Pair, or by filling it from its captures by name; Pairs : Pair[] collects the Pairs it reads.
- New error GRAM4056: a construction whose value cannot be the declared type, said on the grammar where it was a C# error in the generated file - a capture handed back whole that holds text where an array is declared, a generated type where another is declared, a generated type built with the wrong number of values or from a capture that cannot be its member, or a rule's name built or taken as a type where the grammar generates none for it.
- A rule a `when … is …` rules out in a parser (GRAM4022) is written as a refusal; a build that treats warnings as errors refused it (CS0162 in the generated file).
- A rule's name after `when` with no `is` (when Version) is GRAM2009 (it failed as CS0103); a quantified side of `is` (when Version is ['0'..'9']+) is GRAM2024, not GRAM2002; C# that names a parameter standing for a piece of grammar (Value(tag) = switch @(Kind(tag)) { … }) is GRAM4058 (it failed as CS0103).
- dotnet dotgram generate of a .gram prints the warnings the compiler reports in the generated parser, and still writes it.
- A repetition that recovers with a => under a trivia that reads something (Let* recover ';' => @("?") beside trivia = { ' '* }) was refused as one that collects text (GRAM4010); it is accepted, as without trivia.
- A rule called with, recover, as, stream, bytes, and, or or is, declared on the line after an operand or a directive, was read as that operand's with or recover, the directive's as or stream, or a condition's and, or or is. A word that begins a rule's head (an =, parameters, a type) begins that rule there.
- Parse errors in the words of the mistake: GRAM2017, a second quantifier ('a'*?, 'a'+*; there are no lazy quantifiers); GRAM2014, a range outside brackets ('a'..'z'); GRAM2015, a case-insensitive bound (['a'..'z'i]); GRAM2019, a using after the first declaration.
- A worded keyword is no longer matched inside a longer word over tokens.
- A rule of a namespace with a rebinding header (namespace N with (…)), called from outside it (R = N.E), is read under the header; it used to be read as if the header had not been written, with no diagnostic.
- A repetition whose turn may match nothing only through an external recognizer no longer loops for ever; the turns up to its fewest are counted however far each moved.
- The generator no longer runs for ever on a ring of rules that lead with one another (R0 = R1, R1 = R3 | 'b', R3 = R0 & 'a'): such a grammar is refused for its left recursion (GRAM4002), and a grammar that nothing else refuses is refused with the new error GRAM4057.
- A guarded repetition with a most ((?!';' & any){0,2}) is held to it over a string; a negative look over a run read from a buffer reads as the string does.
- A reader, a sequence of lines or of segments no longer takes the end of the part it holds for the end of the input where a lookahead calls a rule read as one scan, nor in a choice of literals or a recovery's skip at that end; a reader could accept or refuse otherwise than the string, with no error.
- A located rule (LocationType) whose value is a struct is told its location on the value it returns; with UsePerCallLocations a mutable struct no longer loses it.
- Std.Double reads over bytes (stream bytes): its exponent was a case-insensitive literal, which a reading over bytes refuses.
- A @SourceSpan rule with => returns the span it builds, not its extent. A place past int.MaxValue characters into a streamed input throws InvalidOperationException where it would be told, rather than wrapping round.
- A refusal at a place that very many alternatives tied for kept every set they said (gigabytes on forty characters). The list is kept up to 16384 sets; past them the message names the first 16384 and ends "among others", and a trace sink is handed GramTrace.TruncatedTies as the last set.
- A reader that carries the reading onto a thread of its own when its stack runs low probes the stack again when it comes back (ten thousand nested T-SQL CASE ended the process).
- The direct reader and the engine give every form of a parse one outcome, position and value, as docs/syntax.md section 7.5 says. A refused negative lookahead is refused where it stands; a reading from a position is never refused before where it began; input that runs out inside a negative lookahead no longer makes the parse Starved (?!("kk") & 'z' refuses "k" as NoMatch). Three refusals inside trivia still differ (the release's known issues).
- A parser generated into a project that is itself an analyzer or a source generator no longer fails its build with RS1035 (the cultures read and set where a deep reading moves to a stack of its own); the generated lines carry the suppression themselves.
KNOWN ISSUES
- Over characters, a repetition that gives a turn back reads the turns before it again from the start each time, so a refused text costs the square of its length (a refused sum of 2,048 quotients in the calculator: about half a second). Bound the size of untrusted input.
- By default a parse read from a position or a window can refuse, or cut short, the rule's first reading in a few shapes (an optional or a repetition before a negative lookahead, a quoted string with doubled quotes; docs/syntax.md section 6.8). The whole forms are right. The experimental build property DotGramPositionalFollow fixes them at a cost.
- See the known issues of the release on GitHub, and docs/status.md, for the rest.