#include <iostream> #include <string> #include <vector> #include <stdexcept> #include <cctype> #include <iomanip> // 用于缩进
// ------------------------- // 1. Token 定义和词法分析 // ------------------------- enum TokenType { NUMBER, PLUS, MINUS, MULTIPLY, DIVIDE, LPAREN, RPAREN, END, };
struct Token { TokenType type; double value; // 仅当 type == NUMBER 时有效 };
class Lexer { std::string text; size_t pos = 0; char currentChar() { return pos < text.size() ? text[pos] : ‘\0’; } void advance() { pos++; }
public: Lexer(const std::string& text) : text(text) {}
Token getNextToken() {
while (isspace(currentChar())) advance();
if (currentChar() == '\0') {
return { END, 0 };
}
if (isdigit(currentChar())) {
std::string numStr;
while (isdigit(currentChar()) || currentChar() == '.') {
numStr += currentChar();
advance();
}
return { NUMBER, std::stod(numStr) };
}
if (currentChar() == '+') {
advance();
return { PLUS, 0 };
}
if (currentChar() == '-') {
advance();
return { MINUS, 0 };
}
if (currentChar() == '*') {
advance();
return { MULTIPLY, 0 };
}
if (currentChar() == '/') {
advance();
return { DIVIDE, 0 };
}
if (currentChar() == '(') {
advance();
return { LPAREN, 0 };
}
if (currentChar() == ')') {
advance();
return { RPAREN, 0 };
}
throw std::runtime_error("Invalid character");
}
};
// ------------------------- // 2. AST 节点定义 // ------------------------- struct ASTNode { virtual ~ASTNode() = default; virtual double evaluate() = 0; virtual void print(int depth = 0) const = 0; };
struct NumberNode : ASTNode { double value;
NumberNode(double val) : value(val) {}
double evaluate() override { return value; }
void print(int depth = 0) const override {
std::cout << std::string(depth * 2, ' ') << "Number: " << value << std::endl;
}
};
struct BinOpNode : ASTNode { char op; ASTNode* left; ASTNode* right;
BinOpNode(char op, ASTNode* left, ASTNode* right)
: op(op), left(left), right(right) {
}
~BinOpNode() {
delete left;
delete right;
}
double evaluate() override {
switch (op) {
case '+': return left->evaluate() + right->evaluate();
case '-': return left->evaluate() - right->evaluate();
case '*': return left->evaluate() * right->evaluate();
case '/': {
double rightVal = right->evaluate();
if (rightVal == 0) throw std::runtime_error("Division by zero");
return left->evaluate() / rightVal;
}
default: throw std::runtime_error("Invalid operator");
}
}
void print(int depth = 0) const override {
std::cout << std::string(depth * 2, ' ') << "Operator: " << op << std::endl;
std::cout << std::string((depth + 1) * 2, ' ') << "Left:" << std::endl;
left->print(depth + 2);
std::cout << std::string((depth + 1) * 2, ' ') << "Right:" << std::endl;
right->print(depth + 2);
}
};
// ------------------------- // 3. 语法分析器(递归下降) // ------------------------- class Parser { Lexer lexer; Token currentToken;
void eat(TokenType expected) {
if (currentToken.type == expected) {
currentToken = lexer.getNextToken();
}
else {
throw std::runtime_error("Unexpected token");
}
}
ASTNode* factor() {
Token token = currentToken;
if (token.type == NUMBER) {
eat(NUMBER);
return new NumberNode(token.value);
}
else if (token.type == LPAREN) {
eat(LPAREN);
ASTNode* node = expr();
eat(RPAREN);
return node;
}
else if (token.type == MINUS) {
eat(MINUS);
return new BinOpNode('-', new NumberNode(0), factor());
}
throw std::runtime_error("Unexpected token in factor");
}
ASTNode* term() {
ASTNode* node = factor();
while (currentToken.type == MULTIPLY || currentToken.type == DIVIDE) {
Token op = currentToken;
if (op.type == MULTIPLY) {
eat(MULTIPLY);
}
else if (op.type == DIVIDE) {
eat(DIVIDE);
}
node = new BinOpNode(op.type == MULTIPLY ? '*' : '/', node, factor());
}
return node;
}
ASTNode* expr() {
ASTNode* node = term();
while (currentToken.type == PLUS || currentToken.type == MINUS) {
Token op = currentToken;
if (op.type == PLUS) {
eat(PLUS);
}
else if (op.type == MINUS) {
eat(MINUS);
}
node = new BinOpNode(op.type == PLUS ? '+' : '-', node, term());
}
return node;
}
public: Parser(const std::string& text) : lexer(text), currentToken(lexer.getNextToken()) {}
ASTNode* parse() {
ASTNode* result = expr();
if (currentToken.type != END) {
throw std::runtime_error("Unexpected token at end");
}
return result;
}
};
// ------------------------- // 4. 主函数(新增打印AST的调用) // ------------------------- int main() { while (true) { std::cout << “Enter an expression (or ‘exit’ to quit): ”; std::string input; std::getline(std::cin, input);
if (input == "exit") break;
try {
Parser parser(input);
ASTNode* ast = parser.parse();
std::cout << "\nAST Structure:" << std::endl;
ast->print(); // 打印AST结构
double result = ast->evaluate();
std::cout << "\nResult: " << result << std::endl;
delete ast;
}
catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
}
return 0;
}