0

I am attempting to mimic the grammar G shown below using ANTLR v4.9.3

enter image description here

My attempt to do so is shown below …

grammar G ;
s : t s | ;
t : 'aaa' t 'bbb' |  ;

I invoke the ANTLR Tool as follows …

org.antlr.v4.Tool G.g4

The tool's response is …

The following sets of rules are mutually left-recursive [s]

My question is …

How does one create an ANTLR grammar for grammar G ?


In order to eliminate the errors, grammar G has been updated to …

grammar G ;
s : t* EOF ;
t : 'aaa' 'bbb' | 'aaa' t 'bbb' ;

I am also trying to programatically distinguish between strings that are in L(G), and strings that are not in L(G) (where L(G) is the language generated by grammar G). In the following code, the first string is in L(G), but the second string is not in L(G).

    String [] stringArray = { "aaaaaabbbbbbaaabbbaaaaaabbbbbb",
                              "aaabbbaaaaaabbbbbbaaabbbb" } ;
    for ( int i = 0 ; i < stringArray.length ; i ++ )
      {
      CharStream charStream = CharStreams.fromString ( stringArray[i] ) ;
      GLexer lexer = new GLexer( charStream ) ;
      CommonTokenStream tokens = new CommonTokenStream( lexer ) ;
      GParser parser = new GParser( tokens ) ;
      ParseTree tree = parser.s() ;
      } // end for i loop

I'd like the code to print messages such as …

The string "aaaaaabbbbbbaaabbbaaaaaabbbbbb" is in L(G).

… and …

The string "aaabbbaaaaaabbbbbbaaabbbb" is not in L(G).

How does one programmatically distinguish between strings that parse successfully (and are in L(G)), and strings that fail to parse successfully (and are not in L(G)) ?


user3134725
  • 1,003
  • 6
  • 12
  • Try replacing `s:t s|;` with `s:t* EOF;` – kaby76 Mar 26 '22 at 15:09
  • Replacing `s:t s|;` by `s:t* EOF;` results in `error(153): SimpleGrammar.g4:2:0: rule s contains a closure with at least one alternative that can match an empty string`. – user3134725 Mar 26 '22 at 15:40
  • You have to replace `t : 'aaa' t 'bbb' | ;` as well; try `t: 'aaa' 'bbb' | 'aaa' t 'bbb';`. – kaby76 Mar 26 '22 at 15:49
  • The second part of this question is now solved. See this [StackOverflow Post](https://stackoverflow.com/questions/22415208/get-rid-of-token-recognition-error). A `RuntimeException` is thrown, and can be caught, when parsing fails. – user3134725 Mar 26 '22 at 19:20

0 Answers0