From da94105307fb799977a12d9a52149c4a622a589b Mon Sep 17 00:00:00 2001 From: Brandon Rozek Date: Tue, 12 Jun 2018 19:06:17 -0400 Subject: [PATCH] Implemented and/or --- lval/conditionals.c | 43 ++++++++++++++++++++++++++++++++++++++++++- lval/conditionals.h | 3 +++ lval/environment.c | 7 +++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/lval/conditionals.c b/lval/conditionals.c index 8333d9f..1dab6bd 100644 --- a/lval/conditionals.c +++ b/lval/conditionals.c @@ -1,6 +1,7 @@ #include "conditionals.h" #include "numbers.h" #include "operations.h" +#include "expressions.h" #include "error.h" lval* builtin_gt(lenv* e, lval* a) { @@ -97,6 +98,17 @@ lval* builtin_cmp(lenv* e, lval* a, char* op) { if (strcmp(op, "!=") == 0) { r = !lval_eq(a->cell[0], a->cell[1]); } + if (strcmp(op, "or") == 0) { + LASSERT_TYPE("or", a, 0, LVAL_LONG) + LASSERT_TYPE("or", a, 1, LVAL_LONG) + r = (a->cell[0]->data.num || a->cell[1]->data.num); + } + if (strcmp(op, "and") == 0) { + LASSERT_TYPE("and", a, 0, LVAL_LONG) + LASSERT_TYPE("and", a, 1, LVAL_LONG) + r = (a->cell[0]->data.num && a->cell[1]->data.num); + } + lval_del(a); return lval_long(r); } @@ -107,4 +119,33 @@ lval* builtin_eq(lenv* e, lval* a) { lval* builtin_ne(lenv* e, lval* a) { return builtin_cmp(e, a, "!="); -} \ No newline at end of file +} +lval* builtin_or(lenv* e, lval* a) { + return builtin_cmp(e, a, "or"); +} + +lval* builtin_and(lenv* e, lval* a) { + return builtin_cmp(e, a, "and"); +} + +lval* builtin_if(lenv* e, lval* a) { + LASSERT_NUM("if", a, 3) + LASSERT_TYPE("if", a, 0, LVAL_LONG) + LASSERT_TYPE("if", a, 1, LVAL_QEXPR) + LASSERT_TYPE("if", a, 2, LVAL_QEXPR) + + // Mark both expressions as evaluable + lval* x; + a->cell[1]->type = LVAL_SEXPR; + a->cell[2]->type = LVAL_SEXPR; + + if (a->cell[0]->data.num) { + x = lval_eval(e, lval_pop(a, 1)); + } else { + x = lval_eval(e, lval_pop(a, 2)); + } + + // Delete the argument list and return + lval_del(a); + return x; +} diff --git a/lval/conditionals.h b/lval/conditionals.h index 2db2046..b49ba16 100644 --- a/lval/conditionals.h +++ b/lval/conditionals.h @@ -15,5 +15,8 @@ lval* builtin_cmp(lenv* e, lval* a, char* op); lval* builtin_eq(lenv* e, lval* a); lval* builtin_ne(lenv* e, lval* a); +lval* builtin_if(lenv* e, lval* a); +lval* builtin_and(lenv* e, lval* a); +lval* builtin_or(lenv* e, lval* a); #endif diff --git a/lval/environment.c b/lval/environment.c index 04c5eba..0691a7f 100644 --- a/lval/environment.c +++ b/lval/environment.c @@ -136,6 +136,13 @@ void lenv_add_builtins(lenv* e) { lenv_add_builtin(e, "==", builtin_eq); lenv_add_builtin(e, "!=", builtin_ne); + lenv_add_builtin(e, "if", builtin_if); + + lenv_add_builtin(e, "and", builtin_and); + lenv_add_builtin(e, "&&", builtin_and); + lenv_add_builtin(e, "or", builtin_or); + lenv_add_builtin(e, "||", builtin_or); + } lval* builtin_ls(lenv* e, lval* a) {