[antlr-interest] ANTLR crash with C# target and rewrite rules

Chrobot, Stefan Stefan.Chrobot at sabre.com
Wed Mar 31 05:34:48 PDT 2010


Hello!

 

I'm using the C# target of ANTLR and have some problems with it.

I'm rewriting the input to the output, but on my way I need to collect
some information about the input (to create StringTemplates on the fly).
I want the $id.text to return the rewritten text of the rule. And I
suppose this should happen, but the runtime crashes instead.

 

What am I doing wrong?

 

 

The grammar:

 

grammar Test;

 

options {

                language = CSharp2;

                output = template;

                rewrite = true;

}

 

start_rule

                :               id+                          {
System.Console.WriteLine($id.text); } // I need to access the text here

                ;

 

id            :               ID                            -> { new
StringTemplate("id") }

                ;

 

ID  :        ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*

    ;

 

WS  :   ( ' ' | '\t' | '\r' | '\n' ) {$channel=HIDDEN;}

    ;

 

The driver:

 

using System;

using Antlr.Runtime;

 

namespace RewriteTest

{

    public class Program

    {

        public static void Main(string[] args)

        {

            string input = "ab cd ef gh";

            

            var stream = new ANTLRStringStream(input);

            var lexer = new TestLexer(stream);

 

            var tokenStream = new TokenRewriteStream(lexer);

            var parser = new TestParser(tokenStream);

 

            parser.start_rule();

 

 
Console.WriteLine("----------------------------------------------");

 

            Console.WriteLine(tokenStream.ToOriginalString());

            Console.WriteLine(tokenStream.ToString());

        }

    }

}

 

The result:

 

Unhandled Exception: System.InvalidCastException: Unable to cast object
of type 'ReplaceOp' to type 'InsertBeforeOp'.

   at Antlr.Runtime.TokenRewriteStream.ToString(String programName,
Int32 start,  Int32 end)

   at Antlr.Runtime.TokenRewriteStream.ToString(Int32 start, Int32 end)

   at Antlr.Runtime.CommonTokenStream.ToString(IToken start, IToken
stop)

   at TestParser.start_rule() in C:\Tests\RewriteTest\TestParser.cs:line
147

   at RewriteTest.Program.Main(String[] args) in
C:\Tests\RewriteTest\Program.cs:line 18



More information about the antlr-interest mailing list