SlideShare a Scribd company logo
1 of 10
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The Token set as an Enum type. This is just "binds" each
token to its list of
* valid lexemes.
*
*
*/
public enum TOKEN {
ARTICLE("a", "the"), // a list of articles
NOUN("dog", "cat", "rat"), // a list of nouns
VERB("loves", "hates", "eats"), // a list of verbs
UNKNOWN(); // keep our lexemes "type-safe"!
//
// The lexemes under this token
private List<String> lexemeList;
// Construct the token with the list of lexems
private TOKEN(String... tokenStrings) {
lexemeList = new ArrayList<>(tokenStrings.length);
lexemeList.addAll(Arrays.asList(tokenStrings));
}
// Gets a token from a lexeme
public static TOKEN fromLexeme(String str) {
// Search through the lexemes looking for a match.
for (TOKEN t : TOKEN.values()) {
if (t.lexemeList.contains(str)) {
return t;
}
}
// If nothing matches then return UNKNOWN.
return UNKNOWN;
}
}
/**
* Programming Languages: Implementation and Design.
*
* A Simple Compiler Adapted from Sebesta (2010) by Josh
Dehlinger further modified by Adam Conover
* (2012-2015)
*
* A simple compiler used for the simple English grammar in
Section 2.2 of Adam Brooks Weber's
* "Modern Programming Languages" book. Parts of this code
was adapted from Robert Sebesta's
* "Concepts of Programming Languages".
*
* This compiler assumes that the source file containing the
sentences to parse is provided as the
* first runtime argument. Within the source file, the compiler
assumes that each sentence to parse
* is provided on its own line.
*
* NOTE: A "real" compiler would more likely treat an entire
file as a single stream of input,
* rather than each line being an independent input stream.
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Compiler {
/**
* It is assumed that the first argument provided is the name
of the source file that is to be
* "compiled".
*/
public static void main(String[] args) throws IOException {
//args = new String[]{"<some hard coded path for
testing>"};
//args = new
String[]{"D:Version_Controlled_SVN_NewtonCOS420J
avaParserSampleinput.txt"};
if (args.length < 1) {
System.out.println("Need a filename!");
} else {
// Java 7 "try-with-resource" to create the file input
buffer.
try (BufferedReader br = new BufferedReader(new
FileReader(args[0]))) {
// Create the new lexer.
LexicalAnalyzer lexer = new LexicalAnalyzer();
// Start lexing and parsing.
processFile(lexer, br);
}
}
}
/**
* Reads each line of the input file and invokes the lexer and
parser for each.
*/
static void processFile(LexicalAnalyzer lexer,
BufferedReader br) throws IOException {
String sourceLine;
// Read each line in the source file to be compiled as a
unique sentence
// to check against the grammar.
while ((sourceLine = br.readLine()) != null) {
// Ignore empty lines and comments.
if (sourceLine.trim().length() <= 0) {
continue;
}
if (sourceLine.trim().startsWith("#")) {
System.out.println("Comment: " +
sourceLine.substring(1).trim());
continue;
}
// Create a new syntax analyzer over the provided lexer.
SyntaxAnalyzer parser = new SyntaxAnalyzer(lexer);
// Parse the given sentence against the given grammar.
We assume that the
// sentence, <S>, production is the start state.
try {
// Start the lexer...
lexer.start(sourceLine);
// Start the parser...
parser.analyze();
// No exceptions, so we must be good!
System.out.printf("The sentence '%s' follows the
BNF grammar.%n", sourceLine);
} catch (ParseException error) {
// If a syntax error was found, print that the sentence
does not follow the grammar.
System.out.printf("SYNTAX ERROR while
processing: '%s'%n", sourceLine);
System.out.printf("ERROR MSG: %s%n",
error.getErrMsg());
}
System.out.println("------------------------------------------
-----------------");
}
}
}
Assume we start with a simple "sentence" grammar as follows:
<S> ::= <NP><V><NP>
<NP> ::= <A> <N>
<V> ::= loves | hates | eats
<A> ::= a | the
<N> ::= dog | cat | rat
Part A:
Show the BNF above with the following additional grammar
elements:
· Adjectives: (0 or more Adjectives separated by commas may
precede any Noun. A comma may or may not be preceded by a
space.)
· furry
· fast
· slow
· delicious
· Adverbs: (0 or 1 Adverb may precede any Verb)
· quickly
· secretly
· Conjunctions: (0 or more may appear in any sentence
· and
· or
· Sentence terminator (The terminator may or may not be
preceded by a space.)
· . (a single period)
· ! (a single period)
·
Part B:
Show/Draw the syntax diagrams for each of the grammar
elements above. Hyperlink reference not valid.
Part C:
Show the parse trees (which can be generated in ANTLRWorks)
for each of the following sentences:
Examples of SYNTACTICALLY VALID Input Strings:
a dog loves the cat.
the cat eats the slow rat and the slow , furry dog secretly hates
the cat and a dog loves the rat !
Examples of SYNTACTICALLY INVALID Input Strings (where
do they fail):
a dog barks at the cat.
the fast furry cat eats quickly
NOTE: You can generate the full parse trees from
ANTLRWorks (as can be done with the attached sample for the
base grammar) or simply draw out the cooresponding AST's
(Abstract Syntax Trees) "by hand" on paper or with a simple
drawing tool. The point of this is to have something that you
can then verify against the parse trees generated by your own
code (in the next part).
Part D:
Modify the (attached) sample code to accept valid sentences
based upon the newly defined grammar above. The parser
should also "reject" invalid sentences with a descriptive error
message. Note that the program should still accept a filename
from the "Command Line" as illustrated in the example. Please
no HARD-CODED file paths in the source.

More Related Content

Similar to import java.util.ArrayList;import java.util.Arrays;import ja.docx

package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flexvip_du
 
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfaioils
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxbudbarber38650
 
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdfAdrianEBJKingr
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfaonesalem
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.pptleyobi6147
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdfSpam92
 
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdfCopy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdffacevenky
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and ProsperKen Kousen
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfShaiAlmog1
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
 
#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docxAASTHA76
 

Similar to import java.util.ArrayList;import java.util.Arrays;import ja.docx (20)

package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Introduction of flex
Introduction of flexIntroduction of flex
Introduction of flex
 
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdfplease navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
please navigate to cs112 webpage and go to assignments -- Trees. Th.pdf
 
Advance Java
Advance JavaAdvance Java
Advance Java
 
forwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docxforwarder.java.txt java forwarder class waits for an in.docx
forwarder.java.txt java forwarder class waits for an in.docx
 
package
packagepackage
package
 
Shell programming
Shell programmingShell programming
Shell programming
 
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf--------------- FloatArrays-java -    ckage csi213-lab05-import java-u.pdf
--------------- FloatArrays-java - ckage csi213-lab05-import java-u.pdf
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
module 4_ Lex_new.ppt
module 4_ Lex_new.pptmodule 4_ Lex_new.ppt
module 4_ Lex_new.ppt
 
golang_refcard.pdf
golang_refcard.pdfgolang_refcard.pdf
golang_refcard.pdf
 
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdfCopy your completed LinkedList class from Lab 3 into the LinkedList..pdf
Copy your completed LinkedList class from Lab 3 into the LinkedList..pdf
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
create-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdfcreate-netflix-clone-02-server.pdf
create-netflix-clone-02-server.pdf
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx#include string.h#include stdlib.h#include systypes.h.docx
#include string.h#include stdlib.h#include systypes.h.docx
 

More from wilcockiris

Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docx
Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docxBarbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docx
Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docxwilcockiris
 
BARGAIN CITY Your career is moving along faster than you e.docx
BARGAIN CITY Your career is moving along faster than you e.docxBARGAIN CITY Your career is moving along faster than you e.docx
BARGAIN CITY Your career is moving along faster than you e.docxwilcockiris
 
Barbara schedules a meeting with a core group of clinic  managers. T.docx
Barbara schedules a meeting with a core group of clinic  managers. T.docxBarbara schedules a meeting with a core group of clinic  managers. T.docx
Barbara schedules a meeting with a core group of clinic  managers. T.docxwilcockiris
 
Barbara schedules a meeting with a core group of clinic managers.docx
Barbara schedules a meeting with a core group of clinic managers.docxBarbara schedules a meeting with a core group of clinic managers.docx
Barbara schedules a meeting with a core group of clinic managers.docxwilcockiris
 
Barbara schedules a meeting with a core group of clinic managers. Th.docx
Barbara schedules a meeting with a core group of clinic managers. Th.docxBarbara schedules a meeting with a core group of clinic managers. Th.docx
Barbara schedules a meeting with a core group of clinic managers. Th.docxwilcockiris
 
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docx
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docxBarbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docx
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docxwilcockiris
 
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docx
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docxBARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docx
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docxwilcockiris
 
Banks 5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docx
Banks    5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docxBanks    5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docx
Banks 5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docxwilcockiris
 
Banking industry•Databases that storeocorporate sensiti.docx
Banking industry•Databases that storeocorporate sensiti.docxBanking industry•Databases that storeocorporate sensiti.docx
Banking industry•Databases that storeocorporate sensiti.docxwilcockiris
 
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docx
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docxBAOL 531 Managerial AccountingWeek Three Article Research Pape.docx
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docxwilcockiris
 
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docx
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docxbankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docx
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docxwilcockiris
 
Barbara and Judi entered into a contract with Linda, which provi.docx
Barbara and Judi entered into a contract with Linda, which provi.docxBarbara and Judi entered into a contract with Linda, which provi.docx
Barbara and Judi entered into a contract with Linda, which provi.docxwilcockiris
 
bappsum.indd 614 182014 30258 PMHuman Reso.docx
bappsum.indd   614 182014   30258 PMHuman Reso.docxbappsum.indd   614 182014   30258 PMHuman Reso.docx
bappsum.indd 614 182014 30258 PMHuman Reso.docxwilcockiris
 
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docx
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docxBank ReservesSuppose that the reserve ratio is .25, and that a b.docx
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docxwilcockiris
 
Bank Services, Grading GuideFIN366 Version 21Individual.docx
Bank Services, Grading GuideFIN366 Version 21Individual.docxBank Services, Grading GuideFIN366 Version 21Individual.docx
Bank Services, Grading GuideFIN366 Version 21Individual.docxwilcockiris
 
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docx
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docxBaldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docx
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docxwilcockiris
 
Bank confirmations are critical to the cash audit. What information .docx
Bank confirmations are critical to the cash audit. What information .docxBank confirmations are critical to the cash audit. What information .docx
Bank confirmations are critical to the cash audit. What information .docxwilcockiris
 
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docx
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docxBalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docx
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docxwilcockiris
 
BAM 515 - Organizational Behavior(Enter your answers on th.docx
BAM 515 - Organizational Behavior(Enter your answers on th.docxBAM 515 - Organizational Behavior(Enter your answers on th.docx
BAM 515 - Organizational Behavior(Enter your answers on th.docxwilcockiris
 
BalanchineGeorge Balanchine is an important figure in the histor.docx
BalanchineGeorge Balanchine is an important figure in the histor.docxBalanchineGeorge Balanchine is an important figure in the histor.docx
BalanchineGeorge Balanchine is an important figure in the histor.docxwilcockiris
 

More from wilcockiris (20)

Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docx
Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docxBarbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docx
Barbara Silva is the CIO for Peachtree Community Hospital in Atlanta.docx
 
BARGAIN CITY Your career is moving along faster than you e.docx
BARGAIN CITY Your career is moving along faster than you e.docxBARGAIN CITY Your career is moving along faster than you e.docx
BARGAIN CITY Your career is moving along faster than you e.docx
 
Barbara schedules a meeting with a core group of clinic  managers. T.docx
Barbara schedules a meeting with a core group of clinic  managers. T.docxBarbara schedules a meeting with a core group of clinic  managers. T.docx
Barbara schedules a meeting with a core group of clinic  managers. T.docx
 
Barbara schedules a meeting with a core group of clinic managers.docx
Barbara schedules a meeting with a core group of clinic managers.docxBarbara schedules a meeting with a core group of clinic managers.docx
Barbara schedules a meeting with a core group of clinic managers.docx
 
Barbara schedules a meeting with a core group of clinic managers. Th.docx
Barbara schedules a meeting with a core group of clinic managers. Th.docxBarbara schedules a meeting with a core group of clinic managers. Th.docx
Barbara schedules a meeting with a core group of clinic managers. Th.docx
 
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docx
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docxBarbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docx
Barbara Rosenwein, A Short History of the Middle Ages 4th edition (U.docx
 
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docx
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docxBARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docx
BARBARA NGAM, MPAShoreline, WA 98155 ▪ 801.317.5999 ▪ [email pro.docx
 
Banks 5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docx
Banks    5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docxBanks    5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docx
Banks 5Maya BanksProfessor Debra MartinEN106DLGU1A2018.docx
 
Banking industry•Databases that storeocorporate sensiti.docx
Banking industry•Databases that storeocorporate sensiti.docxBanking industry•Databases that storeocorporate sensiti.docx
Banking industry•Databases that storeocorporate sensiti.docx
 
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docx
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docxBAOL 531 Managerial AccountingWeek Three Article Research Pape.docx
BAOL 531 Managerial AccountingWeek Three Article Research Pape.docx
 
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docx
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docxbankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docx
bankCustomer1223333SmithJamesbbbbbb12345 Abrams Rd Dallas TX 75043.docx
 
Barbara and Judi entered into a contract with Linda, which provi.docx
Barbara and Judi entered into a contract with Linda, which provi.docxBarbara and Judi entered into a contract with Linda, which provi.docx
Barbara and Judi entered into a contract with Linda, which provi.docx
 
bappsum.indd 614 182014 30258 PMHuman Reso.docx
bappsum.indd   614 182014   30258 PMHuman Reso.docxbappsum.indd   614 182014   30258 PMHuman Reso.docx
bappsum.indd 614 182014 30258 PMHuman Reso.docx
 
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docx
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docxBank ReservesSuppose that the reserve ratio is .25, and that a b.docx
Bank ReservesSuppose that the reserve ratio is .25, and that a b.docx
 
Bank Services, Grading GuideFIN366 Version 21Individual.docx
Bank Services, Grading GuideFIN366 Version 21Individual.docxBank Services, Grading GuideFIN366 Version 21Individual.docx
Bank Services, Grading GuideFIN366 Version 21Individual.docx
 
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docx
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docxBaldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docx
Baldwins Kentucky Revised Statutes AnnotatedTitle XXXV. Domesti.docx
 
Bank confirmations are critical to the cash audit. What information .docx
Bank confirmations are critical to the cash audit. What information .docxBank confirmations are critical to the cash audit. What information .docx
Bank confirmations are critical to the cash audit. What information .docx
 
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docx
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docxBalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docx
BalShtBalance SheetBalance SheetBalance SheetBalance SheetThe Fran.docx
 
BAM 515 - Organizational Behavior(Enter your answers on th.docx
BAM 515 - Organizational Behavior(Enter your answers on th.docxBAM 515 - Organizational Behavior(Enter your answers on th.docx
BAM 515 - Organizational Behavior(Enter your answers on th.docx
 
BalanchineGeorge Balanchine is an important figure in the histor.docx
BalanchineGeorge Balanchine is an important figure in the histor.docxBalanchineGeorge Balanchine is an important figure in the histor.docx
BalanchineGeorge Balanchine is an important figure in the histor.docx
 

Recently uploaded

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

import java.util.ArrayList;import java.util.Arrays;import ja.docx

  • 1. import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The Token set as an Enum type. This is just "binds" each token to its list of * valid lexemes. * * */ public enum TOKEN { ARTICLE("a", "the"), // a list of articles NOUN("dog", "cat", "rat"), // a list of nouns VERB("loves", "hates", "eats"), // a list of verbs UNKNOWN(); // keep our lexemes "type-safe"! //
  • 2. // The lexemes under this token private List<String> lexemeList; // Construct the token with the list of lexems private TOKEN(String... tokenStrings) { lexemeList = new ArrayList<>(tokenStrings.length); lexemeList.addAll(Arrays.asList(tokenStrings)); } // Gets a token from a lexeme public static TOKEN fromLexeme(String str) { // Search through the lexemes looking for a match. for (TOKEN t : TOKEN.values()) { if (t.lexemeList.contains(str)) { return t; } }
  • 3. // If nothing matches then return UNKNOWN. return UNKNOWN; } } /** * Programming Languages: Implementation and Design. * * A Simple Compiler Adapted from Sebesta (2010) by Josh Dehlinger further modified by Adam Conover * (2012-2015) * * A simple compiler used for the simple English grammar in Section 2.2 of Adam Brooks Weber's * "Modern Programming Languages" book. Parts of this code was adapted from Robert Sebesta's * "Concepts of Programming Languages". * * This compiler assumes that the source file containing the sentences to parse is provided as the
  • 4. * first runtime argument. Within the source file, the compiler assumes that each sentence to parse * is provided on its own line. * * NOTE: A "real" compiler would more likely treat an entire file as a single stream of input, * rather than each line being an independent input stream. */ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Compiler { /** * It is assumed that the first argument provided is the name of the source file that is to be * "compiled". */
  • 5. public static void main(String[] args) throws IOException { //args = new String[]{"<some hard coded path for testing>"}; //args = new String[]{"D:Version_Controlled_SVN_NewtonCOS420J avaParserSampleinput.txt"}; if (args.length < 1) { System.out.println("Need a filename!"); } else { // Java 7 "try-with-resource" to create the file input buffer. try (BufferedReader br = new BufferedReader(new FileReader(args[0]))) { // Create the new lexer. LexicalAnalyzer lexer = new LexicalAnalyzer(); // Start lexing and parsing. processFile(lexer, br); } }
  • 6. } /** * Reads each line of the input file and invokes the lexer and parser for each. */ static void processFile(LexicalAnalyzer lexer, BufferedReader br) throws IOException { String sourceLine; // Read each line in the source file to be compiled as a unique sentence // to check against the grammar. while ((sourceLine = br.readLine()) != null) { // Ignore empty lines and comments. if (sourceLine.trim().length() <= 0) { continue; } if (sourceLine.trim().startsWith("#")) {
  • 7. System.out.println("Comment: " + sourceLine.substring(1).trim()); continue; } // Create a new syntax analyzer over the provided lexer. SyntaxAnalyzer parser = new SyntaxAnalyzer(lexer); // Parse the given sentence against the given grammar. We assume that the // sentence, <S>, production is the start state. try { // Start the lexer... lexer.start(sourceLine); // Start the parser... parser.analyze(); // No exceptions, so we must be good!
  • 8. System.out.printf("The sentence '%s' follows the BNF grammar.%n", sourceLine); } catch (ParseException error) { // If a syntax error was found, print that the sentence does not follow the grammar. System.out.printf("SYNTAX ERROR while processing: '%s'%n", sourceLine); System.out.printf("ERROR MSG: %s%n", error.getErrMsg()); } System.out.println("------------------------------------------ -----------------"); } } } Assume we start with a simple "sentence" grammar as follows: <S> ::= <NP><V><NP> <NP> ::= <A> <N> <V> ::= loves | hates | eats <A> ::= a | the <N> ::= dog | cat | rat
  • 9. Part A: Show the BNF above with the following additional grammar elements: · Adjectives: (0 or more Adjectives separated by commas may precede any Noun. A comma may or may not be preceded by a space.) · furry · fast · slow · delicious · Adverbs: (0 or 1 Adverb may precede any Verb) · quickly · secretly · Conjunctions: (0 or more may appear in any sentence · and · or · Sentence terminator (The terminator may or may not be preceded by a space.) · . (a single period) · ! (a single period) · Part B: Show/Draw the syntax diagrams for each of the grammar elements above. Hyperlink reference not valid. Part C: Show the parse trees (which can be generated in ANTLRWorks) for each of the following sentences: Examples of SYNTACTICALLY VALID Input Strings: a dog loves the cat. the cat eats the slow rat and the slow , furry dog secretly hates the cat and a dog loves the rat ! Examples of SYNTACTICALLY INVALID Input Strings (where do they fail): a dog barks at the cat. the fast furry cat eats quickly
  • 10. NOTE: You can generate the full parse trees from ANTLRWorks (as can be done with the attached sample for the base grammar) or simply draw out the cooresponding AST's (Abstract Syntax Trees) "by hand" on paper or with a simple drawing tool. The point of this is to have something that you can then verify against the parse trees generated by your own code (in the next part). Part D: Modify the (attached) sample code to accept valid sentences based upon the newly defined grammar above. The parser should also "reject" invalid sentences with a descriptive error message. Note that the program should still accept a filename from the "Command Line" as illustrated in the example. Please no HARD-CODED file paths in the source.