/** Top-down parser for CS 363 Lab 1. * We create a top-down parser for variable declarations. * The possible input tokens are: "int" id num "," ";" "=" */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.ArrayList; import java.util.Stack; import java.util.StringTokenizer; public class Declaration { // Maintain a list of tokens, and a variable to keep track of // which one we are looking at during the parse. ArrayList tokenList; int pos; public Declaration() { tokenList = new ArrayList(); pos = 0; } public void scan() throws IOException { // To get started, we read standard input for our example variable // declarations. Then we "scan" it by using the standard String Tokenizer // from the Java API, and put the tokens into an arraylist. BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.printf("Please enter variable declaration, separating " + "each token by a space.\n"); String line = in.readLine(); StringTokenizer tok = new StringTokenizer(line, " "); // See what kind of token we have and store that information in list. while(tok.hasMoreTokens()) { String token = tok.nextToken(); String tokenType = ""; if (token.equals(",") || token.equals(";") || token.equals("=") || token.equals("int")) tokenType = token; else { try { int value = Integer.parseInt(token); tokenType = "num"; } catch (Exception e) { // If it's not a number, let's assume it's an identifier. tokenType = "id"; } } tokenList.add(tokenType); } // At this point we have our tokens in tokenList. // The tokens are stored as strings, where each string is one of the // following: "int" "id" "num" "," ";" "=" // debugging output //for (int i = 0; i < tokenList.size(); ++i) // System.out.printf("%s\n", tokenList.get(i)); } /* * Phase 1 - do top-down parsing using a table */ public void parseWithTable() { // Create stack, and start by pushing the start symbol on the stack. Stack stack = new Stack(); stack.push("list"); // Do until the stack is empty... while (stack.size() > 0) { // temp variable to save typing String tos = stack.peek(); String input = tokenList.get(pos); // First case is where the top-of-stack is list and the input token // is int. What should we pop from and push onto the stack? if (tos.equals("list") && input.equals("int")) { System.out.printf("replacing list with int var tail\n"); } // handle other cases // handle syntax error message and abort program. } System.out.printf("Parse is successful.\n"); } /////////////////////////////////////////////////////////////////////// /* * Phase 2 - do top-down parsing based on recursive descent */ public void parseRecursiveDescent() { parseList(); } public void parseList() { String token = tokenList.get(pos++); if (! token.equals("int")) { System.out.printf("int expected, found %s at token #%d\n", token, pos); System.exit(1); } parseVar(); parseTail(); } public void parseVar() { } public void parseTail() { } }