diff --git a/src/parser.cpp b/src/parser.cpp index 8bd3218..ad35d0a 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -56,7 +56,6 @@ Node parse(vector tokens) { }; node = new_node; } - } return node; @@ -174,31 +173,42 @@ ParseReturn parse_expr(vector tokens) { //* We construct a tree while (tokens.size() != 0) { + NodeType type; + + switch (tokens.back().type) { + case (TokenType::Plus): + type = NodeType::Plus; + break; + case (TokenType::Minus): + type = NodeType::Minus; + break; + default: + return { + .node=node, + .tokens=tokens + }; + } + + Token last_token; try { + last_token = tokens.back(); + tokens.pop_back(); + ParseReturn ret = parse_t(tokens); tokens = ret.tokens; + + InnerNode new_node = { + .type=type, + .children={node, ret.node} + }; + node = new_node; } catch (const ParseException& pex) { + tokens.emplace_back(last_token); return { .node=node, .tokens=tokens }; } - - if (tokens.size() != 0) { - if (tokens.back().type == TokenType::Plus) { - InnerNode new_node = { - .type=NodeType::Plus, - .children={node, ret.node} - }; - node = new_node; - } else if (tokens.back().type == TokenType::Minus) { - InnerNode new_node = { - .type=NodeType::Minus, - .children={node, ret.node} - }; - node = new_node; - } - } } return { @@ -220,37 +230,45 @@ ParseReturn parse_t(vector tokens) { //* We construct a tree while (tokens.size() != 0) { + NodeType type; + + switch(tokens.back().type) { + case (TokenType::Star): + type = NodeType::Mult; + break; + case (TokenType::Slash): + type = NodeType::Div; + break; + case (TokenType::Percent): + type = NodeType::Mod; + break; + default: + return { + .node=node, + .tokens=tokens + }; + } + + + Token last_token; try { + last_token = tokens.back(); + tokens.pop_back(); ParseReturn ret = parse_u(tokens); tokens = ret.tokens; + + InnerNode new_node = { + .type=type, + .children={node, ret.node} + }; + node = new_node; } catch (const ParseException& pex) { + tokens.emplace_back(last_token); return { .node=node, .tokens=tokens }; } - - if (tokens.size() != 0) { - if (tokens.back().type == TokenType::Star) { - InnerNode new_node = { - .type=NodeType::Mult, - .children={node, ret.node} - }; - node = new_node; - } else if (tokens.back().type == TokenType::Slash) { - InnerNode new_node = { - .type=NodeType::Div, - .children={node, ret.node} - }; - node = new_node; - } else if (tokens.back().type == TokenType::Percent) { - InnerNode new_node = { - .type=NodeType::Mod, - .children={node, ret.node} - }; - node = new_node; - } - } } return {