Print the AST out

This commit is contained in:
2026-08-01 09:16:32 +10:00
parent 80649d77ae
commit 7df9f25119
5 changed files with 128 additions and 11 deletions

View File

@@ -1,6 +1,8 @@
#include "parser.hpp"
#include <stdexcept>
#include <unordered_map>
#include <variant>
#include <ostream>
using TT = Solstice::TokenType;
@@ -17,6 +19,88 @@ namespace Solstice {
{TT::Comparison_LesserThan, NodeType::LesserThan},
};
std::optional<Literal> Node::getLiteral() const {
if (std::holds_alternative<Literal>(data)) {
return std::get<Literal>(data);
}
return {};
}
std::optional<std::string> Node::getIdentifier() const {
if (std::holds_alternative<std::string>(data)) {
return std::get<std::string>(data);
}
return {};
}
static inline std::string nodeTypeToString(NodeType type) {
switch (type) {
case NodeType::Root:
return "Root";
case NodeType::Literal:
return "Literal";
case NodeType::Identifier:
return "Identifier";
case NodeType::FunctionBind:
return "FunctionBind";
case NodeType::Bind:
return "Bind";
case NodeType::Set:
return "Set";
case NodeType::Lambda:
return "Lambda";
case NodeType::FunctionCall:
return "FunctionCall";
case NodeType::Add:
return "Add";
case NodeType::Subtract:
return "Subtract";
case NodeType::Multiply:
return "Multiply";
case NodeType::Divide:
return "Divide";
case NodeType::Equal:
return "Equal";
case NodeType::NotEqual:
return "NotEqual";
case NodeType::GreaterThan:
return "GreaterThan";
case NodeType::LesserThan:
return "LesserThan";
}
}
std::ostream& operator<<(std::ostream& stream, const Node& node) {
stream << "Node( Type=" << nodeTypeToString(node.type);
if (node.type == NodeType::Literal) {
auto lit = node.getLiteral();
if (lit.has_value()) {
stream << ", Literal: " << *lit;
}
} else if (node.type == NodeType::Identifier) {
auto id = node.getIdentifier();
if (id.has_value()) {
stream << ", Identifier: " << *id;
}
}
if (!node.children.empty()) {
stream << ", Children: { ";
bool first = true;
for (const auto& node : node.children) {
if (first) {
first = false;
} else {
stream << ", ";
}
stream << node;
}
stream << " }";
}
stream << " )";
return stream;
}
std::optional<Token> Parser::peek(int64_t ahead) {
if (current + ahead >= input.size() || current + ahead < 0) {
return {};