Esempio n. 1
0
        /**
         * Function VisitAssignStmt --> <var_ident> := <expr>
         * It updates the value of the identifier in the SymbleTable
         * Throws an error if the variable was not previous declarated
         * Param : assign statement to evaluate
         */
        public Object VisitAssignStmt(Stmt.Assign stmt)
        {
            String name = stmt.Name.Text;

            /* If the var is already in the table we change its value */
            if (SymbleTable.ContainsKey(name))
            {
                Value val = Evaluate(stmt.Value);
                if (val.Type.Equals(SymbleTable[name].Type))
                {
                    SymbleTable[name] = val;
                }
                /* If the expected type and the type of the new assign do not match */
                else
                {
                    throw new RuntimeError(stmt.Name, "Expected " + SymbleTable[name].Type.ToString()
                                           + " but found " + val.Type.ToString());
                }
            }
            /* Otherwise it was not declarated before so it is an error */
            else
            {
                throw new RuntimeError(stmt.Name, "This variable does not exist. Not prevoius declared.");
            }
            return(null);
        }
Esempio n. 2
0
        /**
         * Function VisitAssignStmt : it checks that the variable and the assignment
         * has the same type. Also it throws an error if we try to assign a new value
         * for the loop counter inside the loop or if the type is wrong
         * Param : assign statement to check
         */
        public object VisitAssignStmt(Stmt.Assign stmt)
        {
            /* Error when trying to assign to the loop counter inside the loop */
            if (illegalAssignments.Contains(stmt.Name.Text))
            {
                throw new TypeError(stmt.Name, "Cannot assign to " + stmt.Name.Text + " in a for loop where it is used as a loop counter.");
            }

            /* Check that the var to assign already exists */
            if (SymbleTypeTable.ContainsKey(stmt.Name.Text))
            {
                /* Check that the var and the assigment have same type */
                VALTYPE right = GetType(stmt.Value);
                if (right.Equals(SymbleTypeTable[stmt.Name.Text]))
                {
                    return(null);
                }
                else
                {
                    throw new TypeError(stmt.Name, stmt.Name.Text + " has type " + SymbleTypeTable[stmt.Name.Text] + " but was tried to assign type: " + right.ToString());
                }
            }
            else
            {
                throw new TypeError(stmt.Name, "The var '" + stmt.Name.Text + "' does not exist. Cannot assign not pervious declared variables.");
            }
        }