Skip to content
Olivier Duhart edited this page Aug 21, 2025 · 4 revisions

For this page we will consider the following grammar

root : A B C

where tokens are

  • A : 'a'
  • B : 'b'
  • C : 'c'

This grammar only recognizes the sentence a b c

Error messages try to be as meaningful and readable as possible.

Errors are stored in the Errors list of ParseResult<IN,OUT> return by the Parse() method. An error is an instance of ParseError

var lexer = FluentLexerBuilder<ContextualToken>.NewBuilder()
                .IgnoreEol(true)
                .IgnoreWhiteSpace(true)
                .IgnoreKeywordCase(true)
                .Keyword(ContextualToken.A, "a")
                .Keyword(ContextualToken.B, "b")
                .Keyword(ContextualToken.C, "c");

var build = FluentEBNFParserBuilder<ContextualToken, string>.NewBuilder(new FluentTests(), "root", "en")
    .Production("root : A B C", (objects => "ok"))
    .WithLexerbuilder(lexer)
    .BuildParser();

var parsed = build.Result.Parse("foo bar baz");
if (parsed.IsError) {
    foreach(var error in parsed.Errors) {
        // do something with errors
    }
}

Error messages are internationalized (french english and chinese) There are 2 messages flavors

Basic error messages

For the grammar defined above we can have

  • lexical errors : parsing a , b c will produce message Lexical Error, line 0, column 2 : Unrecognized symbol ',' (44)
  • syntaxic errors : parsing a c b will produce unexpected C ('c (line 0, column 2)'). Expecting B, . `` These messages are available through the ErrorMessage property of `ParseError`
var parsed = build.Result.Parse("foo bar baz");
if (parsed.IsError) {
    foreach(var error in parsed.Errors) {
        // print the basic error message
        Console.WriteLine(error.ErrorMessage)
    }
}

Contextual error messages

Sometimes more context on the error localisation is needed (think of CLI tools). For these case we have the ParseError.ContextualErrorMessage property that display the exact point of the error. For the same parse error as above these messages are :

  • lexical error :
Lexical Error, line 0, column 2 : Unrecognized symbol ',' (44)
  |
0 |a , c b
  |  ^^^ unexpected char ','
  • syntaxic error :
unexpected C ('c (line 0, column 2)'). Expecting B, .
  |
0 |a c b
  |  ^^^ expected B, 
var parsed = build.Result.Parse("foo bar baz");
if (parsed.IsError) {
    foreach(var error in parsed.Errors) {
        // print the basic error message
        Console.WriteLine(error.ContextualErrorMessage)
    }
}

Clone this wiki locally