Our "machines" do it because that's how a parser works. Here's the code for evaluating an expression out of my own coding language. Please excuse the messiness of the code; it's not yet in production so obviously it's not 100% optimized and pretty.
AST::ExprAST *ParseBinOpRHS(int ExprPrec, Lexer::Token token, Lexer::Token binop) {
AST::ExprAST *LHS;
LHS = ParsePrimary(token);
while(1) {
int tokPrec = GetTokPrecedence(binop);
if(tokPrec < ExprPrec)
return LHS;
Lexer::Token nextToken = Lexer::getToken();
AST::ExprAST *RHS = ParsePrimary(nextToken);
if(RHS == 0) {
return error("Syntax Error! Expected value.");
}
if(GetTokPrecedence(nextToken) > tokPrec) {
RHS = ParseBinOpRHS(tokPrec+1, nextToken, binop);
}
LHS = (AST::ExprAST *)new AST::BinaryExprAST(binop.strVal.c_str()[0], LHS, RHS);
binop = nextToken;
}
}
For those of you who don't speak code, it evaluates the left half of the expression (in 5+6+2 this would be '5'), determines the right half of the expression (in 5+6+2 this would be 6), solves, then uses the solution as the left side of the expression (making the new expression 11+2).