SlideShare a Scribd company logo
1 of 7
Download to read offline
Java Code: The traditional way to deal with these in Parsers is the Expression-Term-Factor
pattern:
Expression: TERM {+|- TERM}
Term: FACTOR {*|/ FACTOR}
Factor: number | ( EXPRESSION )
A couple of notation comments:
| means "or" - either + or -, either * or /
{} means an optional repeat. That's what allows this to parse 1+2+3+4
Think of these as functions. Every CAPTIALIZED word is a function call.
Consider our meme expression above: 6/2*(1+2)
We will start by looking at expression. Expression starts with a TERM. We can't do anything
until we resolve TERM, so let's go there.
A term starts with FACTOR. Again, we can't do anything until we deal with that.
A factor is a number or a (EXPRESSION). Now we can look at our token (hint:
MatchAndRemove). We see a number. OK - our factor is a number. We "return" that.
Remember that we got to factor from term. Let's substitute our number in:
TERM: FACTOR(6) {*|/ FACTOR}
Now we deal with our optional pattern. Is the next character * or /? Yes! Now is the next thing a
factor?
It turns out that it is. Let's substitute that in:
TERM: FACTOR(6) / FACTOR(2)
But remember that our pattern is a REPEATING pattern (hint: loop):
TERM: FACTOR(6) / FACTOR(2) {*|/ FACTOR}
We see the * and call factor. But this time, the factor is not a number but a parenthetical
expression.
Factor: number | ( EXPRESSION )
Factor calls expression.
Expression calls term, term calls factor, factor returns the number 1. Term doesn't see a * or / so
it passes the 1 up. Expression sees the + and calls term. Term calls factor which returns the 2.
Expression doesn't see a +|- value so ends the loop and returns 1+2.
So, remember that we were here:
TERM: FACTOR(6) / FACTOR(2) * FACTOR
Our factor is (1+2). That can't be broken down. That math HAS to be done before can multiply
or divide. That's what enforces order of operations.
In code, this looks like something like this (pseudo-code):
Node Factor()
num = matchAndRemove(NUMBER)
if (num.isPresent) return num
if (matchAndRemove(LPAREN).isPresent)
exp = Expression()
if (exp == null) throw new Exception()
if (matchAndRemove(RPAREN).isEmpty)
throw new Exception()
Node Term()
left = Factor()
do
op = MatchAndRemove(TIMES)
if (op.isEmpty) op=MatchAndRemove(DIVIDE)
if (op.isEmpty) return left
right = Factor()
left = MathOpNode(left, op, right)
while (true)
Node Expression()
left = Term()
do
op = MatchAndRemove(PLUS)
if (op.isEmpty) op=MatchAndRemove(MINUS)
if (op.isEmpty) return left
right = Term()
left = MathOpNode(left, op, right)
while (true)
What is this "MathOpNode"? It's "just" a new node type that holds two other nodes (left and
right) and an operation type: *, /, +, -. Notice that the loops use the result of one operation as the
left side of the next operation. This is called left associative - the left most part is done first.
Right associativity is the opposite - the rightmost part is done first, then we work our way left.
Generally, notice the pattern here - we call a function that is the lowest level of precedence. That
function uses results from a higher level of precedence. The lower level can't do anything until
the higher level is resolved. That "magic" is what enforces order of operation. Start by removing
the call in ParseOperation to ParseBottomLevel().
Going through the rest of the chart is easier. The next level is PostIncrement/Decrement
(example: x++ or y--). The patterns are:
ParseBottomLevel() INC Operation(result of ParseBottomLevel, POSTINC)
ParseBottomLevel() DEC Operation(result of ParseBottomLevel, POSTDEC)
else return ParseBottomLevel().
The right associative methods are a little more complex than the left. Consider:
2^3^4. Left associative would be: (2^3)^4. This is 4096.
2^3^4. Right associative would be 2^(3^4). This is 2^81 which is ... very large.
There are two similar ways to build this - either use a Stack OR use recursion (which uses the
built-in call stack).
The operations marked as "None" are terminal - there is no associativity because they can't recur.
You can't have 3<4<5 or a ~ `hello` ~ `world`
Implement the rest of the chart by creating methods that follow the patterns above. A few hints:
To simplify the assignments, I created an AssigmentNode (Node target, Node expression). But
how do we handle something like: a+=5
I split this into two parts - AssignmentNode and OperationNode. I would create this as:
AssignmentNode (a, OperationNode(a + 5) )
We can now test with full expressions. Let's leave ParseOperation public so that we can write
unit tests against it.
Below is Parser.java and attached is the rubric. Use the Parser.java given below to add in all the
needed methods as shown in the rubric. Don't copy the code given. Don't give an explanation. I
need the code for the methods to be added in Parser.java. Make sure to follow the rubric
carefully and include all the methods that looks for patterns in the tokenHandler's list.
Parser.java
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import javax.swing.ActionMap;
public class Parser {
private TokenHandler tokenHandler;
private LinkedList tokens;
public Parser(LinkedList tokens) {
this.tokenHandler = new TokenHandler(tokens);
this.tokens = tokens;
}
public boolean AcceptSeparators() {
boolean foundSeparator = false;
while (tokenHandler.MoreTokens()) {
Optional currentToken = tokenHandler.getCurrentToken();
if (currentToken.isPresent() && (currentToken.get().getType() ==
Token.TokenType.NEWLINE || currentToken.get().getType() ==
Token.TokenType.SEMICOLON)) {
tokenHandler.consumeMatchedToken();
foundSeparator = true;
} else {
break;
}
}
return foundSeparator;
}
public ProgramNode Parse() throws ParseException {
ProgramNode programNode = new ProgramNode(null, 0);
while (tokenHandler.MoreTokens()) {
if (!ParseFunction(programNode) && !parseAction(programNode)) {
throw new ParseException("Unexpected token: " +
tokenHandler.getCurrentToken().getStart());
}
}
return programNode;
}
private boolean ParseFunction(ProgramNode programNode) {
Optional functionNameToken = tokenHandler.getCurrentToken();
if (tokenHandler.MatchAndRemove(Token.TokenType.IDENTIFIER) != null) {
FunctionDefinitionNode functionNode = new
FunctionDefinitionNode(functionNameToken.map(Token::getType).orElse(null).getStart());
programNode.addNode(functionNode);
if (tokenHandler.MatchAndRemove(Token.TokenType.LPAREN) != null) {
if (tokenHandler.MatchAndRemove(Token.TokenType.RPAREN) != null) {
AcceptSeparators();
return true;
}
}
}
return false;
}
private boolean parseAction(ProgramNode programNode) {
Optional functionNameToken = tokenHandler.getCurrentToken();
if (tokenHandler.MatchAndRemove(Token.TokenType.IDENTIFIER) != null) {
ActionMap actionMap = new ActionMap();
programNode.addNode(actionMap);
AcceptSeparators();
return true;
}
return false;
}
public VariableReferenceNode ParseLValueVariable(String variableName) {
return new VariableReferenceNode(variableName, Optional.empty());
}
public VariableReferenceNode ParseLValueArray(String variableName, int index) {
return new VariableReferenceNode(variableName, Optional.of(index));
}
public OperationNode ParseLValueDollar() {
return new OperationNode("$");
}
public ConstantNode ParseBottomLevelConstantsAndPatterns() {
ConstantNodePatternNode node = new ConstantOrNodePatternNode();
node.setConstant("example");
node.setPattern("PATTERN_1");
return node;
}
public OperationNode ParseBottomLevelParenthesis() throws ParseException {
if (tokenHandler.MatchAndRemove(Token.TokenType.LPAREN) != null) {
OperationNode operationNode = ParseExpression();
if (tokenHandler.MatchAndRemove(Token.TokenType.RPAREN) != null) {
return operationNode;
} else {
throw new ParseException("Expected ')'", tokenHandler.getCurrentToken().getStart());
}
return null;
} else {
throw new ParseException("Expected '('", tokenHandler.getCurrentToken().getStart());
}
}
private OperationNode ParseExpression() {
return null;
}
}
begin{tabular}{|c|c|c|c|c|} hline Cade Style & Fewcomments,badnames(0) &
Somegoodnamingsomenecessarycomments(3) & Mastlygaodnaming,mostnecessarycomments(6)
& Goodnaming,non-
trivialmethodswellcommented,staticonlywhennecessary,privatemembers(10)  hline Unit Tests
& Dantexist(0) & At least one (3) & Missingtests6 & All functionality tested (10)  hline
PastIncrement/Decrement & Daesntexist(0) & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(S)  hline
Exponents & Daesntexist(0) & Attempted(5) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult{10  hline Factor
& Daesntexist(0) & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline Term &
Daesntexist0 & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline
Expression & Daesntexist(0) & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline
Concatenation & Daesntexist(0) & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline
BaoleanCompare & Daesntexist0 & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline Match
& Daesntexist(0) & Attempted(3) & &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline
Arraymembership & Daesntexist(0) & Attempted(3) & & Acceptstokensappropriatelyand 
hline end{tabular} begin{tabular}{|c|c|c|c|} hline & & &
generatesOperationNodeorreturnspartialresult(5)  hline AND & Daesntexist(0) &
Attempted(3) & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)
 hline Or & Doesntexist(0) & Attempted(3) &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5)  hline Ternary
