A Use Case With JavaCC [Snippet]
Here's a simple JavaCC use case — check it out!
Join the DZone community and get the full member experience.
Join For FreeLet's say you have the following file:
fsdfsdfsdf
sfsfasdfsdf dfdsfsdfs f
sfsfasdfsdf
Barcelona, Total SCORE 8 (4+4).
having 100% success rate.
sfsdfsdfdf sfasdfum 34749n afsf
Barcelona, Total SCORE 2 (6-4).
having 100% success rate.
Our job is to extract the percentage. Here is the corresponding grammar file:
options
{
LOOKAHEAD = 1;
}
PARSER_BEGIN(ScoreGrammer)
package com.test.grammer;
public class ScoreGrammer
{
public static void main(String args[]) throws Exception
{
ScoreGrammer parser;
try
{
parser = new ScoreGrammer(ScoreGrammer.class.getResource("some file.txt").openStream());
}
catch (java.io.FileNotFoundException e)
{
return;
}
Model model = new Model();
try
{
parser.Parse(model);
}
catch(EOFException e) {
}
catch (ParseException e)
{
System.out.println("Encountered errors during parse." + e);
}
System.out.println("definitions parsed successfully." );
System.out.println(model);
}
}
PARSER_END(ScoreGrammer)
SKIP :
{
" "
| "\t"
| "\n"
| "\r"
| ","
}
TOKEN [IGNORE_CASE]:
{
< BARCELONA: "BARCELONA" >
}
TOKEN:
{
<ALPHA: (["A" - "Z", "a" - "z"])+ >
| <#DIGIT: (["0" - "9"])+> // Defines local pattern (private regular expression)
| <LPARAN: "(">
| <RPARAN: ")">
| <PLUS: "+">
| <MINUS: "-">
| <PERCENT: "%">
| <DOT: ".">
| <ANY: (~["A" - "Z", "a" - "z", ",", "0" - "9", "(", ")", "+", ",", "%", "\t", "\n", "\r", " "])+ >
}
JAVACODE
void jumpToBarcelona() {
Token tok;
while (true) {
tok = getToken(1);
if (tok.kind == BARCELONA) {
break;
}
if (tok.kind == EOF) {
throw new EOFException();
}
tok = getNextToken();
}
}
/** Top level production. */
void Parse(Model model) :
{
Token t;
Variations v = null;
}
{
(
jumpToBarcelona()
t = < BARCELONA >
{
v = new Variations();
v.setBeginLine(t.beginLine);
}
(
(< ALPHA >)+
(
[ < DIGIT > ]
< LPARAN >
< DIGIT >
(
< PLUS >
| < MINUS >
)
< DIGIT >
t = < RPARAN >
{
v.setEndColumn(t.endColumn);
}
< DOT >
(
(
< ALPHA >
t = < DIGIT >
{
v.percent(t.image);
model.addVarition(v);
}
< PERCENT >
)
)
)?
)
)*
}
Hope you found this simple example useful!
Further Reading
Parser Generators: ANTLR Vs. JavaCC
Extracting Javadoc Documentation From Source Files Using JavaParser
Use case
Published at DZone with permission of Mohammad Nadeem, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Hyperion Essbase Technical Functionality
-
Batch Request Processing With API Gateway
-
Execution Type Models in Node.js
-
Measuring Service Performance: The Whys and Hows
Comments