Fix Expr & T parsing

This commit is contained in:
augustin64 2023-11-10 20:02:54 +01:00
parent 46b9bc4cf4
commit 691bf3a232

View File

@ -56,7 +56,6 @@ Node parse(vector<Token> tokens) {
}; };
node = new_node; node = new_node;
} }
} }
return node; return node;
@ -174,30 +173,41 @@ ParseReturn parse_expr(vector<Token> tokens) {
//* We construct a tree //* We construct a tree
while (tokens.size() != 0) { while (tokens.size() != 0) {
try { NodeType type;
ParseReturn ret = parse_t(tokens);
tokens = ret.tokens; switch (tokens.back().type) {
} catch (const ParseException& pex) { case (TokenType::Plus):
type = NodeType::Plus;
break;
case (TokenType::Minus):
type = NodeType::Minus;
break;
default:
return { return {
.node=node, .node=node,
.tokens=tokens .tokens=tokens
}; };
} }
if (tokens.size() != 0) { Token last_token;
if (tokens.back().type == TokenType::Plus) { try {
last_token = tokens.back();
tokens.pop_back();
ParseReturn ret = parse_t(tokens);
tokens = ret.tokens;
InnerNode new_node = { InnerNode new_node = {
.type=NodeType::Plus, .type=type,
.children={node, ret.node} .children={node, ret.node}
}; };
node = new_node; node = new_node;
} else if (tokens.back().type == TokenType::Minus) { } catch (const ParseException& pex) {
InnerNode new_node = { tokens.emplace_back(last_token);
.type=NodeType::Minus, return {
.children={node, ret.node} .node=node,
.tokens=tokens
}; };
node = new_node;
}
} }
} }
@ -220,36 +230,44 @@ ParseReturn parse_t(vector<Token> tokens) {
//* We construct a tree //* We construct a tree
while (tokens.size() != 0) { while (tokens.size() != 0) {
try { NodeType type;
ParseReturn ret = parse_u(tokens);
tokens = ret.tokens; switch(tokens.back().type) {
} catch (const ParseException& pex) { case (TokenType::Star):
type = NodeType::Mult;
break;
case (TokenType::Slash):
type = NodeType::Div;
break;
case (TokenType::Percent):
type = NodeType::Mod;
break;
default:
return { return {
.node=node, .node=node,
.tokens=tokens .tokens=tokens
}; };
} }
if (tokens.size() != 0) {
if (tokens.back().type == TokenType::Star) { Token last_token;
try {
last_token = tokens.back();
tokens.pop_back();
ParseReturn ret = parse_u(tokens);
tokens = ret.tokens;
InnerNode new_node = { InnerNode new_node = {
.type=NodeType::Mult, .type=type,
.children={node, ret.node} .children={node, ret.node}
}; };
node = new_node; node = new_node;
} else if (tokens.back().type == TokenType::Slash) { } catch (const ParseException& pex) {
InnerNode new_node = { tokens.emplace_back(last_token);
.type=NodeType::Div, return {
.children={node, ret.node} .node=node,
.tokens=tokens
}; };
node = new_node;
} else if (tokens.back().type == TokenType::Percent) {
InnerNode new_node = {
.type=NodeType::Mod,
.children={node, ret.node}
};
node = new_node;
}
} }
} }