/**
 * Derived class that represents a variable declaration statement in the SILLY language.
 *   @author Dave Reed
 *   @version 2/3/18
 */
public class VarDeclaration extends Statement {
    private Assignment assign;
    
    /**
     * Reads in a variable declaration statement from the specified TokenStream.
     *   @param input the stream to be read from
     */
    public VarDeclaration(TokenStream input) throws Exception {
        if (!input.next().toString().equals("var")) {
            throw new Exception("SYNTAX ERROR: Malformed variable declaration.");
        }
        this.assign = new Assignment(input);
    }
    
    /**
     * Executes the current variable declaration statement.
     */
    public void execute() throws Exception {
        if (Interpreter.MEMORY.lookupVariable(this.assign.getVariable()) == null) {
            Interpreter.MEMORY.storeVariable(this.assign.getVariable(), new NumberValue(-1));
            this.assign.execute();
        }
        else {
            throw new Exception("RUNTIME ERROR: " + this.assign.getVariable() + " is already declared");
        }
    }
    
    /**
     * Converts the current variable declaration statement into a String.
     *   @return the String representation of this statement
     */
    public String toString() {
        return "var " + this.assign;
    }
}
