Awoken
Awoken

Reputation: 79

ANTLR grammar - how to add members overwrite error handling

I see answer How to get ANTLR 3.2 to exit upon first error? which is helpful.

However, I can't seem to add these '@' rules without my grammar freaking out. My grammar file is simple:

 grammar Exp;
 options {
 output=AST;

 }

 program 
  : includes decls (procedure)*  main  -> ^(SMALLCPROGRAM includes decls (procedure)*    main) //AST - PROGRAM root
  ;

   //Lexer and Parser rules continue below as normal..tested thoroughly and works

But if I try to add any of these @ rules, I get errors such as:

grammar file Exp.g has no rules

and:

 Exp.g:0:1: syntax error: assign.types: org.antlr.runtime.EarlyExitException

 org\antlr\grammar\v3\DefineGrammarItemsWalker.g: node from line 202:4 required (...)+ loop did not match anything at input ';'

Anyone have an idea what the problem is? I simply want to change my grammar so that when I run it from my separate main class (passing input into it using ANTLRStringStream etc) it actually throws an error in the main class when there is a syntactic problem rather than just saying something like:

line 1:57 missing RPAREN at '{'       

Before continuing to parse the rest of the input fine. Ultimately, my main class should refuse to parse any syntactically malformed input as defined by my grammar, and should report the errors to the user.

Upvotes: 1

Views: 562

Answers (1)

Bart Kiers
Bart Kiers

Reputation: 170178

You probably have the order of the sections/blocks incorrectly. Be sure it looks like this:

grammar Exp;

options {
  ...
}

tokens {
  ...
}

@parser::header {
  ...
}

@lexer::header {
  ...
}

@parser::members {

  ...
}

@lexer::members {
  ...
}

I'm guessing you placed an @member or @header section before the tokens { ... } block. tokens { ... } should come directly after options { ... }.

I can also remember that certain 3.x version(s) had an issue with an empty sections: be sure there is at least something in all sections, otherwise omit the empty section.

Upvotes: 2

Related Questions