1

Implement codegen using an Observer

This commit is contained in:
2023-03-21 15:48:42 +01:00
parent 7e1159f785
commit e92e7d2183
4 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,18 @@
//
// Created by christoph on 20.03.23.
//
#include "PostfixObserver.h"
PostfixObserver::PostfixObserver(const Node &root) : Observer(root) {}
// TODO: Shouldn't be recursive
void PostfixObserver::traverse(const Node &node) {
for (const auto &child : node.getChildren()) {
depth++;
traverse(*child);
depth--;
}
action(node);
}

23
src/ast/PostfixObserver.h Normal file
View File

@ -0,0 +1,23 @@
//
// Created by christoph on 20.03.23.
//
#ifndef LOGISIMASSEMBLER_POSTFIXOBSERVER_H
#define LOGISIMASSEMBLER_POSTFIXOBSERVER_H
#include "Observer.h"
class PostfixObserver : public Observer {
public:
PostfixObserver(const Node &root);
~PostfixObserver() override = default;
protected:
void traverse(const Node &node) override;
protected:
uint32_t depth = 0;
};
#endif //LOGISIMASSEMBLER_PREFIXOBSERVER_H

View File

@ -0,0 +1,20 @@
//
// Created by christoph on 21.03.23.
//
#include "CodegenObserver.h"
#include <boost/format.hpp>
#include <iostream>
CodegenObserver::CodegenObserver(const Node &node, std::string &output_string)
: PostfixObserver(node), output_string(output_string) {}
void CodegenObserver::action(const Node &node) {
const uint8_t opcode = node.compile();
const uint8_t INVALID = -1;
if (opcode != INVALID) {
output_string += (boost::format("%x") % static_cast<uint32_t>(opcode)).str(); // uint8_t is always interpreted as char
output_string += ' ';
}
}

View File

@ -0,0 +1,23 @@
//
// Created by christoph on 21.03.23.
//
#ifndef LOGISIMASSEMBLER_CODEGENOBSERVER_H
#define LOGISIMASSEMBLER_CODEGENOBSERVER_H
#include "../ast/PostfixObserver.h"
class CodegenObserver : public PostfixObserver {
public:
CodegenObserver(const Node &node, std::string &output_string);
~CodegenObserver() override = default;
protected:
void action(const Node &node) override;
private:
std::string &output_string;
};
#endif //LOGISIMASSEMBLER_CODEGENOBSERVER_H