From 71c7fd62f8b5257b82cf32b0f747fcf313fcc617 Mon Sep 17 00:00:00 2001 From: Roland Reichwein Date: Fri, 6 Nov 2020 18:20:34 +0100 Subject: Prepare Token/Node handling --- cpp.cpp | 55 +++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 16 deletions(-) (limited to 'cpp.cpp') diff --git a/cpp.cpp b/cpp.cpp index 2135e67..b9f405f 100644 --- a/cpp.cpp +++ b/cpp.cpp @@ -1,5 +1,6 @@ #include "cpp.h" +#include "flowgraph/node.h" #include "bnf.h" #include "cppbnf.h" #include "debug.h" @@ -294,25 +295,46 @@ bool CPP::childTypesOfNodeMatch(index_t node_id, const std::vector& return true; // match } -void CPP::trDeclaration(index_t node_id) +//std::unordered_map> + +// precondition: stack contains child values c1, ..., cn on top -> to be popped +// postcondition: stack contains value on top -> to be pushed +void CPP::getValueOfNode(index_t index) { - std::cout << "DEBUG" << std::endl; + size_t num_childs {m_nodes[index].child_ids.size()}; + + if (mValues.size() < num_childs) + throw std::runtime_error("Expected num_childs elements on Values stack at "s + locationOfNode(index)); + + std::shared_ptr result {nullptr}; + + mValues.resize(mValues.size() - num_childs); + + mValues.push_back(result); } -void CPP::trTranslationUnit(index_t node_id) +// pushes result onto stack +void CPP::getValueOfToken(index_t index) { - if (childTypesOfNodeMatch(node_id, {"declaration-seq"})) { - // resolve sequence - do { - node_id = m_nodes[node_id].child_ids[0]; - if (childTypesOfNodeMatch(node_id, {"declaration"})) { - trDeclaration(m_nodes[node_id].child_ids[0]); - return; - } - } while (childTypesOfNodeMatch(node_id, {"declaration-seq", "declaration"})); - compileError(node_id, "ICE: bad declaration-seq"); - } else - compileError(node_id, "declaration-seq expected"); + if (m_tokens[index].type == "literal") { + FlowGraph::Data data{FlowGraph::MakeConstantInt(stoi(m_tokens[index].value))}; + mValues.push_back(std::make_shared(data)); + } else { + mValues.push_back(std::make_shared(nullptr)); + } +} + +void CPP::visitRecursive(index_t node_id) +{ + const auto& childs {m_nodes[node_id].child_ids}; + for (const auto child: childs) { + if (ChildIdIsNode(child)) { + visitRecursive(child); + } else { + getValueOfToken(TokenIdFromChildId(child)); + } + } + getValueOfNode(node_id); } // Phase 7.c: Translate @@ -321,7 +343,8 @@ void CPP::translate() if (m_nodes.size() == 0) throw std::runtime_error("ICE: Tree is empty"); - trTranslationUnit(0); + // TODO: this could be implemented iteratively, via a stack? + visitRecursive(0); } // Phase 8: Instantiate objects -- cgit v1.2.3