diff options
author | Roland Reichwein <mail@reichwein.it> | 2020-11-06 18:20:34 +0100 |
---|---|---|
committer | Roland Reichwein <mail@reichwein.it> | 2020-11-06 18:20:34 +0100 |
commit | 71c7fd62f8b5257b82cf32b0f747fcf313fcc617 (patch) | |
tree | 6f014b14d08080459a04a965912c62605d9015ca /cpp.cpp | |
parent | 62aafc5c9273cb0b7a91bf2e4dee1ac2d3658bb3 (diff) |
Prepare Token/Node handling
Diffstat (limited to 'cpp.cpp')
-rw-r--r-- | cpp.cpp | 55 |
1 files changed, 39 insertions, 16 deletions
@@ -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<std::string>& return true; // match } -void CPP::trDeclaration(index_t node_id) +//std::unordered_map<std::string, std::function<>> + +// 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<std::any> 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<std::any>(data)); + } else { + mValues.push_back(std::make_shared<std::any>(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 |