예제 #1
0
        private AST GetTerm()
        {
            //term : factor ((MUL | DIV) factor)*
            //------------------------------------------

            var node = Factor();      // we start with the first factor

            //we can now have 0 or more (MUL | DIV) followed by a new factor
            while (currentToken.type == Token.MUL || currentToken.type == Token.DIV)
            {
                var token = currentToken;
                if (currentToken.type == Token.MUL)
                {
                    Eat(Token.MUL); // we found a 'pluss' token, consume it
                    //result *= Factor(); //add the next term to our result
                }
                else
                {
                    Eat(Token.DIV);
                    //result /= Factor();
                }
                node = new BinOp(node, token, Factor());
            }

            return(node);
        }
예제 #2
0
        private AST Expr()
        {
            /*
             * expr   : term ((PLUS | MINUS) term)*
             * term   : factor ((MUL | DIV) factor)*
             * factor : INTEGER | LPAREN expr RPAREN
             */


            var node = GetTerm(); //get the starting value

            while (currentToken.type == Token.PLUS || currentToken.type == Token.MINUS)
            {
                var token = currentToken;
                if (currentToken.type == Token.PLUS)
                {
                    Eat(Token.PLUS); // we found a 'pluss' token, consume it
                }
                else
                {
                    Eat(Token.MINUS);
                }

                node = new BinOp(node, token, GetTerm());
            }

            return(node);
        }
예제 #3
0
        private int VisitBinOp(BinOp node)
        {
            if (node.op.type == Token.PLUS)
            {
                var left  = Visit(node.left);
                var right = Visit(node.right);
                return(left + right);
            }

            if (node.op.type == Token.MINUS)
            {
                var left  = Visit(node.left);
                var right = Visit(node.right);
                return(left - right);
            }

            if (node.op.type == Token.MUL)
            {
                var left  = Visit(node.left);
                var right = Visit(node.right);
                return(left * right);
            }

            if (node.op.type == Token.DIV)
            {
                var left  = Visit(node.left);
                var right = Visit(node.right);
                return(left / right);
            }

            Error();
            return(-1);
        }