public ProgramState Execute(ProgramState state) { MyIDictionary <int, MyPair <string, StreamReader> > fileTable = state.GetFileTab(); MyIDictionary <string, int> symTable = state.GetSymTab(); // 1. evaluate var_file_id to a value int value; try { value = var_file_id.Evaluate(symTable); } catch (ExpressionEvaluationException e) { throw new MyStatementExecutionException("Cannot read from var " + var_file_id.ToString() + "."); } // 2. get the StreamReader object associated in the file table. If there is no entry associated // with that value in the file table, we stop the execution StreamReader sr; try { sr = fileTable.Get(value).GetSecond(); } catch (InvalidKeyMyDictionaryException) { throw new MyStatementExecutionException("Error. There is no entry (" + value + ") in the file table."); } // 3. Read a line from the file using the ReadLine() method of the StreamReader object. // If line is null create a zero int value, otherwise translate the string into an int value int read; try { string line = sr.ReadLine(); read = line.Equals(null) ? 0 : Int32.Parse(line); } catch (IOException) { throw new MyStatementExecutionException("Error on reading from file."); } // 4. Add a new mapping (var_name, int value computed at the previous step) into the sym-table. // If var_name exists in sym-table, update its associated value instead of adding a new mapping symTable.Put(var_name, read); // 5. return return(null); }
public ProgramState Execute(ProgramState state) { MyIDictionary <string, int> symTab = state.GetSymTab(); try { int value = expr.Evaluate(symTab); symTab.Put(id, value); } catch (ExpressionEvaluationException e) { Console.WriteLine(e.ToString()); } return(null); }
public ProgramState Execute(ProgramState state) { MyIDictionary <int, MyPair <string, StreamReader> > fileTable = state.GetFileTab(); MyIDictionary <string, int> symTable = state.GetSymTab(); // 1. check whether the filename is not already in the file table // If it exists stop the execution with an appropiate error message foreach (MyPair <string, StreamReader> pair in fileTable.Values()) { if (pair.GetFirst().Equals(filename)) { throw new MyStatementExecutionException("File " + filename + " already open."); } } // 2. open the file filename. If the file does not exists or other IO error occurs, // stop the execution with an appropiate error message StreamReader sr; try { sr = new StreamReader(filename); } catch (FileNotFoundException) { throw new MyStatementExecutionException("File " + filename + " does not exist"); } catch (IOException e) { throw new MyStatementExecutionException(e.ToString()); } // 3. create a new entrance into the file table which maps a new unique integer id // to the (filename, StreamReader class created before) pair fileTable.Put(++fd, new MyPair <string, StreamReader>(filename, sr)); // 4. set the var_file_id to that new unique integer key into the sym-table. symTable.Put(var_file_id, fd); // 5. return return(null); }