Skip to content

Commit

Permalink
Compiler: add support for importing libraries
Browse files Browse the repository at this point in the history
  • Loading branch information
mrunix00 committed Aug 2, 2024
1 parent 0ba65e5 commit be2e6a4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions include/ast.h
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,14 @@ struct ImportStatement : public AbstractSyntaxTree {
std::string path;
explicit ImportStatement(std::string path);
bool operator==(const AbstractSyntaxTree &other) const override;
void compile(Program &program, Segment &segment) const override;
};

struct ExportStatement : public AbstractSyntaxTree {
AbstractSyntaxTree *stm;
explicit ExportStatement(AbstractSyntaxTree *stm);
bool operator==(const AbstractSyntaxTree &other) const override;
void compile(Program &program, Segment &segment) const override;
};

std::vector<AbstractSyntaxTree *> parse(const char *input);
Expand Down
21 changes: 21 additions & 0 deletions src/ast.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#include "ast.h"
#include "utils.h"

#include <fstream>
#include <sstream>
#include <utility>

Node::Node(Token token) : token(std::move(token)) {
Expand Down Expand Up @@ -621,17 +623,36 @@ bool ImportStatement::operator==(const AbstractSyntaxTree &other) const {
auto &otherImportStatement = dynamic_cast<const ImportStatement &>(other);
return otherImportStatement.path == path;
}
void ImportStatement::compile(Program &program, Segment &segment) const {
std::ifstream importedFile(path);
if (!importedFile.is_open()) {
throw std::runtime_error("Unable to open file: " + path);
}
std::stringstream fileContent;
fileContent << importedFile.rdbuf();
auto statements = parse(fileContent.str().c_str());
for (auto stm : statements) {
if(stm->nodeType == AbstractSyntaxTree::Type::ExportStatement)
stm->compile(program, segment);
delete stm;
}
}

ExportStatement::ExportStatement(AbstractSyntaxTree *stm)
: stm(stm) {
nodeType = AbstractSyntaxTree::Type::ExportStatement;
typeStr = "ExportStatement";
assert(stm->nodeType == AbstractSyntaxTree::Type::Declaration,
"[ExportStatement]: Only declarations can be exported!");
}
bool ExportStatement::operator==(const AbstractSyntaxTree &other) const {
if (nodeType != other.nodeType) return false;
auto &otherExportStatement = dynamic_cast<const ExportStatement &>(other);
return *otherExportStatement.stm == *stm;
}
void ExportStatement::compile(Program &program, Segment &segment) const {
stm->compile(program, segment);
}

void compile(Program &program, const char *input) {
auto ast = parse(input);
Expand Down

0 comments on commit be2e6a4

Please sign in to comment.