Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @header in ANTLR

I'm having trouble getting the "@header" or any other @ rule to work in ANTLR. With a very basic grammer, like this:

grammar test;

options {
     language = CSharp2;
}

@header {
    using System.Collections.Generic;
}

tokens {
  TEST;
}

something : TEST*;

TEST : '0' .. '9'; 

This seems to adhere to the ANTLR documentation and various other examples online, but when I try to generate the output through either ANTLRWorks v1.4 or the ANTLR jar v3.2, I get the following error:

Cannot generate the grammar because:

error(100): [path]\test.g:11:1 syntax error: antlr: [path]\test.g:11:1 unexpected token: tokens {

Which I cannot seem to shake. I am able to generate the lexer and parser successfully without the @header included in the grammar. I have the latest version of Java on Windows:

java version "1.6.0_22" Java(TM) SE Runtime Environment (build 1.6.0_22-b04) Java HotSpot(TM) Client VM (build 17.1-b03, mixed mode, sharing)

I assume this is something stone simple and I'm just blind to it, so please bring on the obvious answers.

like image 471
Moxen Avatar asked Nov 01 '10 01:11

Moxen


People also ask

Does ANTLR use Ebnf?

A language is specified using a context-free grammar expressed using Extended Backus–Naur Form (EBNF). ANTLR can generate lexers, parsers, tree parsers, and combined lexer-parsers. Parsers can automatically generate parse trees or abstract syntax trees, which can be further processed with tree parsers.

Can ANTLR generate AST?

This package allows you to use ANTLR grammars and use the parser output to generate an abstract syntax tree (AST).

Can ANTLR parse C++?

ANTLR can generate parsers in many languages: Java, C#, Python (2 and 3), JavaScript, Go, Swift, Dart, PHP and C++.

What is ANTLR jar used for?

ANTLR (ANother Tool for Language Recognition) is a tool for processing structured text. It does this by giving us access to language processing primitives like lexers, grammars, and parsers as well as the runtime to process text against them. It's often used to build tools and frameworks.


1 Answers

The error is because those blocks are required to appear in a certain order.

  1. options
  2. tokens
  3. @header
  4. @members

then your rules

like image 171
Brad Mace Avatar answered Nov 15 '22 21:11

Brad Mace