a8/a8/lisp.h
aozhiwei bb2f76674d 1
2023-03-03 22:05:15 +08:00

81 lines
1.7 KiB
C++

#pragma once
/*
数据类型
符号: symbol
列表: list
原子: atom
*/
namespace a8
{
namespace lisp
{
enum class ValueType : int
{
kAtom = 1,
kList = 2,
kSymbol = 3,
kCProc = 4,
};
struct Value;
typedef std::shared_ptr<std::vector<std::shared_ptr<Value>>> List;
typedef std::function<std::shared_ptr<Value>(const List&)> CProc;
struct Atom
{
double val = 0;
};
struct Symbol
{
std::string name;
};
struct Value
{
ValueType type;
std::string name;
std::any value;
Value(Atom atom);
Value(List list);
Value(Symbol symbol);
Value(const std::string& proc_name, CProc cproc);
bool IsType(ValueType t) { return t == type; };
a8::XObject ToXObject();
};
class Scope
{
public:
std::shared_ptr<Value> Find(const std::string& name);
void RegisterCProc(const std::string& name, CProc proc);
private:
std::map<std::string, std::shared_ptr<Value>> vars_;
std::shared_ptr<Scope> outer_;
};
class GlobalScope : public Scope
{
public:
GlobalScope();
};
class Expr
{
public:
static std::shared_ptr<Value> Compile(const std::string& script, std::shared_ptr<Scope> env);
static std::shared_ptr<Value> Eval(std::shared_ptr<Value> x, std::shared_ptr<Scope> env);
private:
static int GetToken(const std::string& script, int& pos, std::string& token);
};
}
}