I am new to antlr and java so this may be a trivial question (hopefully!). I am using antlr 3.4. I have a grammar for the lexer:
lexer grammar MyLexer;
options {
language = Java;
}
COMMENT:
( '//' ~('\n'|'\r')* '\r'? '\n'
| '/*' .* '*/'
) {$channel=HIDDEN;};
WS: (' '
| '\t'
| '\r'
| '\n'
) {$channel=HIDDEN;};
COLLECTION: 'collection';
BRACE_OPEN: '{';
BRACE_CLOSE: '}';
and another for the parser:
parser grammar myParser;
options {
language = Java;
tokenVocab = myLexer;
}
collection_def
scope {
MyCollection currentCollection;
}
@init {
$collection_def::currentCollection = new MyCollection();
}
@after {
// There should be a comment preceding this rule. How to get the content of that comment into the commentContent variable?
$collection_def::currentCollection.setDescription(commentContent);
...
}
: COLLECTION BRACE_OPEN
...
BRACE_CLOSE;
The lexer sends comments to the hidden channel. But I want the parser to extract the text contained in the comment that precedes a specific rule (or a specific token, since the COLLECTION token only appears in the rule above). For example, I want this input:
/* Text describing the collection */
collection {
item 1;
item 2;
}
to be parsed to a MyCollection object with its description member variable set to "Text describing the collection".
How can I do this?