ExprAST * FAO::ParseBinOpRHS(int Expc, ExprAST * lhs) { // If this is a binary operator,find its precedence while (true){ int TokPrec = GetPrecedence(); // If this is a binary operator,find its precedence at least as tightly as the current binary operator // consume it,otherwise we are done. if (TokPrec < Expc){ return lhs; } // Okay,we know this is binary operator char BinOp = cur_token_.GetOperation(); Advance(); // eat binary operator // Parse the primary expression after the binary operator ExprAST * rhs = ParsePrimary(); if (rhs == nullptr){ return nullptr; } // If binary operator less tightly with rhs than the operator after rhs,let // the pending operator than rhs as its lhs int NextPrec = GetPrecedence(); if (TokPrec < NextPrec){ rhs = ParseBinOpRHS(TokPrec + 1, rhs); if (rhs == nullptr){ return nullptr; } } // Merge lhs/rhs lhs = new BinaryOpExpr(BinOp, lhs, rhs); } return lhs; }
PNode CreateInfixTree(char* exp) { // create a dummy root with minimal precedence // its content is trivial PNode root = CreateNode("0"); root->precedence = 0; // the previous operand of current operator PNode preOperand = NULL; // the previous operator of current operator PNode preOperator = root; // the impact of preceding parenthesis, if any int correction = 0; int i = 0; char* token = strtok( exp, " " ); while(token) { if (IsOperand(token)) { preOperand = CreateNode(token); } else if (IsOperator(token)) { printf("entrou em eh operador\n"); PNode p = CreateNode(token); p->precedence = GetPrecedence(token) + correction; if (p->precedence > preOperator->precedence) { p->left = preOperand; preOperator->right = p; p->parent = preOperator; } else { preOperator->right = preOperand; PNode q = preOperator->parent; while (p->precedence <= q->precedence) q = q->parent; p->left = q->right; q->right = p; p->parent = q; } preOperand = NULL; preOperator = p; }//else if (IsOperator(exp[i]) else if (IsLeftParenthesis(token)) { correction += 2; } else if (IsRightParenthesis(token)) { correction -= 2; } else { printf("illegal token found: %c\n", exp[i]); break; } token = strtok(NULL, " "); }//while if (preOperand == NULL) printf("illegal expression: cannot end with operator: %s\n", preOperator->data); else preOperator->right = preOperand; // delete dummy root PNode realRoot = root->right; //delete root; free(root); if (realRoot) realRoot->parent = NULL; return realRoot; }