PorygonLang/src/Script.cpp

112 lines
3.1 KiB
C++

#include <utility>
#include <vector>
#include <iterator>
#include <unordered_map>
#include "Script.hpp"
#include "Parser/Lexer.hpp"
#include "Parser/Parser.hpp"
#include "Binder/Binder.hpp"
Script* Script::Create(string script) {
auto s = new Script();
s -> Parse(std::move(script));
return s;
}
Script::Script() {
Diagnostics = new DiagnosticsHolder();
_evaluator = new Evaluator(this);
_boundScript = nullptr;
_scriptVariables = new unordered_map<size_t, shared_ptr<EvalValue>>(0);
}
EvalValue* Script::Evaluate() {
return _evaluator->Evaluate(_boundScript);
}
Script::~Script() {
delete this -> Diagnostics;
delete this -> _boundScript;
delete this -> _evaluator;
this->_scriptVariables->clear();
delete this->_scriptVariables;
}
void Script::Parse(string script) {
auto lexer = Lexer(&script, this);
auto lexResult = lexer.Lex();
auto parser = Parser(lexResult, this);
auto parseResult = parser.Parse();
for (auto token : lexResult){
delete token;
}
lexResult.clear();
if (!Diagnostics->HasErrors()){
unordered_map<int, BoundVariable*> scriptScope;
auto bindScope = new BoundScope(&scriptScope);
this->_boundScript = Binder::Bind(this, parseResult, bindScope);
for (const auto& v : scriptScope){
this->_scriptVariables -> insert({v.first, nullptr});
delete v.second;
}
scriptScope.clear();
}
delete parseResult;
}
EvalValue *Script::GetVariable(const string &key) {
return _scriptVariables -> at(HashedString(key).GetHash()).get();
}
bool Script::HasVariable(const string &key) {
auto f = _scriptVariables->find(HashedString(key).GetHash());
return f != _scriptVariables->end();
}
EvalValue *Script::GetLastValue() {
return _evaluator->GetLastValue();
}
bool Script::HasFunction(const string &key) {
auto f = _scriptVariables->find(HashedString(key).GetHash());
return f != _scriptVariables->end() && f.operator->()->second->GetType()->GetClass() == TypeClass ::Function;
}
shared_ptr<EvalValue> Script::CallFunction(const string &key, vector<EvalValue *> variables) {
auto var = (ScriptFunctionEvalValue*)GetVariable(key);
return this->_evaluator->EvaluateFunction(var, std::move(variables));
}
extern "C" {
Script* CreateScript(char * s){
return Script::Create(s);
}
void EvaluateScript(Script* script){
script->Evaluate();
}
EvalValue* GetLastValue(Script* script){
return script->GetLastValue();
}
bool HasVariable(Script* script, const char* key){
return script->HasVariable(key);
}
EvalValue* GetVariable(Script* script, const char* key){
return script->GetVariable(key);
}
bool HasFunction(Script* script, const char* key){
return script->HasFunction(key);
}
EvalValue* CallFunction(Script* script, const char* key, EvalValue* parameters[], int parameterCount){
std::vector<EvalValue*> v(parameters, parameters + parameterCount);
return script->CallFunction(key, v).get();
}
}