Exemplo n.º 1
0
        public string visit(BinOp node)
        {
            switch (node.op.type)
            {
            case tokens.PLUS:
                return(Convert.ToString(Convert.ToInt32(node.left.accept(this)) + Convert.ToInt32(node.right.accept(this))));

            case tokens.MINUS:
                return(Convert.ToString(Convert.ToInt32(node.left.accept(this)) + Convert.ToInt32(node.right.accept(this))));

            case tokens.MUL:
                return(Convert.ToString(Convert.ToInt32(node.left.accept(this)) * Convert.ToInt32(node.right.accept(this))));

            case tokens.DIV:
                return(Convert.ToString(Convert.ToInt32(node.left.accept(this)) / Convert.ToInt32(node.right.accept(this))));
            }
            return(visit(node));
        }
Exemplo n.º 2
0
        // term: factor ((MUL|DIV) factor)*
        public AST term()
        {
            AST node = factor();

            string[] valid_operators = new string[] { tokens.MUL, tokens.DIV };
            while (Array.IndexOf(valid_operators, current_token.type) != -1)
            {
                Token t = current_token;
                if (t.type == tokens.MUL)
                {
                    eat(tokens.MUL);
                }
                else if (t.type == tokens.DIV)
                {
                    eat(tokens.DIV);
                }
                node = new BinOp(node, t, factor());
            }

            return(node);
        }
Exemplo n.º 3
0
        // expr: term ((PLUS|MINUS) term)*
        public AST expr()
        {
            AST node = term();

            /* ((PLUS|MINUS) term)* turns into a while loop */
            string[] valid_operators = new string[] { tokens.PLUS, tokens.MINUS };
            while (Array.IndexOf(valid_operators, current_token.type) != -1)
            {
                Token t = current_token;
                if (t.type == tokens.PLUS)
                {
                    eat(tokens.PLUS);
                }
                else if (t.type == tokens.MINUS)
                {
                    eat(tokens.MINUS);
                }
                node = new BinOp(node, t, term());
            }
            return(node);
        }