& Daesntexist(0) & Attempted(5) &
AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult{10}  hline
Assignment & Daesntexist0 & Attempted(5) &
AcceptstokensappropriatelyandgeneratesAssignmentNodeorreturnspartialresult{10}  hline
end{tabular}

More Related Content

Similar to Java Code The traditional way to deal with these in Parsers is the .pdf

Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.pptjaba kumar
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1Taisuke Oe
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdfpaijitk
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...Philip Schwarz
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameAntony Stubbs
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... FunctionsMichal Bigos
 
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdfC++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdfrahulfancycorner21
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 

Similar to Java Code The traditional way to deal with these in Parsers is the .pdf (20)

Java 8 by example!
Java 8 by example!Java 8 by example!
Java 8 by example!
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1How to start functional programming (in Scala): Day1
How to start functional programming (in Scala): Day1
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...The Functional Programming Triad of Folding, Scanning and Iteration - a first...
The Functional Programming Triad of Folding, Scanning and Iteration - a first...
 
Array Cont
Array ContArray Cont
Array Cont
 
03. Week 03.pptx
03. Week 03.pptx03. Week 03.pptx
03. Week 03.pptx
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
 
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdfC++ code, please help! Troubleshooting and cannot for the life of me.pdf
C++ code, please help! Troubleshooting and cannot for the life of me.pdf
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Scala oo (1)
Scala oo (1)Scala oo (1)
Scala oo (1)
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Computer programming 2 Lesson 10
Computer programming 2  Lesson 10Computer programming 2  Lesson 10
Computer programming 2 Lesson 10
 

More from stopgolook

Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdf
Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdfJordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdf
Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdfstopgolook
 
Javai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdfJavai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdfstopgolook
 
J.M. Baker worked as a traditional land use researcher and consultan.pdf
J.M. Baker worked as a traditional land use researcher and consultan.pdfJ.M. Baker worked as a traditional land use researcher and consultan.pdf
J.M. Baker worked as a traditional land use researcher and consultan.pdfstopgolook
 
IT Project Management homework Identify any project of your choice.pdf
IT Project Management homework Identify any project of your choice.pdfIT Project Management homework Identify any project of your choice.pdf
IT Project Management homework Identify any project of your choice.pdfstopgolook
 
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdf
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdfINSTRUCTIONSDevelop, and present a plan and business case for an a.pdf
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdfstopgolook
 
In the realm of professional dynamics, understanding and appreciating .pdf
In the realm of professional dynamics, understanding and appreciating .pdfIn the realm of professional dynamics, understanding and appreciating .pdf
In the realm of professional dynamics, understanding and appreciating .pdfstopgolook
 
import React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdfimport React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdfstopgolook
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfstopgolook
 
Im trying to define a class in java but I seem to be having a bit o.pdf
Im trying to define a class in java but I seem to be having a bit o.pdfIm trying to define a class in java but I seem to be having a bit o.pdf
Im trying to define a class in java but I seem to be having a bit o.pdfstopgolook
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfstopgolook
 
In 2011, the head of the Presidential Protection Force (for purposes.pdf
In 2011, the head of the Presidential Protection Force (for purposes.pdfIn 2011, the head of the Presidential Protection Force (for purposes.pdf
In 2011, the head of the Presidential Protection Force (for purposes.pdfstopgolook
 
import java.util.Scanner;public class Main {private static i.pdf
import java.util.Scanner;public class Main {private static i.pdfimport java.util.Scanner;public class Main {private static i.pdf
import java.util.Scanner;public class Main {private static i.pdfstopgolook
 
If a taxpayer has investment income that exceeds a certain threshold.pdf
If a taxpayer has investment income that exceeds a certain threshold.pdfIf a taxpayer has investment income that exceeds a certain threshold.pdf
If a taxpayer has investment income that exceeds a certain threshold.pdfstopgolook
 
Im having an issue with the simulateOPT() methodthis is the p.pdf
Im having an issue with the simulateOPT() methodthis is the p.pdfIm having an issue with the simulateOPT() methodthis is the p.pdf
Im having an issue with the simulateOPT() methodthis is the p.pdfstopgolook
 
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdf
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdfI. Naive Robot Navigation ProblemDesign a program that uses the B.pdf
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdfstopgolook
 

More from stopgolook (15)

Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdf
Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdfJordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdf
Jordano Food Products Supply Chain Profile Jordano Foods Tracie Shan.pdf
 
Javai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdfJavai have to make a method that takes a linked list and then retu.pdf
Javai have to make a method that takes a linked list and then retu.pdf
 
J.M. Baker worked as a traditional land use researcher and consultan.pdf
J.M. Baker worked as a traditional land use researcher and consultan.pdfJ.M. Baker worked as a traditional land use researcher and consultan.pdf
J.M. Baker worked as a traditional land use researcher and consultan.pdf
 
IT Project Management homework Identify any project of your choice.pdf
IT Project Management homework Identify any project of your choice.pdfIT Project Management homework Identify any project of your choice.pdf
IT Project Management homework Identify any project of your choice.pdf
 
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdf
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdfINSTRUCTIONSDevelop, and present a plan and business case for an a.pdf
INSTRUCTIONSDevelop, and present a plan and business case for an a.pdf
 
In the realm of professional dynamics, understanding and appreciating .pdf
In the realm of professional dynamics, understanding and appreciating .pdfIn the realm of professional dynamics, understanding and appreciating .pdf
In the realm of professional dynamics, understanding and appreciating .pdf
 
import React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdfimport React, { useEffect } from react;import { BrowserRouter as.pdf
import React, { useEffect } from react;import { BrowserRouter as.pdf
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
 
Im trying to define a class in java but I seem to be having a bit o.pdf
Im trying to define a class in java but I seem to be having a bit o.pdfIm trying to define a class in java but I seem to be having a bit o.pdf
Im trying to define a class in java but I seem to be having a bit o.pdf
 
in c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdfin c languageTo determine the maximum string length, we need to .pdf
in c languageTo determine the maximum string length, we need to .pdf
 
In 2011, the head of the Presidential Protection Force (for purposes.pdf
In 2011, the head of the Presidential Protection Force (for purposes.pdfIn 2011, the head of the Presidential Protection Force (for purposes.pdf
In 2011, the head of the Presidential Protection Force (for purposes.pdf
 
import java.util.Scanner;public class Main {private static i.pdf
import java.util.Scanner;public class Main {private static i.pdfimport java.util.Scanner;public class Main {private static i.pdf
import java.util.Scanner;public class Main {private static i.pdf
 
If a taxpayer has investment income that exceeds a certain threshold.pdf
If a taxpayer has investment income that exceeds a certain threshold.pdfIf a taxpayer has investment income that exceeds a certain threshold.pdf
If a taxpayer has investment income that exceeds a certain threshold.pdf
 
Im having an issue with the simulateOPT() methodthis is the p.pdf
Im having an issue with the simulateOPT() methodthis is the p.pdfIm having an issue with the simulateOPT() methodthis is the p.pdf
Im having an issue with the simulateOPT() methodthis is the p.pdf
 
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdf
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdfI. Naive Robot Navigation ProblemDesign a program that uses the B.pdf
I. Naive Robot Navigation ProblemDesign a program that uses the B.pdf
 

Recently uploaded

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
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
 
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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
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
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
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
 

Recently uploaded (20)

Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
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
 
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
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
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
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
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
 

Java Code The traditional way to deal with these in Parsers is the .pdf

  • 1. Java Code: The traditional way to deal with these in Parsers is the Expression-Term-Factor pattern: Expression: TERM {+|- TERM} Term: FACTOR {*|/ FACTOR} Factor: number | ( EXPRESSION ) A couple of notation comments: | means "or" - either + or -, either * or / {} means an optional repeat. That's what allows this to parse 1+2+3+4 Think of these as functions. Every CAPTIALIZED word is a function call. Consider our meme expression above: 6/2*(1+2) We will start by looking at expression. Expression starts with a TERM. We can't do anything until we resolve TERM, so let's go there. A term starts with FACTOR. Again, we can't do anything until we deal with that. A factor is a number or a (EXPRESSION). Now we can look at our token (hint: MatchAndRemove). We see a number. OK - our factor is a number. We "return" that. Remember that we got to factor from term. Let's substitute our number in: TERM: FACTOR(6) {*|/ FACTOR} Now we deal with our optional pattern. Is the next character * or /? Yes! Now is the next thing a factor? It turns out that it is. Let's substitute that in: TERM: FACTOR(6) / FACTOR(2) But remember that our pattern is a REPEATING pattern (hint: loop): TERM: FACTOR(6) / FACTOR(2) {*|/ FACTOR} We see the * and call factor. But this time, the factor is not a number but a parenthetical expression. Factor: number | ( EXPRESSION ) Factor calls expression. Expression calls term, term calls factor, factor returns the number 1. Term doesn't see a * or / so it passes the 1 up. Expression sees the + and calls term. Term calls factor which returns the 2. Expression doesn't see a +|- value so ends the loop and returns 1+2. So, remember that we were here: TERM: FACTOR(6) / FACTOR(2) * FACTOR Our factor is (1+2). That can't be broken down. That math HAS to be done before can multiply or divide. That's what enforces order of operations. In code, this looks like something like this (pseudo-code):
  • 2. Node Factor() num = matchAndRemove(NUMBER) if (num.isPresent) return num if (matchAndRemove(LPAREN).isPresent) exp = Expression() if (exp == null) throw new Exception() if (matchAndRemove(RPAREN).isEmpty) throw new Exception() Node Term() left = Factor() do op = MatchAndRemove(TIMES) if (op.isEmpty) op=MatchAndRemove(DIVIDE) if (op.isEmpty) return left right = Factor() left = MathOpNode(left, op, right) while (true) Node Expression() left = Term() do op = MatchAndRemove(PLUS) if (op.isEmpty) op=MatchAndRemove(MINUS) if (op.isEmpty) return left right = Term() left = MathOpNode(left, op, right) while (true) What is this "MathOpNode"? It's "just" a new node type that holds two other nodes (left and right) and an operation type: *, /, +, -. Notice that the loops use the result of one operation as the left side of the next operation. This is called left associative - the left most part is done first. Right associativity is the opposite - the rightmost part is done first, then we work our way left. Generally, notice the pattern here - we call a function that is the lowest level of precedence. That
  • 3. function uses results from a higher level of precedence. The lower level can't do anything until the higher level is resolved. That "magic" is what enforces order of operation. Start by removing the call in ParseOperation to ParseBottomLevel(). Going through the rest of the chart is easier. The next level is PostIncrement/Decrement (example: x++ or y--). The patterns are: ParseBottomLevel() INC Operation(result of ParseBottomLevel, POSTINC) ParseBottomLevel() DEC Operation(result of ParseBottomLevel, POSTDEC) else return ParseBottomLevel(). The right associative methods are a little more complex than the left. Consider: 2^3^4. Left associative would be: (2^3)^4. This is 4096. 2^3^4. Right associative would be 2^(3^4). This is 2^81 which is ... very large. There are two similar ways to build this - either use a Stack OR use recursion (which uses the built-in call stack). The operations marked as "None" are terminal - there is no associativity because they can't recur. You can't have 3<4<5 or a ~ `hello` ~ `world` Implement the rest of the chart by creating methods that follow the patterns above. A few hints: To simplify the assignments, I created an AssigmentNode (Node target, Node expression). But how do we handle something like: a+=5 I split this into two parts - AssignmentNode and OperationNode. I would create this as: AssignmentNode (a, OperationNode(a + 5) ) We can now test with full expressions. Let's leave ParseOperation public so that we can write unit tests against it. Below is Parser.java and attached is the rubric. Use the Parser.java given below to add in all the needed methods as shown in the rubric. Don't copy the code given. Don't give an explanation. I need the code for the methods to be added in Parser.java. Make sure to follow the rubric carefully and include all the methods that looks for patterns in the tokenHandler's list. Parser.java import java.text.ParseException; import java.util.LinkedList; import java.util.List; import java.util.Optional; import javax.swing.ActionMap; public class Parser { private TokenHandler tokenHandler;
  • 4. private LinkedList tokens; public Parser(LinkedList tokens) { this.tokenHandler = new TokenHandler(tokens); this.tokens = tokens; } public boolean AcceptSeparators() { boolean foundSeparator = false; while (tokenHandler.MoreTokens()) { Optional currentToken = tokenHandler.getCurrentToken(); if (currentToken.isPresent() && (currentToken.get().getType() == Token.TokenType.NEWLINE || currentToken.get().getType() == Token.TokenType.SEMICOLON)) { tokenHandler.consumeMatchedToken(); foundSeparator = true; } else { break; } } return foundSeparator; } public ProgramNode Parse() throws ParseException { ProgramNode programNode = new ProgramNode(null, 0); while (tokenHandler.MoreTokens()) { if (!ParseFunction(programNode) && !parseAction(programNode)) { throw new ParseException("Unexpected token: " + tokenHandler.getCurrentToken().getStart()); } } return programNode; } private boolean ParseFunction(ProgramNode programNode) { Optional functionNameToken = tokenHandler.getCurrentToken(); if (tokenHandler.MatchAndRemove(Token.TokenType.IDENTIFIER) != null) { FunctionDefinitionNode functionNode = new FunctionDefinitionNode(functionNameToken.map(Token::getType).orElse(null).getStart()); programNode.addNode(functionNode);
  • 5. if (tokenHandler.MatchAndRemove(Token.TokenType.LPAREN) != null) { if (tokenHandler.MatchAndRemove(Token.TokenType.RPAREN) != null) { AcceptSeparators(); return true; } } } return false; } private boolean parseAction(ProgramNode programNode) { Optional functionNameToken = tokenHandler.getCurrentToken(); if (tokenHandler.MatchAndRemove(Token.TokenType.IDENTIFIER) != null) { ActionMap actionMap = new ActionMap(); programNode.addNode(actionMap); AcceptSeparators(); return true; } return false; } public VariableReferenceNode ParseLValueVariable(String variableName) { return new VariableReferenceNode(variableName, Optional.empty()); } public VariableReferenceNode ParseLValueArray(String variableName, int index) { return new VariableReferenceNode(variableName, Optional.of(index)); } public OperationNode ParseLValueDollar() { return new OperationNode("$"); } public ConstantNode ParseBottomLevelConstantsAndPatterns() { ConstantNodePatternNode node = new ConstantOrNodePatternNode(); node.setConstant("example"); node.setPattern("PATTERN_1"); return node; } public OperationNode ParseBottomLevelParenthesis() throws ParseException {
  • 6. if (tokenHandler.MatchAndRemove(Token.TokenType.LPAREN) != null) { OperationNode operationNode = ParseExpression(); if (tokenHandler.MatchAndRemove(Token.TokenType.RPAREN) != null) { return operationNode; } else { throw new ParseException("Expected ')'", tokenHandler.getCurrentToken().getStart()); } return null; } else { throw new ParseException("Expected '('", tokenHandler.getCurrentToken().getStart()); } } private OperationNode ParseExpression() { return null; } } begin{tabular}{|c|c|c|c|c|} hline Cade Style & Fewcomments,badnames(0) & Somegoodnamingsomenecessarycomments(3) & Mastlygaodnaming,mostnecessarycomments(6) & Goodnaming,non- trivialmethodswellcommented,staticonlywhennecessary,privatemembers(10) hline Unit Tests & Dantexist(0) & At least one (3) & Missingtests6 & All functionality tested (10) hline PastIncrement/Decrement & Daesntexist(0) & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(S) hline Exponents & Daesntexist(0) & Attempted(5) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult{10 hline Factor & Daesntexist(0) & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Term & Daesntexist0 & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Expression & Daesntexist(0) & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Concatenation & Daesntexist(0) & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline BaoleanCompare & Daesntexist0 & Attempted(3) & & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Match & Daesntexist(0) & Attempted(3) & &
  • 7. AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Arraymembership & Daesntexist(0) & Attempted(3) & & Acceptstokensappropriatelyand hline end{tabular} begin{tabular}{|c|c|c|c|} hline & & & generatesOperationNodeorreturnspartialresult(5) hline AND & Daesntexist(0) & Attempted(3) & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Or & Doesntexist(0) & Attempted(3) & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult(5) hline Ternary & Daesntexist(0) & Attempted(5) & AcceptstokensappropriatelyandgeneratesOperationNodeorreturnspartialresult{10} hline Assignment & Daesntexist0 & Attempted(5) & AcceptstokensappropriatelyandgeneratesAssignmentNodeorreturnspartialresult{10} hline end{tabular}