// This is for UCSD CSE 141L, Spring 2006. -Wei and JSampson // // This is some sample code to parse an assembly instruction. Compile with // the provided Makefile. // To run do: // > java Jparser // import java.util.*; import java.io.*; import java.lang.Runtime.*; class Jscanner { public static int debug; private int inst_count; private int line_count; Jscanner() { debug = 0; inst_count = 0; line_count = 0; } private static void help(String error) { System.out.println("usage: scanner [-d] [-h] input"); System.out.println(" [-d] debug"); System.out.println(" [-h] help"); System.out.println(error); } // This uses flex to tokenize strings, and return back what type of // token it is. Depending on the type it prints out a different // message. // Assumes that FILE* yyin variable has been initialized. yyin needs // to point to the input text file. private int parse_inst(Reader r, String filename) { int token = 0; int index; int oper_index = 0; int cii = 0; int cop = 0; int value; inst_count = 0; line_count = 1; boolean found_inst = false; Sample_flex lex = new Sample_flex(r); // Keeps track of line number, and if currently parsing an // instruction followed by operands. // yylex returns an integer with a correponding token tag // prints out debug message do { try { token = lex.yylex() ; } catch (java.io.IOException e) { System.out.println("IO error scanning file \""+filename+"\""); System.out.println(e); } catch (Exception e) { System.out.println("Unexpected exception:"); e.printStackTrace(); } if(token == Token_type.NEWLINE) { found_inst = false; line_count++; } else if(token == Token_type.TOKEN) { if(found_inst) { System.out.println("\t operand TOKEN "+lex.getToken()+ " at line "+ line_count); } else { System.out.println("I have found an instruction TOKEN "+ lex.getToken()+" at line "+line_count); found_inst = true; // state machine can also implemented in flex } } else if(token == Token_type.LABEL) { System.out.println("I have found an instruction LABEL "+ lex.getToken()+" at line "+line_count); } else if(token == lex.YYEOF || token==0) { // end of file reached break; } else { System.out.println("I dont recognize "+ lex.getToken()+" at line "+line_count+" " + token); } } while(true); return inst_count; } public static void main(String argv[]) { Jscanner scan = new Jscanner(); int arg_index = 0; if(argv.length<1) { help("error: wrong number of args "+argv.length); return; } while(arg_index