This commit is contained in:
aozhiwei 2023-03-03 13:49:50 +08:00
parent f0b4b7aa16
commit 592661bae5
2 changed files with 75 additions and 8 deletions

View File

@ -43,6 +43,58 @@ namespace a8
vars_[name] = std::make_shared<Value>(proc);
}
GlobalScope::GlobalScope()
{
RegisterCProc
(
"+",
[] (const List& params) -> std::shared_ptr<Value>
{
Atom result;
for (auto param : params) {
Atom&& atom = std::any_cast<Atom>(param->value);
result.val += atom.val;
}
return std::make_shared<Value>(result);
});
RegisterCProc
(
"-",
[] (const List& params) -> std::shared_ptr<Value>
{
Atom result;
for (auto param : params) {
Atom&& atom = std::any_cast<Atom>(param->value);
result.val -= atom.val;
}
return std::make_shared<Value>(result);
});
RegisterCProc
(
"*",
[] (const List& params) -> std::shared_ptr<Value>
{
Atom result;
for (auto param : params) {
Atom&& atom = std::any_cast<Atom>(param->value);
result.val *= atom.val;
}
return std::make_shared<Value>(result);
});
RegisterCProc
(
"/",
[] (const List& params) -> std::shared_ptr<Value>
{
Atom result;
for (auto param : params) {
Atom&& atom = std::any_cast<Atom>(param->value);
result.val /= atom.val;
}
return std::make_shared<Value>(result);
});
}
std::shared_ptr<Value> Expr::Compile(const std::string& script, std::shared_ptr<Scope> scope)
{
@ -67,12 +119,21 @@ namespace a8
{
List&& list = std::any_cast<List>(x->value);
auto leader = list.at(0);
if (leader->type != ValueType::kCProc) {
abort();
if (leader->type == ValueType::kCProc) {
CProc&& cproc = std::any_cast<CProc>(leader->value);
List exps;
for (auto itr = list.begin() + 1; itr != list.end(); ++itr) {
exps.push_back(Eval(*itr, env));
}
return cproc(exps);
} else {
CProc&& cproc = std::any_cast<CProc>(Eval(leader, env)->value);
List exps;
for (auto itr = list.begin() + 1; itr != list.end(); ++itr) {
exps.push_back(Eval(*itr, env));
}
return cproc(exps);
}
CProc&& cproc = std::any_cast<CProc>(leader->value);
List exps = List(list.begin() + 1, list.end());
return cproc(exps);
}
break;
default:

View File

@ -21,7 +21,7 @@ namespace a8
};
struct Value;
typedef std::vector<std::shared_ptr<Value>> List;
typedef std::function<std::shared_ptr<Value>(const List)> CProc;
typedef std::function<std::shared_ptr<Value>(const List&)> CProc;
struct Atom
{
@ -56,12 +56,18 @@ namespace a8
std::shared_ptr<Scope> outer_;
};
class GlobalScope : public Scope
{
public:
GlobalScope();
};
class Expr
{
public:
std::shared_ptr<Value> Compile(const std::string& script, std::shared_ptr<Scope> scope);
std::shared_ptr<Value> Eval(std::shared_ptr<Value> x, std::shared_ptr<Scope> env);
static std::shared_ptr<Value> Compile(const std::string& script, std::shared_ptr<Scope> scope);
static std::shared_ptr<Value> Eval(std::shared_ptr<Value> x, std::shared_ptr<Scope> env);
private:
};