/** * This constructor is used when VARDECL is a STMT. We get the ID and the type, ensure that it is * a valid type, and add it to its parent body's vartable. * * @param b the parent body * @param c the Code object */ public VARDECL(BODY b, Code c) { body = b; code = c.currentLine(); lineNum = c.currentLineNum(); String[] tokens = Code.tokenize(code); type = tokens[1]; // Ensure that the type is int, string or bool. if (!Terminals.dataTypes.contains(type)) Interpreter.error( "VARDECL", lineNum, code, "Invalid VARDECL data type. Must be int, string, or bool"); if (type.equals(Terminals.VOID)) Interpreter.error( "VARDECL", lineNum, code, "Invalid VARDECL data type. Must be int, string, or bool"); // Get the ID id = ID.validate(tokens[2], c); if (tokens[tokens.length - 1] != Terminals.SEMICOLON) { Interpreter.error("VARDECL", lineNum, code, "Missing semicolon"); } // Add to the varTable of the parent body body.varTable.add(this); }
/** * Ensure that the var doesn't exist twice in the same varTable (it can exist in different * varTables) */ public void validate() { Interpreter.writeln("validate", "Validating VARDECL"); if (Collections.frequency(body.varTable, Interpreter.findVar(body, id)) > 1) { Interpreter.error( "VARDECL", lineNum, code, "Var " + id + " cannot be declared more than once!"); } }
/** Simple print function */ public void print() { if (id != null && type != null) { Interpreter.write("parse", "vardecl " + type + " " + id); } else Interpreter.write("parse", "Empty VARDECL"); }
/** This is a special print function we use for printing the variable tables. */ public void printVar() { if (id != null && type != null) { Interpreter.write("debug", type + " " + id); } else Interpreter.write("debug", "Empty VARDECL"); }