Question
Using JFlex and Byacc/J, write a parser that can determine valid English sentences according to the grammar below. sentence -> nphrase VERB ending | nphrase
Using JFlex and Byacc/J, write a parser that can determine valid English sentences according to the grammar below.
sentence -> nphrase VERB ending
| nphrase VERB vmodifier ending
| nphrase VERB nphrase ending
;
ending -> PUNCT END
;
nphrase -> modifiednoun
| ARTICLE modifiednoun
;
modifiednoun -> NOUN
| nmodifier modifiednoun
;
nmodifier -> ADJECTIVE
| ADVERB nmodifier
;
vmodifier -> ADVERB
| ADVERB vmodifier
| PREPOSITION nphrase
;
The only allowed tokens are ARTICLE VERB NOUN ADJECTIVE ADVERB PREPOSITION END PUNCT
END = newline
PUNCT = period, comma, exclamation, question mark
ARTICLE = the, The, an, An, a, A (both lower, upper case for first character only)
VERB = study, sleep, play, throw, write, eat
NOUN = book, laptop, candy, pen, box
ADJECTIVE = cute, clever, smart, witty, tired, blue, red
ADVERB = willfully, abruptly, endlessly, delightfully, lightly, beautifully
PREPOSITION = before, into, on, above, by, along
JFLEX STARTING CODE:
%% %class Scanner %unicode %line %column %byaccj %{ /* return the current line number.*/ public int getLine() { return yyline; } public int getColumn() { return yycolumn; } %} %% b { return Parser.b; } c { return Parser.c; } . { System.out.println("No match: "+yytext()); }
BYACC STARTING CODE:
%{ import java.io.*; import java.util.*; /* All of the below productions that do not have associated actions are using the DEFAULT action -- $$ = $1 */ %} %token b c %start S %% S: B C { System.out.println("Prod1"); } ; B: b B { System.out.println("Prod2"); } | b { System.out.println("Prod3"); } ; C: c { System.out.println("Prod4"); } ; %% /* Byacc/J expects a member method int yylex(). We need to provide one through this mechanism. See the jflex manual for more information. */ /* reference to the lexer object */ private Scanner lexer; /* interface to the lexer */ private int yylex() { int retVal = -1; try { retVal = lexer.yylex(); } catch (IOException e) { System.err.println("IO Error:" + e); } return retVal; } /* error reporting */ public void yyerror (String error) { System.err.println("Error : " + error + " at line " + lexer.getLine() + " column: " + lexer.getColumn()); } /* constructor taking in File Input */ public Parser (Reader r) { lexer = new Scanner (r); } public static void main (String [] args) throws IOException { Parser yyparser = new Parser(new FileReader(args[0])); yyparser.yyparse(); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started