2

I'm trying to port working antlr to antlr4 but can't find why I get error:

syntax error: 'public' came as a complete surprise to me

on:

public root
    : NEWLINE* global_block EOF -> ^(Root global_block)
    ;

?

btw I also get:

syntax error: '->' came as a complete surprise to me while looking for rule element 
syntax error: '^' came as a complete surprise to me
cnd
  • 32,616
  • 62
  • 183
  • 313

1 Answers1

2

Pragmatic solution

Just delete the public modifier. Rules are public by default.

Reason public is not recognized

I don't know! According to the Antlr4 grammar (https://github.com/antlr/grammars-v4/blob/master/antlr4/ANTLRv4Parser.g4), public should be allowed. However, I am not sure whether this grammar is exactly the one used for Antlr4.

A more severe problem in your spec

AST constructors are no longer supported in Antlr4 so ^(Root global_block) is not possible anymore. You need a tree visitor (or listener) to build a custom tree:

Run antlr with the -visitor option to generate a visitor class. This class is a generic class which has a visit method for each rule, e.g.,

public class PropertyFileBaseVisitor<T> extends AbstractParseTreeVisitor<T>
implements PropertyFileVisitor<T>
{
    @Override public T visitFile(PropertyFileParser.FileContext ctx) { ... }
    @Override public T visitProp(PropertyFileParser.PropContext ctx) { ... }

}

It returns any T, so you can simply write a visitor that builds a tree of your desired type and returns it. For a more in depth discussion of using visitors see If/else statements in ANTLR using listeners

Community
  • 1
  • 1
gexicide
  • 38,535
  • 21
  • 92
  • 152
  • I also get `syntax error: '->' came as a complete surprise to me while looking for rule element` :S – cnd May 30 '14 at 09:30
  • I see ... May you provide tiny example of how can I resolve it with tree visitor – cnd May 30 '14 at 09:33
  • 1
    @Heather, a visitor-example can be found here: http://stackoverflow.com/questions/15610183/if-else-statements-in-antlr-using-listeners – Bart Kiers May 30 '14 at 09:43