/** CS 363 Lab 5 * Let's take a look at block variable (register) allocation. * We will scan some variable "declarations" that occur in * blocks, and see how many distinct memory locations are needed. * Note that variables declared in mutually exclusive blocks * can be overlapped in memory. * Example input: The variables can be stored as: * { R1: a * declare a; R2: b * declare b; R3: c * declare c; R4: x, r [they can share same space!] * { R5: y * declare x; * declare y; * } * { * declare r; * } * } */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; import java.util.Stack; import java.util.ArrayList; public class Driver { public static void main(String [] args) throws FileNotFoundException { // A register is a list of variables. ArrayList [] register = new ArrayList [32]; Scanner kbd = new Scanner(System.in); System.out.print("What is the name of the input file? "); String fileName = kbd.nextLine(); Scanner in = new Scanner(new FileInputStream(fileName)); Stack stack = new Stack(); int regNum = 1; int nestLevel = 0; // At this point we have the file, being read by the stream "in". while (in.hasNextLine()) { String line = in.nextLine(); // What should I do with the input line? If blank, skip it. :) // Each line of the input file could be: // Case 1: an open curly brace "{" // Case 2: a close curly brace "}" // Case 3: a declaration. StringTokenizer tok = new StringTokenizer(line, " ;"); if (tok.countTokens() == 0) continue; String token = tok.nextToken(); if (token.equals("{")) { // ADD CODE HERE } else if (token.equals("}")) { // ADD CODE HERE } else // it's a variable declaration! { String varName = tok.nextToken(); Variable v = new Variable(varName, nestLevel); // ADD CODE HERE } } // Output the variables assigned to each register. for (int i = 1; i <= 31; ++i) { if (register[i] == null) continue; int numVariables = register[i].size(); System.out.printf("Register %2d: ", i); for (int j = 0; j < numVariables - 1; ++j) System.out.printf("%s, ", register[i].get(j).toString()); System.out.printf("%s\n", register[i].get(numVariables - 1).toString()); } } }