Compare commits

..

5 Commits

9 changed files with 228 additions and 62 deletions

133
AST.cpp
View File

@ -77,8 +77,12 @@ std::shared_ptr<Value> FuncDefAST::eval(Context* parent, std::vector<std::shared
ptr = dynamic_cast<IfAST*>(ptr)->getResult(ctx.get()).get(); ptr = dynamic_cast<IfAST*>(ptr)->getResult(ctx.get()).get();
if (!ptr) if (!ptr)
continue; continue;
if (ptr->getType() == T_ReturnAST) if (ptr->getType() == T_ReturnAST) {
return ptr->eval(ctx.get()); auto retAST = dynamic_cast<ReturnAST*>(ptr);
if (this->name == retAST->getName())
return ptr->eval(ctx.get());
throw std::runtime_error("Return name mismatch. Closure is not implemented yet!");
}
ret = ptr->eval(ctx.get()); ret = ptr->eval(ctx.get());
} }
return ret; return ret;
@ -121,59 +125,92 @@ std::shared_ptr<ExprAST> IfAST::getResult(Context* parent) {
} }
std::shared_ptr<Value> LoopAST::eval(Context* parent) { std::shared_ptr<Value> LoopForeverAST::eval(Context* parent) {
// Eval start & end // No context is needed
auto s = this->start->eval(parent); while (true) {
auto e = this->end->eval(parent); for (auto& stmt : this->body) {
if (s->isArray() || e->isArray()) auto* ptr = stmt.get();
throw std::runtime_error("Cannot eval loop start or end as integer"); if (ptr->getType() == T_IfAST)
auto sc = std::dynamic_pointer_cast<SingleValue>(s); ptr = dynamic_cast<IfAST*>(ptr)->getResult(parent).get();
auto ec = std::dynamic_pointer_cast<SingleValue>(e); if (!ptr)
if (!sc || !ec) continue;
throw std::runtime_error("Unexpected error"); if (ptr->getType() == T_ReturnAST)
return ptr->eval(parent);
if (sc->isT()) { ptr->eval(parent);
while (true) {
// No need to create a new context
for (auto& stmt : this->body) {
auto* ptr = stmt.get();
if (ptr->getType() == T_IfAST)
ptr = dynamic_cast<IfAST*>(ptr)->getResult(parent).get();
if (!ptr)
continue;
if (ptr->getType() == T_ReturnAST)
return ptr->eval(parent);
}
} }
} else { }
if (!sc->isInt() || !ec->isInt()) throw std::runtime_error("Unexpected error");
throw std::runtime_error("Cannot eval loop start or end as integer"); }
auto ss = sc->getInt(); std::shared_ptr <Value> LoopForAST::eval(Context* parent) {
auto ee = ec->getInt(); // Create a new context
auto ctx = std::make_shared<Context>(parent);
// Create a new context // Eval condition
auto ctx = std::make_shared<Context>(parent); auto s = std::dynamic_pointer_cast<SingleValue>(this->start->eval(parent)->copy());
auto e = std::dynamic_pointer_cast<SingleValue>(this->end->eval(parent));
for (auto i = ss; i <= ee; ++i) { // Assert that s and e are numeric
ctx->setVariable(this->loopVar, std::make_shared<SingleValue>(i)); if (!s || !e || (!s->isInt() && !s->isFloat()) || (!e->isInt() && !e->isFloat()))
for (auto& stmt : this->body) { throw std::runtime_error("LoopForAST: start and end must be numeric");
auto* ptr = stmt.get();
if (ptr->getType() == T_IfAST) // Main loop
ptr = dynamic_cast<IfAST*>(ptr)->getResult(ctx.get()).get(); while (*s <= *e) {
if (!ptr) // Set the variable
continue; ctx->setVariable(this->name, s);
if (ptr->getType() == T_ReturnAST)
return ptr->eval(ctx.get()); // Eval body
} for (auto& stmt : this->body) {
auto* ptr = stmt.get();
if (ptr->getType() == T_IfAST)
ptr = dynamic_cast<IfAST*>(ptr)->getResult(ctx.get()).get();
if (!ptr)
continue;
if (ptr->getType() == T_ReturnAST)
return ptr->eval(ctx.get());
ptr->eval(ctx.get());
}
// Increment
s->operator++();
}
// Return nil
return std::make_shared<SingleValue>(false);
}
std::shared_ptr <Value> LoopDoTimesAST::eval(Context* parent) {
// Create a new context
auto ctx = std::make_shared<Context>(parent);
// Eval condition
auto terminate = std::dynamic_pointer_cast<SingleValue>(this->times->eval(parent)->copy());
if (!terminate || !terminate->isInt())
throw std::runtime_error("DOTIMES: times must be an integer");
auto n = terminate->getInt();
// Main Loop
for (std::int64_t i = 0; i < n; ++i) {
// Set Variable
ctx->setVariable(this->name, std::make_shared<SingleValue>(i));
// Eval Body
for (auto& stmt : this->body) {
auto* ptr = stmt.get();
if (ptr->getType() == T_IfAST)
ptr = dynamic_cast<IfAST*>(ptr)->getResult(ctx.get()).get();
if (!ptr)
continue;
if (ptr->getType() == T_ReturnAST)
return ptr->eval(ctx.get());
ptr->eval(ctx.get());
} }
} }
// Return nil // Return nil
return std::make_shared<SingleValue>(); return std::make_shared<SingleValue>(false);
} }
std::shared_ptr<Value> UnaryAST::eval(Context* parent) { std::shared_ptr<Value> UnaryAST::eval(Context* parent) {
auto val = this->expr->eval(parent); auto val = this->expr->eval(parent);
auto valS = std::dynamic_pointer_cast<SingleValue>(val); auto valS = std::dynamic_pointer_cast<SingleValue>(val);
@ -334,7 +371,7 @@ std::shared_ptr<Value> ListAST::eval(Context* parent) {
std::transform(vals2.begin(), vals2.end(), std::back_inserter(intVal), [&](std::shared_ptr<SingleValue>& ptr) { std::transform(vals2.begin(), vals2.end(), std::back_inserter(intVal), [&](std::shared_ptr<SingleValue>& ptr) {
return ptr->getInt(); return ptr->getInt();
}); });
return std::make_shared<SingleValue>(std::reduce(intVal.begin() + 1, intVal.end(), intVal[0], [this](std::int64_t x, std::int64_t y) { return std::make_shared<SingleValue>(std::accumulate(intVal.begin() + 1, intVal.end(), intVal[0], [this](std::int64_t x, std::int64_t y) {
switch (this->op) { switch (this->op) {
case LOGAND: case LOGAND:
return x & y; return x & y;
@ -386,12 +423,12 @@ std::shared_ptr<Value> ListAST::eval(Context* parent) {
std::transform(vals2.begin(), vals2.end(), std::back_inserter(floatVal), [&](std::shared_ptr<SingleValue>& ptr) { std::transform(vals2.begin(), vals2.end(), std::back_inserter(floatVal), [&](std::shared_ptr<SingleValue>& ptr) {
return (ptr->isFloat() ? ptr->getFloat() : ptr->getInt()); return (ptr->isFloat() ? ptr->getFloat() : ptr->getInt());
}); });
return std::make_shared<SingleValue>(std::reduce(floatVal.begin() + 1, floatVal.end(), floatVal[0], opFunc)); return std::make_shared<SingleValue>(std::accumulate(floatVal.begin() + 1, floatVal.end(), floatVal[0], opFunc));
} else { } else {
std::transform(vals2.begin(), vals2.end(), std::back_inserter(intVal), [&](std::shared_ptr<SingleValue>& ptr) { std::transform(vals2.begin(), vals2.end(), std::back_inserter(intVal), [&](std::shared_ptr<SingleValue>& ptr) {
return ptr->getInt(); return ptr->getInt();
}); });
return std::make_shared<SingleValue>(std::reduce(intVal.begin() + 1, intVal.end(), intVal[0], opFunc)); return std::make_shared<SingleValue>(std::accumulate(intVal.begin() + 1, intVal.end(), intVal[0], opFunc));
} }
} }

52
AST.h
View File

@ -17,6 +17,9 @@ enum ASTType {
T_FuncCallAST, T_FuncCallAST,
T_IfAST, T_IfAST,
T_LoopAST, T_LoopAST,
T_LoopForeverAST,
T_LoopForAST,
T_LoopDoTimesAST,
T_UnaryAST, T_UnaryAST,
T_BinaryAST, T_BinaryAST,
T_ListAST, T_ListAST,
@ -132,20 +135,52 @@ public:
} }
}; };
class LoopAST : public ExprAST { class LoopAST : public ExprAST {};
class LoopForeverAST : public LoopAST {
private: private:
std::string loopVar; std::vector<std::shared_ptr<ExprAST>> body;
public:
explicit LoopForeverAST(std::vector<std::shared_ptr<ExprAST>> body) : body(std::move(body)) {}
std::shared_ptr<Value> eval(Context* parent) override final;
inline ASTType getType() const override final {
return T_LoopForeverAST;
}
};
class LoopForAST : public LoopAST {
private:
std::string name;
std::shared_ptr<ExprAST> start; std::shared_ptr<ExprAST> start;
std::shared_ptr<ExprAST> end; std::shared_ptr<ExprAST> end;
std::vector<std::shared_ptr<ExprAST>> body; std::vector<std::shared_ptr<ExprAST>> body;
public: public:
LoopAST(std::string loopVar, std::shared_ptr<ExprAST> start, std::shared_ptr<ExprAST> end, std::vector<std::shared_ptr<ExprAST>> body) : loopVar(std::move(loopVar)), start(std::move(start)), end(std::move(end)), body(std::move(body)) {} LoopForAST(std::string name, std::shared_ptr<ExprAST> start, std::shared_ptr<ExprAST> end, std::vector<std::shared_ptr<ExprAST>> body) : name(std::move(name)), start(std::move(start)), end(std::move(end)), body(std::move(body)) {}
std::shared_ptr<Value> eval(Context* parent) override final; std::shared_ptr<Value> eval(Context* parent) override final;
inline ASTType getType() const override final { inline ASTType getType() const override final {
return T_LoopAST; return T_LoopForAST;
}
};
class LoopDoTimesAST : public LoopAST {
private:
std::string name;
std::shared_ptr<ExprAST> times;
std::vector<std::shared_ptr<ExprAST>> body;
public:
LoopDoTimesAST(std::string name, std::shared_ptr<ExprAST> times, std::vector<std::shared_ptr<ExprAST>> body) : name(std::move(name)), times(std::move(times)), body(std::move(body)) {}
std::shared_ptr<Value> eval(Context* parent) override final;
inline ASTType getType() const override final {
return T_LoopDoTimesAST;
} }
}; };
@ -230,12 +265,19 @@ public:
class ReturnAST : public ExprAST { class ReturnAST : public ExprAST {
private: private:
std::shared_ptr<ExprAST> expr; std::shared_ptr<ExprAST> expr;
std::string name;
public: public:
explicit ReturnAST(std::shared_ptr<ExprAST> expr) : expr(std::move(expr)) {} explicit ReturnAST(std::shared_ptr<ExprAST> expr) : expr(std::move(expr)), name() {}
ReturnAST(std::shared_ptr<ExprAST> expr, std::string name) : expr(std::move(expr)), name(std::move(name)) {}
std::shared_ptr<Value> eval(Context* parent) override final; std::shared_ptr<Value> eval(Context* parent) override final;
std::string getName() const {
return name;
}
inline ASTType getType() const override final { inline ASTType getType() const override final {
return T_ReturnAST; return T_ReturnAST;
} }

View File

@ -60,6 +60,7 @@ aref [aA][rR][eE][fF]
t [tT] t [tT]
nil [nN][iI][lL] nil [nN][iI][lL]
return [rR][eE][tT][uU][rR][nN] return [rR][eE][tT][uU][rR][nN]
returnfrom [rR][eE][tT][uU][rR][nN][-][fF][rR][oO][mM]
makearray [mM][aA][kK][eE][-][aA][rR][rR][aA][yY] makearray [mM][aA][kK][eE][-][aA][rR][rR][aA][yY]
defconstant [dD][eE][fF][cC][oO][nN][sS][tT][aA][nN][tT] defconstant [dD][eE][fF][cC][oO][nN][sS][tT][aA][nN][tT]
@ -333,6 +334,11 @@ defconstant [dD][eE][fF][cC][oO][nN][sS][tT][aA][nN][tT]
return token::TOKEN_RETURN; return token::TOKEN_RETURN;
}; };
{returnfrom} {
std::printf("Scanned returnfrom\n");
return token::TOKEN_RETURN_FROM;
};
{makearray} { {makearray} {
std::printf("Scanned makearray\n"); std::printf("Scanned makearray\n");
return token::TOKEN_MAKE_ARRAY; return token::TOKEN_MAKE_ARRAY;

View File

@ -88,6 +88,7 @@ namespace DragonLisp {
T "t" T "t"
NIL "nil" NIL "nil"
RETURN "return" RETURN "return"
RETURN_FROM "return-from"
MAKE_ARRAY "make-array" MAKE_ARRAY "make-array"
DEFCONSTANT "defconstant" DEFCONSTANT "defconstant"
; ;
@ -159,6 +160,7 @@ array-ref
return-expr return-expr
: LPAREN RETURN R-Value RPAREN { std::printf("Parsed return-expr -> ( RETURN R-Value )\n"); $$ = drv.constructReturnAST($3); } : LPAREN RETURN R-Value RPAREN { std::printf("Parsed return-expr -> ( RETURN R-Value )\n"); $$ = drv.constructReturnAST($3); }
| LPAREN RETURN_FROM IDENTIFIER R-Value RPAREN { std::printf("Parsed return-expr -> ( RETURN_FROM IDENTIFIER R-Value )\n"); $$ = drv.constructReturnAST($4, $3); }
; ;
func-body-expr func-body-expr

View File

@ -98,26 +98,26 @@ std::shared_ptr<ReturnAST> DLDriver::constructReturnAST(std::shared_ptr<ExprAST>
return std::make_shared<ReturnAST>(std::move(value)); return std::make_shared<ReturnAST>(std::move(value));
} }
std::shared_ptr <ReturnAST> DLDriver::constructReturnAST(std::shared_ptr <ExprAST> value, std::string name) {
return std::make_shared<ReturnAST>(std::move(value), std::move(name));
}
std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::vector<std::shared_ptr<ExprAST>> body) { std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::vector<std::shared_ptr<ExprAST>> body) {
return std::make_shared<LoopAST>( return std::make_shared<LoopForeverAST>(
"",
std::make_shared<LiteralAST>(true),
std::make_shared<LiteralAST>(true),
std::move(body) std::move(body)
); );
} }
std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::string id, std::shared_ptr<ExprAST> to, std::vector<std::shared_ptr<ExprAST>> body) { std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::string id, std::shared_ptr<ExprAST> to, std::vector<std::shared_ptr<ExprAST>> body) {
return std::make_shared<LoopAST>( return std::make_shared<LoopDoTimesAST>(
std::move(id), std::move(id),
std::make_shared<LiteralAST>(std::int64_t(0)),
std::move(to), std::move(to),
std::move(body) std::move(body)
); );
} }
std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::string id, std::shared_ptr<ExprAST> from, std::shared_ptr<ExprAST> to, std::vector<std::shared_ptr<ExprAST>> body) { std::shared_ptr<LoopAST> DLDriver::constructLoopAST(std::string id, std::shared_ptr<ExprAST> from, std::shared_ptr<ExprAST> to, std::vector<std::shared_ptr<ExprAST>> body) {
return std::make_shared<LoopAST>( return std::make_shared<LoopForAST>(
std::move(id), std::move(id),
std::move(from), std::move(from),
std::move(to), std::move(to),

View File

@ -68,6 +68,7 @@ public:
// Return AST // Return AST
static std::shared_ptr<ReturnAST> constructReturnAST(std::shared_ptr<ExprAST> value); static std::shared_ptr<ReturnAST> constructReturnAST(std::shared_ptr<ExprAST> value);
static std::shared_ptr<ReturnAST> constructReturnAST(std::shared_ptr<ExprAST> value, std::string name);
// Loop AST // Loop AST
static std::shared_ptr<LoopAST> constructLoopAST(std::vector<std::shared_ptr<ExprAST>> body); static std::shared_ptr<LoopAST> constructLoopAST(std::vector<std::shared_ptr<ExprAST>> body);

View File

@ -32,7 +32,11 @@
) )
) )
(fibonacci 15) ; returns 987 ; Time complexity very very very high!!!
; This is a recursive function.
; O(2^n) time complexity.
; Since this interpreter is not well optimized, it will take a long time to run this function.
(print (fibonacci 8)) ; returns 34
; This is a comment. ; This is a comment.
; This is another comment. ; This is another comment.
@ -48,7 +52,7 @@
) ; prints 1 2 3 4 5 6 7 8 9 10 ) ; prints 1 2 3 4 5 6 7 8 9 10
(defvar i 1) (defvar i 1)
(loop (if (> i 5) (return i)) (incf i 3)) ; returns 7 (print (loop (if (> i 5) (return i)) (incf i 3))) ; returns 7
(dotimes (i 10) (print i)) ; prints 0 1 2 3 4 5 6 7 8 9 (dotimes (i 10) (print i)) ; prints 0 1 2 3 4 5 6 7 8 9
@ -58,3 +62,19 @@
(DoTiMeS (i (+ 99999 -99989)) (print i) (setf (aref arr i) (* i i i))) ; prints 0 1 2 3 4 5 6 7 8 9 (DoTiMeS (i (+ 99999 -99989)) (print i) (setf (aref arr i) (* i i i))) ; prints 0 1 2 3 4 5 6 7 8 9
(dOtImEs (i 10) (print (aref arr i))) ; prints 0 1 8 27 64 125 216 343 512 729 (dOtImEs (i 10) (print (aref arr i))) ; prints 0 1 8 27 64 125 216 343 512 729
(defvar dp (make-array 90))
(loop for i from 0 to 89 do (setf (aref dp i) -1))
(defun fibFast (n)
(if (>= n 90) (return-from fibFast "I can't handle this number!"))
(if (>= (aref dp n) 0) (return-from fibFast (aref dp n)))
(if (<= n 1) (return-from fibFast 1))
(setf (aref dp n) (+ (fibFast (- n 1)) (fibFast (- n 2))))
)
; This is a dynamic programming function,
; still recursive, but with a memoization table.
; O(n) time complexity.
(print (fibFast 8)) ; prints 34
(print (fibFast 80)) ; prints 37889062373143906

View File

@ -50,6 +50,8 @@ enum Token {
DOLIST, DOLIST,
DO, DO,
AREF, AREF,
RETURN,
RETURN_FROM,
MAKE_ARRAY, MAKE_ARRAY,
DEFCONSTANT, DEFCONSTANT,
}; };

56
value.h
View File

@ -106,6 +106,62 @@ public:
bool operator==(const SingleValue& rhs) const { bool operator==(const SingleValue& rhs) const {
return type == rhs.type && value == rhs.value; return type == rhs.type && value == rhs.value;
} }
bool operator<(const SingleValue& rhs) const {
if ((!this->isInt() && !this->isFloat()) || (!rhs.isInt() && !rhs.isFloat()))
throw std::runtime_error("Cannot compare non-numeric values");
if (this->isInt() && rhs.isInt())
return this->getInt() < rhs.getInt();
if (this->isInt())
return this->getInt() < rhs.getFloat();
if (rhs.isInt())
return this->getFloat() < rhs.getInt();
return this->getFloat() < rhs.getFloat();
}
bool operator<=(const SingleValue& rhs) const {
if ((!this->isInt() && !this->isFloat()) || (!rhs.isInt() && !rhs.isFloat()))
throw std::runtime_error("Cannot compare non-numeric values");
if (this->isInt() && rhs.isInt())
return this->getInt() <= rhs.getInt();
if (this->isInt())
return this->getInt() <= rhs.getFloat();
if (rhs.isInt())
return this->getFloat() <= rhs.getInt();
return this->getFloat() <= rhs.getFloat();
}
SingleValue& operator++() {
if (this->isInt())
this->value = this->getInt() + 1;
else if (this->isFloat())
this->value = this->getFloat() + 1;
else
throw std::runtime_error("Cannot increment non-numeric value");
return *this;
}
SingleValue& operator--() {
if (this->isInt())
this->value = this->getInt() - 1;
else if (this->isFloat())
this->value = this->getFloat() - 1;
else
throw std::runtime_error("Cannot decrement non-numeric value");
return *this;
}
SingleValue operator++(int) {
SingleValue tmp(*this);
operator++();
return tmp;
}
SingleValue operator--(int) {
SingleValue tmp(*this);
operator--();
return tmp;
}
}; };
class ArrayValue : public Value { class ArrayValue : public Value {