Accessing rule return values from contexts
Accessing rule return values from contexts
I'm using this example code to better understand ANTLR. From what I understand the row
rule returns a Map<String,String> values
. The rows
label inside the file
rule collects all the RowContext objects. From the for-each loop in the file
rule, is there a way to access the Map<String,String> values
returned by the row
rule?
row
Map<String,String> values
rows
file
file
Map<String,String> values
row
If not, how can I achieve accessing all of the row
rules' Map<String,String> values
from the file
rule?
row
Map<String,String> values
file
Snippet of the code:
/** Derived from rule "file : hdr row+ ;" */
file
locals [int i=0]
: hdr ( rows+=row[$hdr.text.split(",")] {$i++;} )+
{
System.out.println($i+" rows");
for (RowContext r : $rows) {
System.out.println("row token interval: "+r.getSourceInterval());
}
}
;
hdr : row[null] {System.out.println("header: '"+$text.trim()+"'");} ;
/** Derived from rule "row : field (',' field)* 'r'? 'n' ;" */
row[String columns] returns [Map<String,String> values]
locals [int col=0]
@init {
$values = new HashMap<String,String>();
}
@after {
if ($values!=null && $values.size()>0) {
System.out.println("values = "+$values);
}
}
1 Answer
1
Have a look in the generated CSVParser.java
. You can find your inline code in this generated file. If you want to access the values, just access the field values
of RowContext
.
CSVParser.java
values
RowContext
for (RowContext r : $rows) {
System.out.println("row token interval: "+r.getSourceInterval());
System.out.println("values: "+r.values);
}
However I recommend not to use inline code in a parser grammar. ANTLR generates a Visitor
and a Listener
for you. Listener/Visitor-Code is compiled just in time (if you use an appropriate IDE) while generator inline code is not compiled until generation time.
Visitor
Listener
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment