Question

You’ll create the parser with a 2-part layered approach. You’ll first create a Lexer, which will read characters from a file and output tokens. Then you’ll write the second part, which will process th...

You’ll create the parser with a 2-part layered approach. You’ll first create a Lexer, which will read characters from a file and output tokens. Then you’ll write the second part, which will process the tokens and determine if there are errors in the program.

This program have 3 files Lexer.java, Token.java, Parser.java

Part 1 Lexer:

The class Lexer should have the following methods:
public constructor which takes a file name as a parameter○private
getInput which reads the data from the file into a char array
public getNextToken which returns a Token object
private functions for getIdentifier and getInteger.
These helper functions should handle extracting the rest of an identifier/integer once one is identified
A main function that calls getNextToken within a loop and prints out all the tokens in the given file.

For example, if your file contains:

aa=34

bb=45+6

The Lexer will print:

TokenType Token Value

Identifier aa

AssignOp =

Integer 34

Identifier bb

AssignOp =

Integer 45

PlusOp +

Integer 6

EndOfFile -

Part 2 Parser

Define the class Parser with the following methods:
A constructor which creates a Lexer as a data member
parseProgram -- this method drives the process and parses an entire program.
Thismethod should call parseAssignment within a loop
parseAssignment -- this method should parse a single assignment statement. It shouldcall parseId, parseAssignmentOp, and parseExpression.
parseId-- this method parses a single identifier
parseAssignOp-- this method parses a single assignment operator
parseExpression-- this method parses an expression, i.e., the right-hand-side of anassignment. Note that expressions can include + signs, e.g., Y+3+4
a main method which just creates a Parser and calls ParseProgram.

For instance, the code:

x12=17+43

a = x12+35+1

is syntactically correct for the SIMPLE language, and the parser should just report, “valid program”.

The code: 17=x+3 is not valid and the parser should report, “Expecting Identifier on line 1”.

Starting code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;

public class Lexer {

final int MAXSIZE=3000;
char buffer[]; // this will hold the chars of the file
int bufSize=0; // how many chars their actually are
int index=0; // the location within buffer as we scan

public Lexer(String fileName) {
this.buffer = new char[MAXSIZE];
getInput(fileName);

}
public void getInput(String fileName) {
File inputFile = new File (fileName);
try (FileReader reader = new FileReader(inputFile)) {
this.bufSize = reader.read(this.buffer,0,1000);
} catch(FileNotFoundException fnf) {
System.out.println("File not found.");
System.out.println(fnf.getMessage());
System.exit(1);
} catch(IOException exc) {
System.out.println("IO Exception");
System.out.println(exc.getMessage());
System.exit(1);
}

}
// just print out buffer, mainly for debugging
public String toString() {
int i=0;
String s="";
while (i s = s+this.buffer[i];
i++;
}
return s;
}
// this method scans the buffer starting at index. If it finds a lowercase letter, it
// continues to scan and adds the lower case letters to a string until a non lower-case letter
// is scanned. this.index is incremented and will end up on the last lowercase letter
// NOTE: THIS IS A SAMPLE METHOD YOU DO NOT NEED IN LEXER
public String firstWord() {
String s="";
char c = this.buffer[this.index];
while ((c>='a') && (c<='z')) {
s=s+c;
this.index++;
c = this.buffer[this.index];
}
return s;

}

public static void main(String[] args) {
Lexer lexer = new Lexer("token_file");
System.out.println(lexer);
System.out.println(lexer.firstWord());

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please let me know if you have any doubts or you want me to modify the answer. And if you find this answer useful then don't forget to rate my answer as thumps up. Thank you! :)


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;


public class Lexer {

    final int MAXSIZE = 3000;
    char buffer[];
    int bufferSize = 0;
    int index = 0;


    public Lexer(String fileName) {
        this.buffer = new char[MAXSIZE];
        getInput(fileName);

    }


    private void getInput(String fileName) {
        File inputFile = new File(fileName);
        try (FileReader reader = new FileReader(inputFile)) {
            this.bufferSize = reader.read(this.buffer, 0, 1000);
        } catch (FileNotFoundException fnf) {
            System.out.println("File not found.");
            System.out.println(fnf.getMessage());
            System.exit(1);
        } catch (IOException exc) {
            System.out.println("IO Exception");
            System.out.println(exc.getMessage());
            System.exit(1);
        }

    }

    public Token getNextToken() {


        if (buffer[index] == '\n') {
            index++;
            //return (new Token("\n", "\n"));
        }


        if (buffer[index] == ' ')
            index++;

        while (this.index < this.bufferSize || this.buffer[index] != '-') {

            if (Character.isDigit(this.buffer[index])) {

                return getInteger();

            } else if (Character.isLetterOrDigit(this.buffer[index])) {
                return getIdentifier();

            } else if (this.buffer[index] == '+') {
                index++;
                return (new Token("PlusOp", "+"));

            } else if (this.buffer[index] == '=') {
                index++;
                return (new Token("AssignOp", "="));

            } else if (this.buffer[index] == '#') {
                index++;
                return (new Token("Unknown", "#"));

            }else if (this.buffer[index] == '$'){
                index++;
                return (new Token("Unknown", "$"));

            } else if (this.buffer[index] == '-') {
                return (new Token("End of File", "-"));
            }

        }
        return getNextToken();

    }


    public String toString() {
        int i = 0;
        String s = "";
        while (i < this.bufferSize) {
            s = s + this.buffer[i];
            i++;
        }
        return s;
    }


    private Token getIdentifier() {
        String str = "";
        while ((this.index < this.bufferSize) && Character.isLetterOrDigit(this.buffer[index])) {
            str += this.buffer[index];
            index++;
        }
        return (new Token("Identifier", str));
    }

    private Token getInteger() {
        String str = "";

        while ((this.index < this.bufferSize) && Character.isDigit(this.buffer[index])) {
            str += this.buffer[index];
            index++;

        }
        return (new Token("Integer", str));
    }


    public static void main(String[] args) {
        Lexer lexer = new Lexer("/Users/swapnil/IdeaProjects/LexerParser/src/input.txt");
        //System.out.println(lexer);


        System.out.println("Token Type    Token Value\n");
        Token tok = lexer.getNextToken();
        System.out.println(tok);


        while (!tok.getType().equals("End of File")) {
            tok = lexer.getNextToken();
            System.out.println(tok);


        }

    }

}


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Token {
    private String type;
    private String value;
    //private final EOF = '-';


    public Token (String type, String value){
        this.type = type;
        this.value = value;

    }

    public String getType() {
        return type;
    }

    public String toString(){
        return (type + "        " +value);
    }

    public boolean equals(Token other){
        return this.value == other.value;
    }


}


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
public class Parser {
    Lexer l1;
    Token tok;


    //tok.getType()


    public Parser(Lexer l1){
        this.l1 = l1;
        tok = l1.getNextToken();

    }

    public boolean parseExpression(){

        System.out.println(tok);


        while (!tok.getType().equals("\n")){
            if(!tok.getType().equals("Integer")){
                System.out.println(tok + " is not integer");
                System.out.println("Invalid");
                return false;
            }
            tok = l1.getNextToken();
            System.out.println(tok);

            if (!tok.getType().equals("PlusOp")){
                System.out.println(tok + " is not identifier");
                System.out.println("Invalid");
                return false;
            }
            tok = l1.getNextToken();
        }

        return true;
    }

    public boolean parseAssignOp(){
        //l1.getNextToken();

        if(tok.getType().equals("AssignOp")){
            System.out.println("=");
            tok = l1.getNextToken();

            return true;
        }else{
            return false;
        }


    }

    public boolean parseId() {

        System.out.println(tok);
        l1.index++;
        //tok = l1.getNextToken();
        if (tok.getType().equals("Identifier")) {
            tok = l1.getNextToken();
            return true;
        }else {
            System.out.println("Not an Identifier");
        }

        return false;
    }

    public void parseAssignment(){
        //l1.getNextToken();
        parseId();
        parseAssignOp();
        parseExpression();

    }

    public void parseProgram(){

        while(tok.getType() != "End of File"){
            parseAssignment();
            break;

        }

    }

    public static void main(String [] args){


        Lexer l1 = new Lexer("/Users/swapnil/IdeaProjects/LexerParser/src/input.txt");
        Parser par = new Parser(l1);
        par.parseProgram();

    }
}

LexerParser [~/IdeaProjects/LexerParser]-,../src/Lexer.java [LexerParser] Project 『LoxerParser-/IdeaProjects/LexerParser idea

Add a comment
Know the answer?
Add Answer to:
You’ll create the parser with a 2-part layered approach. You’ll first create a Lexer, which will read characters from a file and output tokens. Then you’ll write the second part, which will process th...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • The following code uses a Scanner object to read a text file called dogYears.txt. Notice that...

    The following code uses a Scanner object to read a text file called dogYears.txt. Notice that each line of this file contains a dog's name followed by an age. The program then outputs this data to the console. The output looks like this: Tippy 2 Rex 7 Desdemona 5 1. Your task is to use the Scanner methods that will initialize the variables name1, name2, name3, age1, age2, age3 so that the execution of the three println statements below will...

  • 1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you...

    1. Copy the file secret.txt into a path that you can access. Read FilePath.doc if you have questions on file path. Copy SecretMessage.java into your NetBeans or other IDE tools. 2. Finish the main method that will read the file secret.txt, separate it into word tokens.You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. These letters should converted to capitals, then be appended to StringBuffer object to...

  • QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes...

    QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...

  • Your assignment is to write a grade book for a teacher. The teacher has a text file, which includ...

    Your assignment is to write a grade book for a teacher. The teacher has a text file, which includes student's names, and students test grades. There are four test scores for each student. Here is an example of such a file: Count: 5 Sally 78.0 84.0 79.0 86.0 Rachel 68.0 76.0 87.0 76.0 Melba 87.0 78.0 98.0 88.0 Grace 76.0 67.0 89.0 0.0 Lisa 68.0 76.0 65.0 87.0 The first line of the file will indicate the number of students...

  • The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java....

    The names of the two input files as well as the output file are supposed to be provided as arguments. Could you please fix it? Thanks. DPriorityQueue.java: // Import the required classes import java.io.*; import java.util.*; //Create the class public class DPriorityQueue { //Declare the private members variables. private int type1,type2; private String CostInTime[][], SVertex, DVertex; private List<String> listOfTheNodes; private Set<String> List; private List<Root> ListOfVisitedNode; private HashMap<String, Integer> minimalDistance; private HashMap<String, Integer> distOfVertices; private PriorityQueue<City> priorityQueue; // prove the definition...

  • Write a program that can read XML files for customer accounts receivable, such as <ar>        <customerAccounts>...

    Write a program that can read XML files for customer accounts receivable, such as <ar>        <customerAccounts>               <customerAccount>                       <name>Apple County Grocery</name>                       <accountNumber>1001</accountNumber>                       <balance>1565.99</balance>               </customerAccount>               <customerAccount>                       <name>Uptown Grill</name>                       <accountNumber>1002</accountNumber>                       <balance>875.20</balance>               </customerAccount>        </customerAccounts>        <transactions>               <payment>                       <accountNumber>1002</accountNumber>                       <amount>875.20</amount>               </payment>               <purchase>                       <accountNumber>1002</accountNumber>                       <amount>400.00</amount>               </purchase>               <purchase>                       <accountNumber>1001</accountNumber>                       <amount>99.99</amount>               </purchase>               <payment>                       <accountNumber>1001</accountNumber>                       <amount>1465.98</amount>               </payment>        </transactions>     </ar> Your program should construct an CustomerAccountsParser object, parse the XML data & create new CustomerAccount objects in the CustomerAccountsParser for each of the products the XML data, execute all of...

  • C++ Write a function parseScores which takes a single input argument, a file name, as a string. Your function should read each line from the given filename, parse and process the data, and print the r...

    C++ Write a function parseScores which takes a single input argument, a file name, as a string. Your function should read each line from the given filename, parse and process the data, and print the required information. Your function should return the number of student entries read from the file. Empty lines do not count as entries, and should be ignored. If the input file cannot be opened, return -1 and do not print anything.     Your function should be named...

  • This task involves constructing a Java program that supports interaction via a graphical user interface.The object...

    This task involves constructing a Java program that supports interaction via a graphical user interface.The object is to implement a Scrabble graphical game. The basis for the game is quite simple. Presented with a 6x6 grid of Scrabble tiles, the challenge is for the player(s) to form as many high scoring words as possible.  Words may only be formed from sequences of adjacent tiles.  Two tiles are adjacent if their edges or corners meet.  A tile may...

  • Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written...

    Must be written in JAVA Code Write a program that will read in a file of student academic credit data and create a list of students on academic warning. The list of students on warning will be written to a file. Each line of the input file will contain the student name (a single String with no spaces), the number of semester hours earned (an integer), the total quality points earned (a double). The following shows part of a typical...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT