diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 9e91edcec1..35c71e7c51 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -1,11 +1,15 @@ -#include "MAL.h" -#include "Environment.h" -#include "StaticList.h" -#include "Types.h" +#include "Core.h" +#include "Reader.h" +#include "ReadLine.h" +#include "String.h" +#include "Validation.h" + +#include #include #include #include +#include #define CHECK_ARGS_IS(expected) \ checkArgsIs(name.c_str(), expected, \ @@ -19,19 +23,26 @@ checkArgsAtLeast(name.c_str(), expected, \ std::distance(argsBegin, argsEnd)) -static String printValues(malValueIter begin, malValueIter end, - const String& sep, bool readably); +std::vector> handlers; +// We want to populate this list without duplication of the function +// names in the source (or source generation). +// This trick relies on static variables. +// The returned value is ignored, but void variables are forbidden. +bool addHandler(const String &name, malBuiltIn::ApplyFunc handler) +{ + handlers.push_back(new malBuiltIn(name, handler)); + return false; +} -static StaticList handlers; +#define BUILTIN_UNUSED_PARAMETER_NAME (void)name -#define ARG(type, name) type* name = VALUE_CAST(type, *argsBegin++) +#define ARG(type, var) type* var = VALUE_CAST(name, type, *argsBegin++) #define FUNCNAME(uniq) builtIn ## uniq #define HRECNAME(uniq) handler ## uniq #define BUILTIN_DEF(uniq, symbol) \ static malBuiltIn::ApplyFunc FUNCNAME(uniq); \ - static StaticList::Node HRECNAME(uniq) \ - (handlers, new malBuiltIn(symbol, FUNCNAME(uniq))); \ + static bool HRECNAME(uniq) = addHandler(symbol, FUNCNAME(uniq)); \ malValuePtr FUNCNAME(uniq)(const String& name, \ malValueIter argsBegin, malValueIter argsEnd) @@ -81,9 +92,9 @@ BUILTIN_IS("nil?", nilValue); BUILTIN("-") { - int argCount = CHECK_ARGS_BETWEEN(1, 2); + CHECK_ARGS_BETWEEN(1, 2); ARG(malInteger, lhs); - if (argCount == 1) { + if (argsBegin == argsEnd) { return mal::integer(- lhs->value()); } @@ -130,27 +141,27 @@ BUILTIN(">") BUILTIN("=") { CHECK_ARGS_IS(2); - const malValue* lhs = (*argsBegin++).ptr(); - const malValue* rhs = (*argsBegin++).ptr(); + const malValue* lhs = (*argsBegin++); + const malValue* rhs = (*argsBegin++); - return mal::boolean(lhs->isEqualTo(rhs)); + return mal::boolean(lhs->doIsEqualTo(rhs)); } BUILTIN("apply") { CHECK_ARGS_AT_LEAST(2); - malValuePtr op = *argsBegin++; // this gets checked in APPLY + ARG(malApplicable, op); // Copy the first N-1 arguments in. malValueVec args(argsBegin, argsEnd-1); // Then append the argument as a list. - const malSequence* lastArg = VALUE_CAST(malSequence, *(argsEnd-1)); + const malSequence* lastArg = VALUE_CAST(name, malSequence, *(argsEnd-1)); for (int i = 0; i < lastArg->count(); i++) { args.push_back(lastArg->item(i)); } - return APPLY(op, args.begin(), args.end()); + return op->apply(args.begin(), args.end()); } BUILTIN("assoc") @@ -170,21 +181,15 @@ BUILTIN("atom") BUILTIN("concat") { - int count = 0; + auto items = new malList(); for (auto it = argsBegin; it != argsEnd; ++it) { - const malSequence* seq = VALUE_CAST(malSequence, *it); - count += seq->count(); - } - - malValueVec* items = new malValueVec(count); - int offset = 0; - for (auto it = argsBegin; it != argsEnd; ++it) { - const malSequence* seq = STATIC_CAST(malSequence, *it); - std::copy(seq->begin(), seq->end(), items->begin() + offset); - offset += seq->count(); + const malSequence* seq = VALUE_CAST(name, malSequence, *it); + for (const auto &x : *seq) { + items->push_back(x); + } } - return mal::list(items); + return malValuePtr(items); } BUILTIN("conj") @@ -201,11 +206,13 @@ BUILTIN("cons") malValuePtr first = *argsBegin++; ARG(malSequence, rest); - malValueVec* items = new malValueVec(1 + rest->count()); - items->at(0) = first; - std::copy(rest->begin(), rest->end(), items->begin() + 1); + auto items = new malList(); + items->push_back(first); + for (const auto &x : *rest) { + items->push_back(x); + } - return mal::list(items); + return malValuePtr(items); } BUILTIN("contains?") @@ -256,7 +263,7 @@ BUILTIN("empty?") BUILTIN("eval") { CHECK_ARGS_IS(1); - return EVAL(*argsBegin, NULL); + return EVAL(*argsBegin, replEnv); } BUILTIN("first") @@ -294,7 +301,7 @@ BUILTIN("get") BUILTIN("hash-map") { - return mal::hash(argsBegin, argsEnd, true); + return mal::hash(argsBegin, argsEnd, name); } BUILTIN("keys") @@ -317,6 +324,7 @@ BUILTIN("keyword") BUILTIN("list") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::list(argsBegin, argsEnd); } @@ -332,17 +340,17 @@ BUILTIN("macro?") BUILTIN("map") { CHECK_ARGS_IS(2); - malValuePtr op = *argsBegin++; // this gets checked in APPLY + ARG(malApplicable, op); ARG(malSequence, source); const int length = source->count(); - malValueVec* items = new malValueVec(length); + auto items = new malList(); auto it = source->begin(); for (int i = 0; i < length; i++) { - items->at(i) = APPLY(op, it+i, it+i+1); + items->push_back(op->apply(it+i, it+i+1)); } - return mal::list(items); + return malValuePtr(items); } BUILTIN("meta") @@ -367,17 +375,20 @@ BUILTIN("nth") BUILTIN("pr-str") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::string(printValues(argsBegin, argsEnd, " ", true)); } BUILTIN("println") { + BUILTIN_UNUSED_PARAMETER_NAME; std::cout << printValues(argsBegin, argsEnd, " ", false) << "\n"; return mal::nilValue(); } BUILTIN("prn") { + BUILTIN_UNUSED_PARAMETER_NAME; std::cout << printValues(argsBegin, argsEnd, " ", true) << "\n"; return mal::nilValue(); } @@ -395,7 +406,11 @@ BUILTIN("readline") CHECK_ARGS_IS(1); ARG(malString, str); - return readline(str->value()); + String input; + if (s_readLine_get(str->value(), input)) { + return mal::string(input); + } + return mal::nilValue(); } BUILTIN("reset!") @@ -409,7 +424,7 @@ BUILTIN("rest") { CHECK_ARGS_IS(1); if (*argsBegin == mal::nilValue()) { - return mal::list(new malValueVec(0)); + return mal::list(); } ARG(malSequence, seq); return seq->rest(); @@ -432,11 +447,11 @@ BUILTIN("seq") if (length == 0) return mal::nilValue(); - malValueVec* items = new malValueVec(length); + auto items = new malList(); for (int i = 0; i < length; i++) { - (*items)[i] = mal::string(str.substr(i, 1)); + items->push_back(mal::string(str.substr(i, 1))); } - return mal::list(items); + return malValuePtr(items); } MAL_FAIL("%s is not a string or sequence", arg->print(true).c_str()); } @@ -463,6 +478,7 @@ BUILTIN("slurp") BUILTIN("str") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::string(printValues(argsBegin, argsEnd, "", false)); } @@ -471,13 +487,13 @@ BUILTIN("swap!") CHECK_ARGS_AT_LEAST(2); ARG(malAtom, atom); - malValuePtr op = *argsBegin++; // this gets checked in APPLY + ARG(malApplicable, op); malValueVec args(1 + argsEnd - argsBegin); args[0] = atom->deref(); std::copy(argsBegin, argsEnd, args.begin() + 1); - malValuePtr value = APPLY(op, args.begin(), args.end()); + malValuePtr value = op->apply(args.begin(), args.end()); return atom->reset(value); } @@ -522,6 +538,7 @@ BUILTIN("vec") BUILTIN("vector") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::vector(argsBegin, argsEnd); } @@ -530,30 +547,12 @@ BUILTIN("with-meta") CHECK_ARGS_IS(2); malValuePtr obj = *argsBegin++; malValuePtr meta = *argsBegin++; - return obj->withMeta(meta); + return obj->doWithMeta(meta); } -void installCore(malEnvPtr env) { +void installCore() { for (auto it = handlers.begin(), end = handlers.end(); it != end; ++it) { malBuiltIn* handler = *it; - env->set(handler->name(), handler); + replEnv->set(handler->name(), handler); } } - -static String printValues(malValueIter begin, malValueIter end, - const String& sep, bool readably) -{ - String out; - - if (begin != end) { - out += (*begin)->print(readably); - ++begin; - } - - for ( ; begin != end; ++begin) { - out += sep; - out += (*begin)->print(readably); - } - - return out; -} diff --git a/impls/cpp/Core.h b/impls/cpp/Core.h new file mode 100644 index 0000000000..cffb7c26e6 --- /dev/null +++ b/impls/cpp/Core.h @@ -0,0 +1,9 @@ +#pragma once + +#include "Environment.h" +#include "Types.h" + +void installCore(); + +extern const malEnvPtr replEnv; // step*.cpp +extern malValuePtr EVAL(malValuePtr, malEnvPtr); // step*.cpp diff --git a/impls/cpp/Debug.h b/impls/cpp/Debug.h index c2ee75c78c..5ff647b8cb 100644 --- a/impls/cpp/Debug.h +++ b/impls/cpp/Debug.h @@ -1,35 +1,11 @@ -#ifndef INCLUDE_DEBUG_H -#define INCLUDE_DEBUG_H +#pragma once #include #include -#define DEBUG_TRACE 1 -//#define DEBUG_OBJECT_LIFETIMES 1 -//#define DEBUG_ENV_LIFETIMES 1 - #define DEBUG_TRACE_FILE stderr -#define NOOP do { } while (false) -#define NOTRACE(...) NOOP - -#if DEBUG_TRACE - #define TRACE(...) fprintf(DEBUG_TRACE_FILE, __VA_ARGS__) -#else - #define TRACE NOTRACE -#endif - -#if DEBUG_OBJECT_LIFETIMES - #define TRACE_OBJECT TRACE -#else - #define TRACE_OBJECT NOTRACE -#endif - -#if DEBUG_ENV_LIFETIMES - #define TRACE_ENV TRACE -#else - #define TRACE_ENV NOTRACE -#endif +#define TRACE(...) fprintf(DEBUG_TRACE_FILE, __VA_ARGS__) #define _ASSERT(file, line, condition, ...) \ if (!(condition)) { \ @@ -41,5 +17,3 @@ #define ASSERT(condition, ...) \ _ASSERT(__FILE__, __LINE__, condition, __VA_ARGS__) - -#endif // INCLUDE_DEBUG_H diff --git a/impls/cpp/Dockerfile b/impls/cpp/Dockerfile index 8c0e3f7931..4ed5932899 100644 --- a/impls/cpp/Dockerfile +++ b/impls/cpp/Dockerfile @@ -20,4 +20,4 @@ WORKDIR /mal ########################################################## # Install g++ for any C/C++ based implementations -RUN apt-get -y install g++ libreadline-dev +RUN apt-get -y install g++ libreadline-dev libgc-dev diff --git a/impls/cpp/Environment.cpp b/impls/cpp/Environment.cpp index 1ae8f3e562..affc7a5f1f 100644 --- a/impls/cpp/Environment.cpp +++ b/impls/cpp/Environment.cpp @@ -1,19 +1,16 @@ +#include "Debug.h" #include "Environment.h" -#include "Types.h" - -#include +#include "Validation.h" malEnv::malEnv(malEnvPtr outer) : m_outer(outer) { - TRACE_ENV("Creating malEnv %p, outer=%p\n", this, m_outer.ptr()); } malEnv::malEnv(malEnvPtr outer, const StringVec& bindings, malValueIter argsBegin, malValueIter argsEnd) -: m_outer(outer) +: malEnv(outer) { - TRACE_ENV("Creating malEnv %p, outer=%p\n", this, m_outer.ptr()); int n = bindings.size(); auto it = argsBegin; for (int i = 0; i < n; i++) { @@ -30,30 +27,15 @@ malEnv::malEnv(malEnvPtr outer, const StringVec& bindings, MAL_CHECK(it == argsEnd, "Too many parameters"); } -malEnv::~malEnv() -{ - TRACE_ENV("Destroying malEnv %p, outer=%p\n", this, m_outer.ptr()); -} - -malEnvPtr malEnv::find(const String& symbol) +malValuePtr malEnv::get(const String& symbol) const { - for (malEnvPtr env = this; env; env = env->m_outer) { - if (env->m_map.find(symbol) != env->m_map.end()) { - return env; - } - } - return NULL; -} - -malValuePtr malEnv::get(const String& symbol) -{ - for (malEnvPtr env = this; env; env = env->m_outer) { + for (auto env = this; env; env = env->m_outer) { auto it = env->m_map.find(symbol); if (it != env->m_map.end()) { return it->second; } } - MAL_FAIL("'%s' not found", symbol.c_str()); + return NULL; } malValuePtr malEnv::set(const String& symbol, malValuePtr value) @@ -61,13 +43,3 @@ malValuePtr malEnv::set(const String& symbol, malValuePtr value) m_map[symbol] = value; return value; } - -malEnvPtr malEnv::getRoot() -{ - // Work our way down the the global environment. - for (malEnvPtr env = this; ; env = env->m_outer) { - if (!env->m_outer) { - return env; - } - } -} diff --git a/impls/cpp/Environment.h b/impls/cpp/Environment.h index 9753a22ead..1c915395aa 100644 --- a/impls/cpp/Environment.h +++ b/impls/cpp/Environment.h @@ -1,11 +1,14 @@ -#ifndef INCLUDE_ENVIRONMENT_H -#define INCLUDE_ENVIRONMENT_H +#pragma once -#include "MAL.h" +#include "String.h" +#include "Types.h" -#include +#include +#include -class malEnv : public RefCounted { +#include + +class malEnv : public gc { public: malEnv(malEnvPtr outer = NULL); malEnv(malEnvPtr outer, @@ -13,17 +16,17 @@ class malEnv : public RefCounted { malValueIter argsBegin, malValueIter argsEnd); - ~malEnv(); + malValuePtr get(const String& symbol) const; + // NULL means not found - malValuePtr get(const String& symbol); - malEnvPtr find(const String& symbol); malValuePtr set(const String& symbol, malValuePtr value); - malEnvPtr getRoot(); private: - typedef std::map Map; + typedef std::unordered_map, std::equal_to, + gc_allocator>> + Map; Map m_map; - malEnvPtr m_outer; + const malEnvPtr m_outer; }; - -#endif // INCLUDE_ENVIRONMENT_H diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h deleted file mode 100644 index c82b50cc09..0000000000 --- a/impls/cpp/MAL.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef INCLUDE_MAL_H -#define INCLUDE_MAL_H - -#include "Debug.h" -#include "RefCountedPtr.h" -#include "String.h" -#include "Validation.h" - -#include - -class malValue; -typedef RefCountedPtr malValuePtr; -typedef std::vector malValueVec; -typedef malValueVec::iterator malValueIter; - -class malEnv; -typedef RefCountedPtr malEnvPtr; - -// step*.cpp -extern malValuePtr APPLY(malValuePtr op, - malValueIter argsBegin, malValueIter argsEnd); -extern malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -extern malValuePtr readline(const String& prompt); -extern String rep(const String& input, malEnvPtr env); - -// Core.cpp -extern void installCore(malEnvPtr env); - -// Reader.cpp -extern malValuePtr readStr(const String& input); - -#endif // INCLUDE_MAL_H diff --git a/impls/cpp/Makefile b/impls/cpp/Makefile index 1c81812297..13664b0ed3 100644 --- a/impls/cpp/Makefile +++ b/impls/cpp/Makefile @@ -1,4 +1,21 @@ -uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +step0 := step0_repl +step1 := step1_read_print +step2 := step2_eval +step3 := step3_env +step4 := step4_if_fn_do +step5 := step5_tco +step6 := step6_file +step7 := step7_quote +step8 := step8_macros +step9 := step9_try +stepA := stepA_mal + +step0A = $(step0) $(step1A) +step1A = $(step1) $(step2) $(step3A) +step3A = $(step3) $(step4A) +step4A = $(step4) $(step5) $(step6) $(step7) $(step8) $(step9) $(stepA) + +uname_S != uname -s 2>/dev/null CXX=g++ ifeq ($(uname_S),Darwin) @@ -8,25 +25,20 @@ ifeq ($(uname_S),Darwin) LIBPATHS=-L$(READLINE)/lib endif -LD=$(CXX) -AR=ar +LINK.o = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) DEBUG=-ggdb -CXXFLAGS=-O3 -Wall $(DEBUG) $(INCPATHS) -std=c++11 -LDFLAGS=-O3 $(DEBUG) $(LIBPATHS) -L. -lreadline -lhistory +OPT = -O3 +WARN = -Wall -Wextra +STDCXX = -std=c++11 -LIBSOURCES=Core.cpp Environment.cpp Reader.cpp ReadLine.cpp String.cpp \ - Types.cpp Validation.cpp -LIBOBJS=$(LIBSOURCES:%.cpp=%.o) +CPPFLAGS += $(INCPATHS) +CXXFLAGS += $(OPT) $(WARN) $(DEBUG) $(STDCXX) +LDLIBS += $(LIBPATHS) -lreadline -lhistory -lgccpp -lgc -MAINS=$(wildcard step*.cpp) -TARGETS=$(MAINS:%.cpp=%) +.PHONY: all clean dist -.PHONY: all clean - -.SUFFIXES: .cpp .o - -all: $(TARGETS) +all: $(step0A) dist: mal @@ -34,18 +46,14 @@ mal: stepA_mal cp $< $@ .deps: *.cpp *.h - $(CXX) $(CXXFLAGS) -MM *.cpp > .deps - -$(TARGETS): %: %.o libmal.a - $(LD) $^ -o $@ $(LDFLAGS) - -libmal.a: $(LIBOBJS) - $(AR) rcs $@ $^ + $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM *.cpp > .deps -.cpp.o: - $(CXX) $(CXXFLAGS) -c $< -o $@ +$(step0A): ReadLine.o String.o +$(step1A): Reader.o Types.o Validation.o +$(step3A): Environment.o +$(step4A): Core.o clean: - rm -rf *.o $(TARGETS) libmal.a .deps mal + rm -f *.o $(step0A) .deps mal -include .deps diff --git a/impls/cpp/README.md b/impls/cpp/README.md index 5d0ddd37d7..0946ed1800 100644 --- a/impls/cpp/README.md +++ b/impls/cpp/README.md @@ -15,7 +15,7 @@ You may need to edit the READLINE path in the Makefile. This should compile on Ubuntu 14.10 and 15.04 with the following packages - apt-get install clang-3.5 libreadline-dev make + apt-get install clang-3.5 libreadline-dev libgc-dev make ## Docker @@ -38,3 +38,16 @@ can be used to make and run this implementation. ./docker run +#About garbage collection. + +Destructors were once used to trace deallocations, but in order to +call them we need to inherit from gc_cleanup instead of gc. The +collection then fails because it cannot guess in which order it must +invoke the destructor in cycles. + +The heap does not seem to grow forever when the following program runs +with GC_PRINT_STATS=1 in the environment. +for (int i = 0; i < 10000; i++) { + rep("(let* [f (fn* [] nil)] nil)", replEnv); + GC_gcollect(); +} diff --git a/impls/cpp/ReadLine.cpp b/impls/cpp/ReadLine.cpp index f4b76609b2..b883233896 100644 --- a/impls/cpp/ReadLine.cpp +++ b/impls/cpp/ReadLine.cpp @@ -1,32 +1,69 @@ +#include "Debug.h" #include "ReadLine.h" -#include "String.h" - -#include -#include -#include #include #include #include -ReadLine::ReadLine(const String& historyFile) -: m_historyPath(copyAndFree(tilde_expand(historyFile.c_str()))) +// make CPPFLAGS=-DDEBUG_READLINE + +char* historyPath = NULL; +int newLines = 0; + +void finalize() { - read_history(m_historyPath.c_str()); + int err = append_history(newLines, historyPath); + if (err == 0) { +#if DEBUG_READLINE + TRACE("Written %d line(s) to '%s'\n", newLines, historyPath); +#endif + } + else { + TRACE("Error %d while appending to '%s'\n", err, historyPath); + } + free(historyPath); } -ReadLine::~ReadLine() +void initialize() { + atexit(finalize); + + historyPath = tilde_expand("~/.mal-history"); + + int e1 = read_history(historyPath); + if (e1 == 0) { +#if DEBUG_READLINE + TRACE("Read '%s'\n", historyPath); +#endif + } + else if (e1 == ENOENT) { + int e2 = write_history(historyPath); + if (e2 == 0) { +#if DEBUG_READLINE + TRACE("Created '%s'\n", historyPath); +#endif + } + else { + TRACE("Error %d while creating '%s'\n", e2, historyPath); + } + } + else { + TRACE("Error %d while reading '%s'\n", e1, historyPath); + } } -bool ReadLine::get(const String& prompt, String& out) +bool s_readLine_get(const String& prompt, String& out) { + if (historyPath == NULL) { + initialize(); + } + char *line = readline(prompt.c_str()); if (line == NULL) { return false; } add_history(line); // Add input to in-memory history - append_history(1, m_historyPath.c_str()); + ++newLines; out = line; free(line); diff --git a/impls/cpp/ReadLine.h b/impls/cpp/ReadLine.h index 94327aad97..748f581281 100644 --- a/impls/cpp/ReadLine.h +++ b/impls/cpp/ReadLine.h @@ -1,17 +1,5 @@ -#ifndef INCLUDE_READLINE_H -#define INCLUDE_READLINE_H +#pragma once #include "String.h" -class ReadLine { -public: - ReadLine(const String& historyFile); - ~ReadLine(); - - bool get(const String& prompt, String& line); - -private: - String m_historyPath; -}; - -#endif // INCLUDE_READLINE_H +bool s_readLine_get(const String& prompt, String& line); diff --git a/impls/cpp/Reader.cpp b/impls/cpp/Reader.cpp index dbcb6c9c83..804d18194a 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -1,7 +1,9 @@ -#include "MAL.h" -#include "Types.h" +#include "Debug.h" +#include "Reader.h" +#include "Validation.h" #include +#include typedef std::regex Regex; @@ -114,16 +116,15 @@ void Tokeniser::skipWhitespace() static malValuePtr readAtom(Tokeniser& tokeniser); static malValuePtr readForm(Tokeniser& tokeniser); -static void readList(Tokeniser& tokeniser, malValueVec* items, +static void readList(Tokeniser& tokeniser, + std::function process, const String& end); static malValuePtr processMacro(Tokeniser& tokeniser, const String& symbol); malValuePtr readStr(const String& input) { Tokeniser tokeniser(input); - if (tokeniser.eof()) { - throw malEmptyInputException(); - } + MAL_CHECK(!tokeniser.eof(), "no MAL form in \"%s\"", input.c_str()); return readForm(tokeniser); } @@ -137,21 +138,24 @@ static malValuePtr readForm(Tokeniser& tokeniser) if (token == "(") { tokeniser.next(); - std::unique_ptr items(new malValueVec); - readList(tokeniser, items.get(), ")"); - return mal::list(items.release()); + auto items = new malList(); + readList(tokeniser, + [items] (malValuePtr x) { items->push_back(x); }, ")"); + return malValuePtr(items); } if (token == "[") { tokeniser.next(); - std::unique_ptr items(new malValueVec); - readList(tokeniser, items.get(), "]"); - return mal::vector(items.release()); + auto items = new malVector(); + readList(tokeniser, + [items] (malValuePtr x) { items->push_back(x); }, "]"); + return malValuePtr(items); } if (token == "{") { tokeniser.next(); malValueVec items; - readList(tokeniser, &items, "}"); - return mal::hash(items.begin(), items.end(), false); + readList(tokeniser, + [&items] (malValuePtr x) { items.push_back(x); }, "}"); + return mal::hash(items.begin(), items.end(), "{ } map literal"); } return readAtom(tokeniser); } @@ -162,7 +166,7 @@ static malValuePtr readAtom(Tokeniser& tokeniser) const char* token; const char* symbol; }; - ReaderMacro macroTable[] = { + const static ReaderMacro macroTable[] = { { "@", "deref" }, { "`", "quasiquote" }, { "'", "quote" }, @@ -174,7 +178,7 @@ static malValuePtr readAtom(Tokeniser& tokeniser) const char* token; malValuePtr value; }; - Constant constantTable[] = { + const static Constant constantTable[] = { { "false", mal::falseValue() }, { "nil", mal::nilValue() }, { "true", mal::trueValue() }, @@ -209,7 +213,8 @@ static malValuePtr readAtom(Tokeniser& tokeniser) return mal::symbol(token); } -static void readList(Tokeniser& tokeniser, malValueVec* items, +static void readList(Tokeniser& tokeniser, + std::function process, const String& end) { while (1) { @@ -218,7 +223,7 @@ static void readList(Tokeniser& tokeniser, malValueVec* items, tokeniser.next(); return; } - items->push_back(readForm(tokeniser)); + process(readForm(tokeniser)); } } diff --git a/impls/cpp/Reader.h b/impls/cpp/Reader.h new file mode 100644 index 0000000000..ee47f9ff15 --- /dev/null +++ b/impls/cpp/Reader.h @@ -0,0 +1,6 @@ +#pragma once + +#include "String.h" +#include "Types.h" + +malValuePtr readStr(const String& input); diff --git a/impls/cpp/RefCountedPtr.h b/impls/cpp/RefCountedPtr.h deleted file mode 100644 index 04cb952dc1..0000000000 --- a/impls/cpp/RefCountedPtr.h +++ /dev/null @@ -1,77 +0,0 @@ -#ifndef INCLUDE_REFCOUNTEDPTR_H -#define INCLUDE_REFCOUNTEDPTR_H - -#include "Debug.h" - -#include - -class RefCounted { -public: - RefCounted() : m_refCount(0) { } - virtual ~RefCounted() { } - - const RefCounted* acquire() const { m_refCount++; return this; } - int release() const { return --m_refCount; } - int refCount() const { return m_refCount; } - -private: - RefCounted(const RefCounted&); // no copy ctor - RefCounted& operator = (const RefCounted&); // no assignments - - mutable int m_refCount; -}; - -template -class RefCountedPtr { -public: - RefCountedPtr() : m_object(0) { } - - RefCountedPtr(T* object) : m_object(0) - { acquire(object); } - - RefCountedPtr(const RefCountedPtr& rhs) : m_object(0) - { acquire(rhs.m_object); } - - const RefCountedPtr& operator = (const RefCountedPtr& rhs) { - acquire(rhs.m_object); - return *this; - } - - bool operator == (const RefCountedPtr& rhs) const { - return m_object == rhs.m_object; - } - - bool operator != (const RefCountedPtr& rhs) const { - return m_object != rhs.m_object; - } - - operator bool () const { - return m_object != NULL; - } - - ~RefCountedPtr() { - release(); - } - - T* operator -> () const { return m_object; } - T* ptr() const { return m_object; } - -private: - void acquire(T* object) { - if (object != NULL) { - object->acquire(); - } - release(); - m_object = object; - } - - void release() { - if ((m_object != NULL) && (m_object->release() == 0)) { - delete m_object; - } - } - - T* m_object; -}; - -#endif // INCLUDE_REFCOUNTEDPTR_H diff --git a/impls/cpp/StaticList.h b/impls/cpp/StaticList.h deleted file mode 100644 index a02a51c3a8..0000000000 --- a/impls/cpp/StaticList.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef INCLUDE_STATICLIST_H -#define INCLUDE_STATICLIST_H - -template -class StaticList -{ -public: - StaticList() : m_head(NULL) { } - - class Iterator; - Iterator begin() { return Iterator(m_head); } - Iterator end() { return Iterator(NULL); } - - class Node { - public: - Node(StaticList& list, T item) - : m_item(item), m_next(list.m_head) { - list.m_head = this; - } - - private: - friend class Iterator; - T m_item; - Node* m_next; - }; - - class Iterator { - public: - Iterator& operator ++ () { - m_node = m_node->m_next; - return *this; - } - - T& operator * () { return m_node->m_item; } - bool operator != (const Iterator& that) { - return m_node != that.m_node; - } - - private: - friend class StaticList; - Iterator(Node* node) : m_node(node) { } - Node* m_node; - }; - -private: - friend class Node; - Node* m_head; -}; - -#endif // INCLUDE_STATICLIST_H diff --git a/impls/cpp/String.cpp b/impls/cpp/String.cpp index dcdce2b0c1..2c972919ef 100644 --- a/impls/cpp/String.cpp +++ b/impls/cpp/String.cpp @@ -1,9 +1,6 @@ -#include "Debug.h" #include "String.h" #include -#include -#include #include // Adapted from: http://stackoverflow.com/questions/2342162 @@ -28,13 +25,6 @@ String stringPrintf(const char* fmt, ...) { return str; } -String copyAndFree(char* mallocedString) -{ - String ret(mallocedString); - free(mallocedString); - return ret; -} - String escape(const String& in) { String out; @@ -85,4 +75,3 @@ String unescape(const String& in) out.shrink_to_fit(); return out; } - diff --git a/impls/cpp/String.h b/impls/cpp/String.h index bbedf9b33d..679d806d50 100644 --- a/impls/cpp/String.h +++ b/impls/cpp/String.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_STRING_H -#define INCLUDE_STRING_H +#pragma once #include #include @@ -11,8 +10,5 @@ typedef std::vector StringVec; #define PLURAL(n) &("s"[(n)==1]) extern String stringPrintf(const char* fmt, ...); -extern String copyAndFree(char* mallocedString); extern String escape(const String& s); extern String unescape(const String& s); - -#endif // INCLUDE_STRING_H diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index daf47cf748..14bf21e9cd 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -1,10 +1,26 @@ #include "Debug.h" -#include "Environment.h" #include "Types.h" - -#include -#include -#include +#include "Validation.h" + +template +T* value_cast(const String& context, malValuePtr obj, const char* typeName) +{ + T* dest = dynamic_cast(obj); + MAL_CHECK(dest != NULL, "%s: %s is not a %s", context.c_str(), + obj->print(true).c_str(), typeName); + return dest; +} +#define INSTANTIATE_VALUE_CAST(T) \ + template T* value_cast(const String&, malValuePtr, const char*) +INSTANTIATE_VALUE_CAST(malApplicable); +INSTANTIATE_VALUE_CAST(malAtom); +INSTANTIATE_VALUE_CAST(malHash); +INSTANTIATE_VALUE_CAST(malInteger); +INSTANTIATE_VALUE_CAST(malLambda); +INSTANTIATE_VALUE_CAST(malList); +INSTANTIATE_VALUE_CAST(malSequence); +INSTANTIATE_VALUE_CAST(malString); +INSTANTIATE_VALUE_CAST(malSymbol); namespace mal { malValuePtr atom(malValuePtr value) { @@ -24,14 +40,9 @@ namespace mal { return malValuePtr(c); }; - - malValuePtr hash(const malHash::Map& map) { - return malValuePtr(new malHash(map)); - } - malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, - bool isEvaluated) { - return malValuePtr(new malHash(argsBegin, argsEnd, isEvaluated)); + const String& context) { + return malValuePtr(new malHash(argsBegin, argsEnd, context)); } malValuePtr integer(int64_t value) { @@ -46,42 +57,38 @@ namespace mal { return malValuePtr(new malKeyword(token)); }; - malValuePtr lambda(const StringVec& bindings, + malValuePtr lambda(malLambda::ApplyFunc apply, + const StringVec& bindings, malValuePtr body, malEnvPtr env) { - return malValuePtr(new malLambda(bindings, body, env)); + return malValuePtr(new malLambda(apply, bindings, body, env)); } - malValuePtr list(malValueVec* items) { - return malValuePtr(new malList(items)); - }; - malValuePtr list(malValueIter begin, malValueIter end) { return malValuePtr(new malList(begin, end)); }; - malValuePtr list(malValuePtr a) { - malValueVec* items = new malValueVec(1); - items->at(0) = a; - return malValuePtr(new malList(items)); + malValuePtr list() { + static malValuePtr c = malValuePtr(new malList()); + return malValuePtr(c); } malValuePtr list(malValuePtr a, malValuePtr b) { - malValueVec* items = new malValueVec(2); - items->at(0) = a; - items->at(1) = b; - return malValuePtr(new malList(items)); + auto items = new malList(); + items->push_back(a); + items->push_back(b); + return malValuePtr(items); } malValuePtr list(malValuePtr a, malValuePtr b, malValuePtr c) { - malValueVec* items = new malValueVec(3); - items->at(0) = a; - items->at(1) = b; - items->at(2) = c; - return malValuePtr(new malList(items)); + auto items = new malList(); + items->push_back(a); + items->push_back(b); + items->push_back(c); + return malValuePtr(items); } malValuePtr macro(const malLambda& lambda) { - return malValuePtr(new malLambda(lambda, true)); + return lambda.asMacro(); }; malValuePtr nilValue() { @@ -102,63 +109,82 @@ namespace mal { return malValuePtr(c); }; - malValuePtr vector(malValueVec* items) { - return malValuePtr(new malVector(items)); - }; - malValuePtr vector(malValueIter begin, malValueIter end) { return malValuePtr(new malVector(begin, end)); }; }; +malAtom::malAtom(malValuePtr value) : m_value(value) { } +malValuePtr malAtom::deref() const { return m_value; } +malValuePtr malAtom::reset(malValuePtr value) { return m_value = value; } +String malAtom::print(bool readably) const +{ + return STRF("(atom %s)", m_value->print(readably).c_str()); +} + +malBuiltIn::malBuiltIn(const String&name, ApplyFunc* apply, malValuePtr meta) + : malApplicable(meta), m_name(name), m_handler(apply) { } + malValuePtr malBuiltIn::apply(malValueIter argsBegin, malValueIter argsEnd) const { return m_handler(m_name, argsBegin, argsEnd); } -static String makeHashKey(malValuePtr key) +malValuePtr malBuiltIn::doWithMeta(malValuePtr meta) const +{ + return malValuePtr(new malBuiltIn(m_name, m_handler, meta)); +} +String malBuiltIn::name() const { return m_name; } +String malBuiltIn::print(bool) const +{ + return STRF("#builtin-function(%s)", m_name.c_str()); +} + +malConstant::malConstant(String name) : m_name(name) { } +bool malConstant::doIsEqualTo(const malValue* rhs) const +{ + return this == rhs; // these are singletons +} +String malConstant::print(bool) const { return m_name; } + +bool malHash::malKeyEqual::operator()(const malValuePtr& lhs, + const malValuePtr& rhs) const +{ + return lhs->doIsEqualTo(rhs); +} + +size_t malHash::malKeyHash::operator()(const malValuePtr& key) const { if (const malString* skey = DYNAMIC_CAST(malString, key)) { - return skey->print(true); + return std::hash{}(skey->print(true)); } else if (const malKeyword* kkey = DYNAMIC_CAST(malKeyword, key)) { - return kkey->print(true); + return std::hash{}(kkey->print(true)); } MAL_FAIL("%s is not a string or keyword", key->print(true).c_str()); } -static malHash::Map addToMap(malHash::Map& map, - malValueIter argsBegin, malValueIter argsEnd) +void malHash::addToMap(malValueIter argsBegin, malValueIter argsEnd, + const String& context) { // This is intended to be called with pre-evaluated arguments. + checkArgsEven(context.c_str(), std::distance(argsBegin, argsEnd)); for (auto it = argsBegin; it != argsEnd; ++it) { - String key = makeHashKey(*it++); - map[key] = *it; + auto key = *it++; + m_map[key] = *it; } - - return map; } -static malHash::Map createMap(malValueIter argsBegin, malValueIter argsEnd) +malHash::malHash() { } +malHash::malHash(malValueIter argsBegin, malValueIter argsEnd, + const String& context) { - MAL_CHECK(std::distance(argsBegin, argsEnd) % 2 == 0, - "hash-map requires an even-sized list"); - - malHash::Map map; - return addToMap(map, argsBegin, argsEnd); + addToMap(argsBegin, argsEnd, context); } - -malHash::malHash(malValueIter argsBegin, malValueIter argsEnd, bool isEvaluated) -: m_map(createMap(argsBegin, argsEnd)) -, m_isEvaluated(isEvaluated) -{ - -} - -malHash::malHash(const malHash::Map& map) -: m_map(map) -, m_isEvaluated(true) +malHash::malHash(const Map &map, malValuePtr meta) +: malValue(meta) +, m_map(map) { } @@ -166,72 +192,64 @@ malHash::malHash(const malHash::Map& map) malValuePtr malHash::assoc(malValueIter argsBegin, malValueIter argsEnd) const { - MAL_CHECK(std::distance(argsBegin, argsEnd) % 2 == 0, - "assoc requires an even-sized list"); - - malHash::Map map(m_map); - return mal::hash(addToMap(map, argsBegin, argsEnd)); + auto map = new malHash(m_map); + map->addToMap(argsBegin, argsEnd, "assoc"); + return malValuePtr(map); } bool malHash::contains(malValuePtr key) const { - auto it = m_map.find(makeHashKey(key)); + auto it = m_map.find(key); return it != m_map.end(); } malValuePtr malHash::dissoc(malValueIter argsBegin, malValueIter argsEnd) const { - malHash::Map map(m_map); + auto map = new malHash(m_map); for (auto it = argsBegin; it != argsEnd; ++it) { - String key = makeHashKey(*it); - map.erase(key); + auto key = *it; + map->m_map.erase(key); } - return mal::hash(map); + return malValuePtr(map); } -malValuePtr malHash::eval(malEnvPtr env) +malValuePtr malHash::doWithMeta(malValuePtr meta) const { - if (m_isEvaluated) { - return malValuePtr(this); - } + return malValuePtr(new malHash(m_map, meta)); +} - malHash::Map map; +malValuePtr malHash::fmap(std::function f) const +{ + auto map = new malHash(); for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { - map[it->first] = EVAL(it->second, env); + map->m_map[it->first] = f(it->second); } - return mal::hash(map); + return malValuePtr(map); } malValuePtr malHash::get(malValuePtr key) const { - auto it = m_map.find(makeHashKey(key)); + auto it = m_map.find(key); return it == m_map.end() ? mal::nilValue() : it->second; } malValuePtr malHash::keys() const { - malValueVec* keys = new malValueVec(); - keys->reserve(m_map.size()); + auto keys = new malList(); for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { - if (it->first[0] == '"') { - keys->push_back(mal::string(unescape(it->first))); - } - else { - keys->push_back(mal::keyword(it->first)); - } + keys->push_back(it->first); } - return mal::list(keys); + return malValuePtr(keys); } malValuePtr malHash::values() const { - malValueVec* keys = new malValueVec(); - keys->reserve(m_map.size()); + auto keys = new malList(); for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { keys->push_back(it->second); } - return mal::list(keys); + return malValuePtr(keys); } String malHash::print(bool readably) const @@ -240,11 +258,12 @@ String malHash::print(bool readably) const auto it = m_map.begin(), end = m_map.end(); if (it != end) { - s += it->first + " " + it->second->print(readably); + s += it->first->print(readably) + " " + it->second->print(readably); ++it; } for ( ; it != end; ++it) { - s += " " + it->first + " " + it->second->print(readably); + s += " " + it->first->print(readably) + + " " + it->second->print(readably); } return s + "}"; @@ -252,7 +271,11 @@ String malHash::print(bool readably) const bool malHash::doIsEqualTo(const malValue* rhs) const { - const malHash::Map& r_map = static_cast(rhs)->m_map; + auto r = dynamic_cast(rhs); + if (!r) { + return false; + } + const malHash::Map& r_map = r->m_map; if (m_map.size() != r_map.size()) { return false; } @@ -260,41 +283,45 @@ bool malHash::doIsEqualTo(const malValue* rhs) const for (auto it0 = m_map.begin(), end0 = m_map.end(), it1 = r_map.begin(); it0 != end0; ++it0, ++it1) { - if (it0->first != it1->first) { + if (!it0->first->doIsEqualTo(it1->first)) { return false; } - if (!it0->second->isEqualTo(it1->second.ptr())) { + if (!it0->second->doIsEqualTo(it1->second)) { return false; } } return true; } -malLambda::malLambda(const StringVec& bindings, - malValuePtr body, malEnvPtr env) -: m_bindings(bindings) -, m_body(body) -, m_env(env) -, m_isMacro(false) +malInteger::malInteger(int64_t value) : m_value(value) { } +bool malInteger::doIsEqualTo(const malValue* rhs) const { - + auto r = dynamic_cast(rhs); + return r && (m_value == r->m_value); } +String malInteger::print(bool) const { return std::to_string(m_value); } +int64_t malInteger::value() const { return m_value; } -malLambda::malLambda(const malLambda& that, malValuePtr meta) -: malApplicable(meta) -, m_bindings(that.m_bindings) -, m_body(that.m_body) -, m_env(that.m_env) -, m_isMacro(that.m_isMacro) -{ +malStringBase::malStringBase(const String& token) : m_value(token) { } +String malStringBase::print(bool) const { return m_value; } +String malStringBase::value() const { return m_value; } +malKeyword::malKeyword(const String& token) : malStringBase(token) { } +bool malKeyword::doIsEqualTo(const malValue* rhs) const +{ + auto r = dynamic_cast(rhs); + return r && (value() == r->value()); } -malLambda::malLambda(const malLambda& that, bool isMacro) -: malApplicable(that.m_meta) -, m_bindings(that.m_bindings) -, m_body(that.m_body) -, m_env(that.m_env) +malLambda::malLambda(ApplyFunc apply, + const StringVec& bindings, + malValuePtr body, malEnvPtr env, + bool isMacro, malValuePtr meta) +: malApplicable(meta) +, m_apply(apply) +, m_bindings(bindings) +, m_body(body) +, m_env(env) , m_isMacro(isMacro) { @@ -303,155 +330,142 @@ malLambda::malLambda(const malLambda& that, bool isMacro) malValuePtr malLambda::apply(malValueIter argsBegin, malValueIter argsEnd) const { - return EVAL(m_body, makeEnv(argsBegin, argsEnd)); + return m_apply(argsBegin, argsEnd); +} + +StringVec malLambda::getBindings() const { return m_bindings; } + +malValuePtr malLambda::asMacro() const +{ + return malValuePtr(new malLambda(m_apply, m_bindings, m_body, m_env, + true)); } malValuePtr malLambda::doWithMeta(malValuePtr meta) const { - return new malLambda(*this, meta); + return malValuePtr(new malLambda(m_apply, m_bindings, m_body, m_env, + m_isMacro, meta)); } -malEnvPtr malLambda::makeEnv(malValueIter argsBegin, malValueIter argsEnd) const +malEnvPtr malLambda::getEnv() const { return m_env; } +malValuePtr malLambda::getBody() const { return m_body; } +bool malLambda::isMacro() const { return m_isMacro; } +String malLambda::print(bool) const { - return malEnvPtr(new malEnv(m_env, m_bindings, argsBegin, argsEnd)); + return STRF("#user-%s(%p)", m_isMacro ? "macro" : "function", this); } +malList::malList() { } +malList::malList(malValueIter begin, malValueIter end, malValuePtr meta) +: malSequence(begin, end, meta) { } malValuePtr malList::conj(malValueIter argsBegin, malValueIter argsEnd) const { - int oldItemCount = std::distance(begin(), end()); - int newItemCount = std::distance(argsBegin, argsEnd); - - malValueVec* items = new malValueVec(oldItemCount + newItemCount); - std::reverse_copy(argsBegin, argsEnd, items->begin()); - std::copy(begin(), end(), items->begin() + newItemCount); + auto items = new malList(); + while (argsEnd-- != argsBegin) { + items->push_back(*argsEnd); + } + for (auto const &x : *this) { + items->push_back(x); + } - return mal::list(items); + return malValuePtr(items); } - -malValuePtr malList::eval(malEnvPtr env) +malValuePtr malList::doWithMeta(malValuePtr meta) const { - // Note, this isn't actually called since the TCO updates, but - // is required for the earlier steps, so don't get rid of it. - if (count() == 0) { - return malValuePtr(this); - } - - std::unique_ptr items(evalItems(env)); - auto it = items->begin(); - malValuePtr op = *it; - return APPLY(op, ++it, items->end()); + return malValuePtr(new malList(begin(), end(), meta)); } String malList::print(bool readably) const { - return '(' + malSequence::print(readably) + ')'; + return '(' + printValues(begin(), end(), " ", readably) + ')'; } -malValuePtr malValue::eval(malEnvPtr env) +malValue::malValue(malValuePtr meta) +: m_meta(meta) { - // Default case of eval is just to return the object itself. - return malValuePtr(this); } -bool malValue::isEqualTo(const malValue* rhs) const +bool malValue::doIsEqualTo(const malValue*) const { return false; } +malValuePtr malValue::doWithMeta(malValuePtr) const { - // Special-case. Vectors and Lists can be compared. - bool matchingTypes = (typeid(*this) == typeid(*rhs)) || - (dynamic_cast(this) && - dynamic_cast(rhs)); - - return matchingTypes && doIsEqualTo(rhs); + MAL_FAIL("cannot add metadata to %s", print(true).c_str()); } bool malValue::isTrue() const { - return (this != mal::falseValue().ptr()) - && (this != mal::nilValue().ptr()); + return (this != mal::falseValue()) + && (this != mal::nilValue()); } malValuePtr malValue::meta() const { - return m_meta.ptr() == NULL ? mal::nilValue() : m_meta; -} - -malValuePtr malValue::withMeta(malValuePtr meta) const -{ - return doWithMeta(meta); -} - -malSequence::malSequence(malValueVec* items) -: m_items(items) -{ - + return m_meta == NULL ? mal::nilValue() : m_meta; } -malSequence::malSequence(malValueIter begin, malValueIter end) -: m_items(new malValueVec(begin, end)) +malSequence::malSequence() { } - -malSequence::malSequence(const malSequence& that, malValuePtr meta) +malSequence::malSequence(malValueIter begin, malValueIter end, + malValuePtr meta) : malValue(meta) -, m_items(new malValueVec(*(that.m_items))) +, m_items(begin, end) { } - -malSequence::~malSequence() -{ - delete m_items; -} +malValueIter malSequence::begin() const { return m_items.begin(); } +int malSequence::count() const { return m_items.size(); } bool malSequence::doIsEqualTo(const malValue* rhs) const { - const malSequence* rhsSeq = static_cast(rhs); + const malSequence* rhsSeq = dynamic_cast(rhs); + if (!rhsSeq) { + return false; + } if (count() != rhsSeq->count()) { return false; } - for (malValueIter it0 = m_items->begin(), + for (malValueIter it0 = m_items.begin(), it1 = rhsSeq->begin(), - end = m_items->end(); it0 != end; ++it0, ++it1) { + end = m_items.end(); it0 != end; ++it0, ++it1) { - if (! (*it0)->isEqualTo((*it1).ptr())) { + if (!(*it0)->doIsEqualTo((*it1))) { return false; } } return true; } - -malValueVec* malSequence::evalItems(malEnvPtr env) const -{ - malValueVec* items = new malValueVec;; - items->reserve(count()); - for (auto it = m_items->begin(), end = m_items->end(); it != end; ++it) { - items->push_back(EVAL(*it, env)); - } - return items; -} +malValueIter malSequence::end() const { return m_items.end(); } malValuePtr malSequence::first() const { return count() == 0 ? mal::nilValue() : item(0); } -String malSequence::print(bool readably) const +String printValues(malValueIter begin, malValueIter end, + const String& sep, bool readably) { String str; - auto end = m_items->cend(); - auto it = m_items->cbegin(); + auto it = begin; if (it != end) { str += (*it)->print(readably); ++it; } + for ( ; it != end; ++it) { - str += " "; + str += sep; str += (*it)->print(readably); } + return str; } +bool malSequence::isEmpty() const { return m_items.empty(); } +malValuePtr malSequence::item(int index) const { return m_items.at(index); } +void malSequence::push_back(malValuePtr newItem) { + m_items.push_back(newItem); +} malValuePtr malSequence::rest() const { @@ -459,40 +473,53 @@ malValuePtr malSequence::rest() const return mal::list(start, end()); } -String malString::escapedValue() const +malString::malString(const String& token) : malStringBase(token) { } +bool malString::doIsEqualTo(const malValue* rhs) const { - return escape(value()); + auto r = dynamic_cast(rhs); + return r && (value() == r->value()); } String malString::print(bool readably) const { - return readably ? escapedValue() : value(); + return readably ? escape(value()) : value(); } -malValuePtr malSymbol::eval(malEnvPtr env) +malSymbol::malSymbol(const String& token) : malStringBase(token) { } +bool malSymbol::doIsEqualTo(const malValue* rhs) const { - return env->get(value()); + auto r = dynamic_cast(rhs); + return r && (value() == r->value()); } +malVector::malVector() { } +malVector::malVector(malValueIter begin, malValueIter end, malValuePtr meta) + : malSequence(begin, end, meta) { } malValuePtr malVector::conj(malValueIter argsBegin, malValueIter argsEnd) const { - int oldItemCount = std::distance(begin(), end()); - int newItemCount = std::distance(argsBegin, argsEnd); - - malValueVec* items = new malValueVec(oldItemCount + newItemCount); - std::copy(begin(), end(), items->begin()); - std::copy(argsBegin, argsEnd, items->begin() + oldItemCount); + auto items = new malVector(begin(), end()); + for ( ; argsBegin != argsEnd; ++argsBegin) { + items->push_back(*argsBegin); + } + return malValuePtr(items); +} - return mal::vector(items); +malValuePtr malVector::fmap(std::function f) const +{ + auto items = new malVector(); + for (const auto &x : *this) { + items->push_back(f(x)); + } + return malValuePtr(items); } -malValuePtr malVector::eval(malEnvPtr env) +malValuePtr malVector::doWithMeta(malValuePtr meta) const { - return mal::vector(evalItems(env)); + return new malVector(begin(), end(), meta); } String malVector::print(bool readably) const { - return '[' + malSequence::print(readably) + ']'; + return '[' + printValues(begin(), end(), " ", readably) + ']'; } diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index f92887c0fa..ce44b95b5b 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -1,261 +1,169 @@ -#ifndef INCLUDE_TYPES_H -#define INCLUDE_TYPES_H +#pragma once -#include "MAL.h" +#include "String.h" -#include -#include +#include +#include -class malEmptyInputException : public std::exception { }; +#include +#include +#include -class malValue : public RefCounted { -public: - malValue() { - TRACE_OBJECT("Creating malValue %p\n", this); - } - malValue(malValuePtr meta) : m_meta(meta) { - TRACE_OBJECT("Creating malValue %p\n", this); - } - virtual ~malValue() { - TRACE_OBJECT("Destroying malValue %p\n", this); - } +class malValue; +typedef malValue* malValuePtr; +typedef std::vector> malValueVec; +typedef malValueVec::const_iterator malValueIter; - malValuePtr withMeta(malValuePtr meta) const; - virtual malValuePtr doWithMeta(malValuePtr meta) const = 0; - malValuePtr meta() const; +class malEnv; // Environment.h +typedef malEnv* malEnvPtr; +class malValue : public gc { +public: + virtual malValuePtr doWithMeta(malValuePtr meta) const; + malValuePtr meta() const; bool isTrue() const; - - bool isEqualTo(const malValue* rhs) const; - - virtual malValuePtr eval(malEnvPtr env); - + virtual bool doIsEqualTo(const malValue* rhs) const; virtual String print(bool readably) const = 0; - protected: - virtual bool doIsEqualTo(const malValue* rhs) const = 0; - - malValuePtr m_meta; + malValue(malValuePtr meta = NULL); +private: + const malValuePtr m_meta; }; template -T* value_cast(malValuePtr obj, const char* typeName) { - T* dest = dynamic_cast(obj.ptr()); - MAL_CHECK(dest != NULL, "%s is not a %s", - obj->print(true).c_str(), typeName); - return dest; -} - -#define VALUE_CAST(Type, Value) value_cast(Value, #Type) -#define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value).ptr())) -#define STATIC_CAST(Type, Value) (static_cast((Value).ptr())) +T* value_cast(const String& context, malValuePtr obj, const char* typeName); -#define WITH_META(Type) \ - virtual malValuePtr doWithMeta(malValuePtr meta) const { \ - return new Type(*this, meta); \ - } \ +#define VALUE_CAST(context, Type, Value) value_cast(context, Value, #Type) +#define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value))) +#define STATIC_CAST(Type, Value) (static_cast((Value))) class malConstant : public malValue { public: - malConstant(String name) : m_name(name) { } - malConstant(const malConstant& that, malValuePtr meta) - : malValue(meta), m_name(that.m_name) { } - - virtual String print(bool readably) const { return m_name; } - - virtual bool doIsEqualTo(const malValue* rhs) const { - return this == rhs; // these are singletons - } - - WITH_META(malConstant); - + malConstant(String name); + String print(bool readably) const override; + bool doIsEqualTo(const malValue* rhs) const override; private: const String m_name; }; class malInteger : public malValue { public: - malInteger(int64_t value) : m_value(value) { } - malInteger(const malInteger& that, malValuePtr meta) - : malValue(meta), m_value(that.m_value) { } - - virtual String print(bool readably) const { - return std::to_string(m_value); - } - - int64_t value() const { return m_value; } - - virtual bool doIsEqualTo(const malValue* rhs) const { - return m_value == static_cast(rhs)->m_value; - } - - WITH_META(malInteger); - + malInteger(int64_t value); + String print(bool readably) const override; + int64_t value() const; + bool doIsEqualTo(const malValue* rhs) const override; private: const int64_t m_value; }; class malStringBase : public malValue { public: - malStringBase(const String& token) - : m_value(token) { } - malStringBase(const malStringBase& that, malValuePtr meta) - : malValue(meta), m_value(that.value()) { } - - virtual String print(bool readably) const { return m_value; } - - String value() const { return m_value; } - + String print(bool readably) const override; + String value() const; +protected: + malStringBase(const String& token); private: const String m_value; }; class malString : public malStringBase { public: - malString(const String& token) - : malStringBase(token) { } - malString(const malString& that, malValuePtr meta) - : malStringBase(that, meta) { } - - virtual String print(bool readably) const; - - String escapedValue() const; - - virtual bool doIsEqualTo(const malValue* rhs) const { - return value() == static_cast(rhs)->value(); - } - - WITH_META(malString); + malString(const String& token); + String print(bool readably) const override; + bool doIsEqualTo(const malValue* rhs) const override; }; class malKeyword : public malStringBase { public: - malKeyword(const String& token) - : malStringBase(token) { } - malKeyword(const malKeyword& that, malValuePtr meta) - : malStringBase(that, meta) { } - - virtual bool doIsEqualTo(const malValue* rhs) const { - return value() == static_cast(rhs)->value(); - } - - WITH_META(malKeyword); + malKeyword(const String& token); + bool doIsEqualTo(const malValue* rhs) const override; }; class malSymbol : public malStringBase { public: - malSymbol(const String& token) - : malStringBase(token) { } - malSymbol(const malSymbol& that, malValuePtr meta) - : malStringBase(that, meta) { } - - virtual malValuePtr eval(malEnvPtr env); - - virtual bool doIsEqualTo(const malValue* rhs) const { - return value() == static_cast(rhs)->value(); - } - - WITH_META(malSymbol); + malSymbol(const String& token); + bool doIsEqualTo(const malValue* rhs) const override; }; class malSequence : public malValue { public: - malSequence(malValueVec* items); - malSequence(malValueIter begin, malValueIter end); - malSequence(const malSequence& that, malValuePtr meta); - virtual ~malSequence(); - - virtual String print(bool readably) const; - - malValueVec* evalItems(malEnvPtr env) const; - int count() const { return m_items->size(); } - bool isEmpty() const { return m_items->empty(); } - malValuePtr item(int index) const { return (*m_items)[index]; } - - malValueIter begin() const { return m_items->begin(); } - malValueIter end() const { return m_items->end(); } - - virtual bool doIsEqualTo(const malValue* rhs) const; - + void push_back(malValuePtr newItem); + int count() const; + bool isEmpty() const; + malValuePtr item(int index) const; + malValueIter begin() const; + malValueIter end() const; + bool doIsEqualTo(const malValue* rhs) const override; virtual malValuePtr conj(malValueIter argsBegin, malValueIter argsEnd) const = 0; - malValuePtr first() const; - virtual malValuePtr rest() const; - + malValuePtr rest() const; +protected: + malSequence(); + malSequence(malValueIter begin, malValueIter end, malValuePtr meta = NULL); private: - malValueVec* const m_items; + malValueVec m_items; }; class malList : public malSequence { public: - malList(malValueVec* items) : malSequence(items) { } - malList(malValueIter begin, malValueIter end) - : malSequence(begin, end) { } - malList(const malList& that, malValuePtr meta) - : malSequence(that, meta) { } - - virtual String print(bool readably) const; - virtual malValuePtr eval(malEnvPtr env); - - virtual malValuePtr conj(malValueIter argsBegin, - malValueIter argsEnd) const; - - WITH_META(malList); + malList(); + malList(malValueIter begin, malValueIter end, malValuePtr meta = NULL); + String print(bool readably) const override; + malValuePtr conj(malValueIter argsBegin, + malValueIter argsEnd) const override; + malValuePtr doWithMeta(malValuePtr meta) const override; }; class malVector : public malSequence { public: - malVector(malValueVec* items) : malSequence(items) { } - malVector(malValueIter begin, malValueIter end) - : malSequence(begin, end) { } - malVector(const malVector& that, malValuePtr meta) - : malSequence(that, meta) { } - - virtual malValuePtr eval(malEnvPtr env); - virtual String print(bool readably) const; - - virtual malValuePtr conj(malValueIter argsBegin, - malValueIter argsEnd) const; - - WITH_META(malVector); + malVector(); + malVector(malValueIter begin, malValueIter end, malValuePtr meta = NULL); + malValuePtr fmap(std::function f) const; + String print(bool readably) const override; + malValuePtr conj(malValueIter argsBegin, + malValueIter argsEnd) const override; + malValuePtr doWithMeta(malValuePtr meta) const override; }; class malApplicable : public malValue { public: - malApplicable() { } - malApplicable(malValuePtr meta) : malValue(meta) { } - virtual malValuePtr apply(malValueIter argsBegin, malValueIter argsEnd) const = 0; +protected: + malApplicable() { } + malApplicable(malValuePtr meta) : malValue(meta) { } }; class malHash : public malValue { public: - typedef std::map Map; - - malHash(malValueIter argsBegin, malValueIter argsEnd, bool isEvaluated); - malHash(const malHash::Map& map); - malHash(const malHash& that, malValuePtr meta) - : malValue(meta), m_map(that.m_map), m_isEvaluated(that.m_isEvaluated) { } - + malHash(malValueIter argsBegin, malValueIter argsEnd, + const String& context); malValuePtr assoc(malValueIter argsBegin, malValueIter argsEnd) const; malValuePtr dissoc(malValueIter argsBegin, malValueIter argsEnd) const; bool contains(malValuePtr key) const; - malValuePtr eval(malEnvPtr env); + malValuePtr fmap(std::function f) const; malValuePtr get(malValuePtr key) const; malValuePtr keys() const; malValuePtr values() const; - - virtual String print(bool readably) const; - - virtual bool doIsEqualTo(const malValue* rhs) const; - - WITH_META(malHash); - + String print(bool readably) const override; + bool doIsEqualTo(const malValue* rhs) const override; + malValuePtr doWithMeta(malValuePtr meta) const override; private: - const Map m_map; - const bool m_isEvaluated; + struct malKeyHash { + size_t operator()(const malValuePtr& key) const; + }; + struct malKeyEqual { + bool operator()(const malValuePtr& lhs, const malValuePtr& rhs) const; + }; + typedef std::unordered_map>> + Map; + void addToMap(malValueIter argsBegin, malValueIter argsEnd, + const String& context); + malHash(); + malHash(const Map &map, malValuePtr meta = NULL); + Map m_map; }; class malBuiltIn : public malApplicable { @@ -263,28 +171,12 @@ class malBuiltIn : public malApplicable { typedef malValuePtr (ApplyFunc)(const String& name, malValueIter argsBegin, malValueIter argsEnd); - - malBuiltIn(const String& name, ApplyFunc* handler) - : m_name(name), m_handler(handler) { } - - malBuiltIn(const malBuiltIn& that, malValuePtr meta) - : malApplicable(meta), m_name(that.m_name), m_handler(that.m_handler) { } - - virtual malValuePtr apply(malValueIter argsBegin, - malValueIter argsEnd) const; - - virtual String print(bool readably) const { - return STRF("#builtin-function(%s)", m_name.c_str()); - } - - virtual bool doIsEqualTo(const malValue* rhs) const { - return this == rhs; // these are singletons - } - - String name() const { return m_name; } - - WITH_META(malBuiltIn); - + malBuiltIn(const String&name, ApplyFunc* handler, malValuePtr meta = NULL); + malValuePtr apply(malValueIter argsBegin, + malValueIter argsEnd) const override; + String print(bool readably) const override; + String name() const; + malValuePtr doWithMeta(malValuePtr meta) const override; private: const String m_name; ApplyFunc* m_handler; @@ -292,29 +184,24 @@ class malBuiltIn : public malApplicable { class malLambda : public malApplicable { public: - malLambda(const StringVec& bindings, malValuePtr body, malEnvPtr env); - malLambda(const malLambda& that, malValuePtr meta); - malLambda(const malLambda& that, bool isMacro); + typedef std::function ApplyFunc; + malLambda(ApplyFunc apply, const StringVec& bindings, malValuePtr body, + malEnvPtr env, bool isMacro = false, malValuePtr meta = NULL); + malValuePtr asMacro() const; - virtual malValuePtr apply(malValueIter argsBegin, - malValueIter argsEnd) const; + malValuePtr apply(malValueIter argsBegin, + malValueIter argsEnd) const override; - malValuePtr getBody() const { return m_body; } - malEnvPtr makeEnv(malValueIter argsBegin, malValueIter argsEnd) const; + StringVec getBindings() const; + malValuePtr getBody() const; + malEnvPtr getEnv() const; - virtual bool doIsEqualTo(const malValue* rhs) const { - return this == rhs; // do we need to do a deep inspection? - } - - virtual String print(bool readably) const { - return STRF("#user-%s(%p)", m_isMacro ? "macro" : "function", this); - } - - bool isMacro() const { return m_isMacro; } - - virtual malValuePtr doWithMeta(malValuePtr meta) const; + String print(bool readably) const override; + bool isMacro() const; + malValuePtr doWithMeta(malValuePtr meta) const override; private: + const ApplyFunc m_apply; const StringVec m_bindings; const malValuePtr m_body; const malEnvPtr m_env; @@ -323,23 +210,10 @@ class malLambda : public malApplicable { class malAtom : public malValue { public: - malAtom(malValuePtr value) : m_value(value) { } - malAtom(const malAtom& that, malValuePtr meta) - : malValue(meta), m_value(that.m_value) { } - - virtual bool doIsEqualTo(const malValue* rhs) const { - return this->m_value->isEqualTo(rhs); - } - - virtual String print(bool readably) const { - return "(atom " + m_value->print(readably) + ")"; - }; - - malValuePtr deref() const { return m_value; } - - malValuePtr reset(malValuePtr value) { return m_value = value; } - - WITH_META(malAtom); + malAtom(malValuePtr value); + String print(bool readably) const override; + malValuePtr deref() const; + malValuePtr reset(malValuePtr value); private: malValuePtr m_value; @@ -351,15 +225,15 @@ namespace mal { malValuePtr builtin(const String& name, malBuiltIn::ApplyFunc handler); malValuePtr falseValue(); malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, - bool isEvaluated); - malValuePtr hash(const malHash::Map& map); + const String& context); malValuePtr integer(int64_t value); malValuePtr integer(const String& token); malValuePtr keyword(const String& token); - malValuePtr lambda(const StringVec&, malValuePtr, malEnvPtr); + malValuePtr lambda(malLambda::ApplyFunc apply, const StringVec&, + malValuePtr, malEnvPtr); malValuePtr list(malValueVec* items); malValuePtr list(malValueIter begin, malValueIter end); - malValuePtr list(malValuePtr a); + malValuePtr list(); malValuePtr list(malValuePtr a, malValuePtr b); malValuePtr list(malValuePtr a, malValuePtr b, malValuePtr c); malValuePtr macro(const malLambda& lambda); @@ -367,8 +241,8 @@ namespace mal { malValuePtr string(const String& token); malValuePtr symbol(const String& token); malValuePtr trueValue(); - malValuePtr vector(malValueVec* items); malValuePtr vector(malValueIter begin, malValueIter end); }; -#endif // INCLUDE_TYPES_H +String printValues(malValueIter begin, malValueIter end, + const String& sep, bool readably); diff --git a/impls/cpp/Validation.cpp b/impls/cpp/Validation.cpp index 5b03b0f8ae..3f07923073 100644 --- a/impls/cpp/Validation.cpp +++ b/impls/cpp/Validation.cpp @@ -1,33 +1,30 @@ +#include "Types.h" #include "Validation.h" -int checkArgsIs(const char* name, int expected, int got) +void checkArgsIs(const char* name, int expected, int got) { MAL_CHECK(got == expected, "\"%s\" expects %d arg%s, %d supplied", name, expected, PLURAL(expected), got); - return got; } -int checkArgsBetween(const char* name, int min, int max, int got) +void checkArgsBetween(const char* name, int min, int max, int got) { MAL_CHECK((got >= min) && (got <= max), "\"%s\" expects between %d and %d arg%s, %d supplied", name, min, max, PLURAL(max), got); - return got; } -int checkArgsAtLeast(const char* name, int min, int got) +void checkArgsAtLeast(const char* name, int min, int got) { MAL_CHECK(got >= min, "\"%s\" expects at least %d arg%s, %d supplied", name, min, PLURAL(min), got); - return got; } -int checkArgsEven(const char* name, int got) +void checkArgsEven(const char* name, int got) { MAL_CHECK(got % 2 == 0, "\"%s\" expects an even number of args, %d supplied", name, got); - return got; } diff --git a/impls/cpp/Validation.h b/impls/cpp/Validation.h index d65e0fb64d..96cd08d6f2 100644 --- a/impls/cpp/Validation.h +++ b/impls/cpp/Validation.h @@ -1,16 +1,13 @@ -#ifndef INCLUDE_VALIDATION_H -#define INCLUDE_VALIDATION_H +#pragma once #include "String.h" #define MAL_CHECK(condition, ...) \ - if (!(condition)) { throw STRF(__VA_ARGS__); } else { } + if (condition) { } else throw mal::string(STRF(__VA_ARGS__)); #define MAL_FAIL(...) MAL_CHECK(false, __VA_ARGS__) -extern int checkArgsIs(const char* name, int expected, int got); -extern int checkArgsBetween(const char* name, int min, int max, int got); -extern int checkArgsAtLeast(const char* name, int min, int got); -extern int checkArgsEven(const char* name, int got); - -#endif // INCLUDE_VALIDATION_H +extern void checkArgsIs(const char* name, int expected, int got); +extern void checkArgsBetween(const char* name, int min, int max, int got); +extern void checkArgsAtLeast(const char* name, int min, int got); +extern void checkArgsEven(const char* name, int got); diff --git a/impls/cpp/step0_repl.cpp b/impls/cpp/step0_repl.cpp index 6b9b29c8d6..20bbca8755 100644 --- a/impls/cpp/step0_repl.cpp +++ b/impls/cpp/step0_repl.cpp @@ -2,20 +2,17 @@ #include "ReadLine.h" #include -#include String READ(const String& input); String EVAL(const String& ast); String PRINT(const String& ast); String rep(const String& input); -static ReadLine s_readLine("~/.mal-history"); - -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { std::cout << rep(input) << "\n"; } return 0; diff --git a/impls/cpp/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index 9075c45295..82abd56610 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -1,42 +1,34 @@ -#include "MAL.h" - +#include "Reader.h" #include "ReadLine.h" #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); -static ReadLine s_readLine("~/.mal-history"); - static String rep(const String& input); static malValuePtr EVAL(malValuePtr ast); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; - while (s_readLine.get(prompt, input)) { - String out; - try { - out = rep(input); - } - catch (malEmptyInputException&) { - continue; // no output - } - catch (String& s) { - out = s; - }; - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input) << "\n"; } return 0; } static String rep(const String& input) { - return PRINT(EVAL(READ(input))); + try { + return PRINT(EVAL(READ(input))); + } + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; + } } malValuePtr READ(const String& input) @@ -53,14 +45,3 @@ String PRINT(malValuePtr ast) { return ast->print(true); } - -// These have been added after step 1 to keep the linker happy. -malValuePtr EVAL(malValuePtr ast, malEnvPtr) -{ - return ast; -} - -malValuePtr APPLY(malValuePtr ast, malValueIter, malValueIter) -{ - return ast; -} diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index 9b64f5ea5c..53f65efd82 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -1,47 +1,53 @@ -#include "MAL.h" - -#include "Environment.h" +#include "Reader.h" #include "ReadLine.h" +#include "String.h" #include "Types.h" +#include "Validation.h" + +#include #include -#include +#include + +class malEnv + : public std::unordered_map, + std::equal_to, + gc_allocator>> +{ +}; malValuePtr READ(const String& input); String PRINT(malValuePtr ast); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -static ReadLine s_readLine("~/.mal-history"); static malBuiltIn::ApplyFunc builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; malEnvPtr replEnv(new malEnv); - replEnv->set("+", mal::builtin("+", &builtIn_add)); - replEnv->set("-", mal::builtin("-", &builtIn_sub)); - replEnv->set("*", mal::builtin("+", &builtIn_mul)); - replEnv->set("/", mal::builtin("/", &builtIn_div)); - while (s_readLine.get(prompt, input)) { - String out; - try { - out = rep(input, replEnv); - } - catch (malEmptyInputException&) { - continue; // no output - } - catch (String& s) { - out = s; - }; - std::cout << out << "\n"; + (*replEnv)["+"] = mal::builtin("+", &builtIn_add); + (*replEnv)["-"] = mal::builtin("-", &builtIn_sub); + (*replEnv)["*"] = mal::builtin("+", &builtIn_mul); + (*replEnv)["/"] = mal::builtin("/", &builtIn_div); + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } String rep(const String& input, malEnvPtr env) { - return PRINT(EVAL(READ(input), env)); + try { + return PRINT(EVAL(READ(input), env)); + } + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; + } } malValuePtr READ(const String& input) @@ -53,7 +59,34 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { // std::cout << "EVAL: " << PRINT(ast) << "\n"; - return ast->eval(env); + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto it = env->find(key); + MAL_CHECK(it != env->end(), "'%s' not found", key.c_str()); + auto value = it->second; + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + const malList* list = DYNAMIC_CAST(malList, ast); + if (!list || (list->count() == 0)) { + return ast; + } + + // From here on down we are evaluating a non-empty list. + + // Now we're left with the case of a regular list to be evaluated. + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + return op->apply(items.begin(), items.end()); } String PRINT(malValuePtr ast) @@ -61,16 +94,7 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - -#define ARG(type, name) type* name = VALUE_CAST(type, *argsBegin++) +#define ARG(type, var) type* var = VALUE_CAST(name, type, *argsBegin++) #define CHECK_ARGS_IS(expected) \ checkArgsIs(name.c_str(), expected, std::distance(argsBegin, argsEnd)) @@ -91,9 +115,9 @@ static malValuePtr builtIn_add(const String& name, static malValuePtr builtIn_sub(const String& name, malValueIter argsBegin, malValueIter argsEnd) { - int argCount = CHECK_ARGS_BETWEEN(1, 2); + CHECK_ARGS_BETWEEN(1, 2); ARG(malInteger, lhs); - if (argCount == 1) { + if (argsBegin == argsEnd) { return mal::integer(- lhs->value()); } ARG(malInteger, rhs); diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index fe76214a71..397580ae2f 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -1,43 +1,44 @@ -#include "MAL.h" - #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); - -static ReadLine s_readLine("~/.mal-history"); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static malEnvPtr replEnv(new malEnv); -int main(int argc, char* argv[]) +static malBuiltIn::ApplyFunc + builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; + +int main(int, char*[]) { String prompt = "user> "; String input; - installCore(replEnv); - while (s_readLine.get(prompt, input)) { - String out; - try { - out = rep(input, replEnv); - } - catch (malEmptyInputException&) { - continue; // no output - } - catch (String& s) { - out = s; - }; - std::cout << out << "\n"; + replEnv->set("+", mal::builtin("+", &builtIn_add)); + replEnv->set("-", mal::builtin("-", &builtIn_sub)); + replEnv->set("*", mal::builtin("+", &builtIn_mul)); + replEnv->set("/", mal::builtin("/", &builtIn_div)); + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } String rep(const String& input, malEnvPtr env) { - return PRINT(EVAL(READ(input), env)); + try { + return PRINT(EVAL(READ(input), env)); + } + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; + } } malValuePtr READ(const String& input) @@ -47,51 +48,64 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } - - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { - std::cout << "EVAL: " << PRINT(ast) << "\n"; - } - - const malList* list = DYNAMIC_CAST(malList, ast); - if (!list || (list->count() == 0)) { - return ast->eval(env); - } + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { + std::cout << "EVAL: " << PRINT(ast) << "\n"; + } + + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + const malList* list = DYNAMIC_CAST(malList, ast); + if (!list || (list->count() == 0)) { + return ast; + } - // From here on down we are evaluating a non-empty list. - // First handle the special forms. - if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) { - String special = symbol->value(); - int argCount = list->count() - 1; + // From here on down we are evaluating a non-empty list. + // First handle the special forms. + if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) { + String special = symbol->value(); + int argCount = list->count() - 1; - if (special == "def!") { - checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); - return env->set(id->value(), EVAL(list->item(2), env)); - } + if (special == "def!") { + checkArgsIs("def!", 2, argCount); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); + return env->set(id->value(), EVAL(list->item(2), env)); + } - if (special == "let*") { - checkArgsIs("let*", 2, argCount); - const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); - malEnvPtr inner(new malEnv(env)); - for (int i = 0; i < count; i += 2) { - const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); - inner->set(var->value(), EVAL(bindings->item(i+1), inner)); + if (special == "let*") { + checkArgsIs("let*", 2, argCount); + const malSequence* bindings = + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); + malEnvPtr inner(new malEnv(env)); + for (int i = 0; i < count; i += 2) { + const malSymbol* var = + VALUE_CAST("let*", malSymbol, bindings->item(i)); + inner->set(var->value(), EVAL(bindings->item(i+1), inner)); + } + return EVAL(list->item(2), inner); } - return EVAL(list->item(2), inner); } - } - // Now we're left with the case of a regular list to be evaluated. - std::unique_ptr items(list->evalItems(env)); - malValuePtr op = items->at(0); - return APPLY(op, items->begin()+1, items->end()); + // Now we're left with the case of a regular list to be evaluated. + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + return op->apply(items.begin(), items.end()); } String PRINT(malValuePtr ast) @@ -99,22 +113,51 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) +#define ARG(type, var) type* var = VALUE_CAST(name, type, *argsBegin++) + +#define CHECK_ARGS_IS(expected) \ + checkArgsIs(name.c_str(), expected, std::distance(argsBegin, argsEnd)) + +#define CHECK_ARGS_BETWEEN(min, max) \ + checkArgsBetween(name.c_str(), min, max, std::distance(argsBegin, argsEnd)) + + +static malValuePtr builtIn_add(const String& name, + malValueIter argsBegin, malValueIter argsEnd) { - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); + CHECK_ARGS_IS(2); + ARG(malInteger, lhs); + ARG(malInteger, rhs); + return mal::integer(lhs->value() + rhs->value()); +} - return handler->apply(argsBegin, argsEnd); +static malValuePtr builtIn_sub(const String& name, + malValueIter argsBegin, malValueIter argsEnd) +{ + CHECK_ARGS_BETWEEN(1, 2); + ARG(malInteger, lhs); + if (argsBegin == argsEnd) { + return mal::integer(- lhs->value()); + } + ARG(malInteger, rhs); + return mal::integer(lhs->value() - rhs->value()); } -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) +static malValuePtr builtIn_mul(const String& name, + malValueIter argsBegin, malValueIter argsEnd) { - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); + CHECK_ARGS_IS(2); + ARG(malInteger, lhs); + ARG(malInteger, rhs); + return mal::integer(lhs->value() * rhs->value()); } +static malValuePtr builtIn_div(const String& name, + malValueIter argsBegin, malValueIter argsEnd) +{ + CHECK_ARGS_IS(2); + ARG(malInteger, lhs); + ARG(malInteger, rhs); + MAL_CHECK(rhs->value() != 0, "Division by zero"); \ + return mal::integer(lhs->value() / rhs->value()); +} diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index cef3c4ed99..4360ed875a 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -1,45 +1,41 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); - while (s_readLine.get(prompt, input)) { - String out; - try { - out = rep(input, replEnv); - } - catch (malEmptyInputException&) { - continue; // no output - } - catch (String& s) { - out = s; - }; - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } String rep(const String& input, malEnvPtr env) { - return PRINT(EVAL(READ(input), env)); + try { + return PRINT(EVAL(READ(input), env)); + } + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; + } } malValuePtr READ(const String& input) @@ -49,91 +45,102 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } - - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { - std::cout << "EVAL: " << PRINT(ast) << "\n"; - } - - const malList* list = DYNAMIC_CAST(malList, ast); - if (!list || (list->count() == 0)) { - return ast->eval(env); - } - - // From here on down we are evaluating a non-empty list. - // First handle the special forms. - if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) { - String special = symbol->value(); - int argCount = list->count() - 1; - - if (special == "def!") { - checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); - return env->set(id->value(), EVAL(list->item(2), env)); + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { + std::cout << "EVAL: " << PRINT(ast) << "\n"; + } + + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + const malList* list = DYNAMIC_CAST(malList, ast); + if (!list || (list->count() == 0)) { + return ast; } - if (special == "do") { - checkArgsAtLeast("do", 1, argCount); + // From here on down we are evaluating a non-empty list. + // First handle the special forms. + if (const malSymbol* symbol = DYNAMIC_CAST(malSymbol, list->item(0))) { + String special = symbol->value(); + int argCount = list->count() - 1; - for (int i = 1; i < argCount; i++) { - EVAL(list->item(i), env); + if (special == "def!") { + checkArgsIs("def!", 2, argCount); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); + return env->set(id->value(), EVAL(list->item(2), env)); } - return EVAL(list->item(argCount), env); - } - if (special == "fn*") { - checkArgsIs("fn*", 2, argCount); + if (special == "do") { + checkArgsAtLeast("do", 1, argCount); - const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - StringVec params; - for (int i = 0; i < bindings->count(); i++) { - const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); - params.push_back(sym->value()); + for (int i = 1; i < argCount; i++) { + EVAL(list->item(i), env); + } + return EVAL(list->item(argCount), env); } - return mal::lambda(params, list->item(2), env); - } + if (special == "fn*") { + checkArgsIs("fn*", 2, argCount); + + const malSequence* bindings = + VALUE_CAST("fn*", malSequence, list->item(1)); + StringVec params; + for (int i = 0; i < bindings->count(); i++) { + const malSymbol* sym = + VALUE_CAST("fn*", malSymbol, bindings->item(i)); + params.push_back(sym->value()); + } + + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); + } - if (special == "if") { - checkArgsBetween("if", 2, 3, argCount); + if (special == "if") { + checkArgsBetween("if", 2, 3, argCount); - bool isTrue = EVAL(list->item(1), env)->isTrue(); - if (!isTrue && (argCount == 2)) { - return mal::nilValue(); + bool isTrue = EVAL(list->item(1), env)->isTrue(); + if (!isTrue && (argCount == 2)) { + return mal::nilValue(); + } + return EVAL(list->item(isTrue ? 2 : 3), env); } - return EVAL(list->item(isTrue ? 2 : 3), env); - } - if (special == "let*") { - checkArgsIs("let*", 2, argCount); - const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); - malEnvPtr inner(new malEnv(env)); - for (int i = 0; i < count; i += 2) { - const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); - inner->set(var->value(), EVAL(bindings->item(i+1), inner)); + if (special == "let*") { + checkArgsIs("let*", 2, argCount); + const malSequence* bindings = + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); + malEnvPtr inner(new malEnv(env)); + for (int i = 0; i < count; i += 2) { + const malSymbol* var = + VALUE_CAST("let*", malSymbol, bindings->item(i)); + inner->set(var->value(), EVAL(bindings->item(i+1), inner)); + } + return EVAL(list->item(2), inner); } - return EVAL(list->item(2), inner); } - } - // Now we're left with the case of a regular list to be evaluated. - std::unique_ptr items(list->evalItems(env)); - malValuePtr op = items->at(0); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { - return EVAL(lambda->getBody(), - lambda->makeEnv(items->begin()+1, items->end())); - } - else { - return APPLY(op, items->begin()+1, items->end()); - } + // Now we're left with the case of a regular list to be evaluated. + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + return op->apply(items.begin(), items.end()); } String PRINT(malValuePtr ast) @@ -141,15 +148,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static const char* malFunctionTable[] = { "(def! not (fn* (cond) (if cond false true)))", }; @@ -159,14 +157,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 0766d53f02..b92472ecae 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -1,45 +1,41 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); - while (s_readLine.get(prompt, input)) { - String out; - try { - out = rep(input, replEnv); - } - catch (malEmptyInputException&) { - continue; // no output - } - catch (String& s) { - out = s; - }; - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } String rep(const String& input, malEnvPtr env) { - return PRINT(EVAL(READ(input), env)); + try { + return PRINT(EVAL(READ(input), env)); + } + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; + } } malValuePtr READ(const String& input) @@ -49,19 +45,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -72,7 +77,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } @@ -90,15 +95,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -115,12 +124,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -130,16 +140,20 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - std::unique_ptr items(list->evalItems(env)); - malValuePtr op = items->at(0); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items->begin()+1, items->end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -148,15 +162,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static const char* malFunctionTable[] = { "(def! not (fn* (cond) (if cond false true)))", }; @@ -166,14 +171,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index e0c15e6109..7b504a679e 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -1,68 +1,58 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); - -static ReadLine s_readLine("~/.mal-history"); -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); makeArgv(replEnv, argc - 2, argv + 2); if (argc > 1) { String filename = escape(argv[1]); - safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); + rep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { - String out = safeRep(input, replEnv); - if (out.length() > 0) - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } -static String safeRep(const String& input, malEnvPtr env) +String rep(const String& input, malEnvPtr env) { try { - return rep(input, env); + return PRINT(EVAL(READ(input), env)); } - catch (malEmptyInputException&) { - return String(); + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; } - catch (String& s) { - return s; - }; } static void makeArgv(malEnvPtr env, int argc, char* argv[]) { - malValueVec* args = new malValueVec(); + auto args = new malList(); for (int i = 0; i < argc; i++) { args->push_back(mal::string(argv[i])); } - env->set("*ARGV*", mal::list(args)); -} - -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -72,19 +62,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -95,7 +94,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } @@ -113,15 +112,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -138,12 +141,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -153,16 +157,20 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - std::unique_ptr items(list->evalItems(env)); - malValuePtr op = items->at(0); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items->begin()+1, items->end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -171,15 +179,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static const char* malFunctionTable[] = { "(def! not (fn* (cond) (if cond false true)))", "(def! load-file (fn* (filename) \ @@ -191,14 +190,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index 1ced69952a..0c267c1a28 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -1,69 +1,59 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); makeArgv(replEnv, argc - 2, argv + 2); if (argc > 1) { String filename = escape(argv[1]); - safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); + rep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { - String out = safeRep(input, replEnv); - if (out.length() > 0) - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } -static String safeRep(const String& input, malEnvPtr env) +String rep(const String& input, malEnvPtr env) { try { - return rep(input, env); + return PRINT(EVAL(READ(input), env)); } - catch (malEmptyInputException&) { - return String(); + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; } - catch (String& s) { - return s; - }; } static void makeArgv(malEnvPtr env, int argc, char* argv[]) { - malValueVec* args = new malValueVec(); + auto args = new malList(); for (int i = 0; i < argc; i++) { args->push_back(mal::string(argv[i])); } - env->set("*ARGV*", mal::list(args)); -} - -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -73,19 +63,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -96,7 +95,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } @@ -114,15 +113,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -139,12 +142,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -165,16 +169,20 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - std::unique_ptr items(list->evalItems(env)); - malValuePtr op = items->at(0); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items->begin()+1, items->end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -183,15 +191,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static bool isSymbol(malValuePtr obj, const String& text) { const malSymbol* sym = DYNAMIC_CAST(malSymbol, obj); @@ -221,7 +220,7 @@ static malValuePtr quasiquote(malValuePtr obj) if (unquoted) return unquoted; - malValuePtr res = mal::list(new malValueVec(0)); + malValuePtr res = mal::list(); for (int i=seq->count()-1; 0<=i; i--) { const malValuePtr elt = seq->item(i); const malValuePtr spl_unq = starts_with(elt, "splice-unquote"); @@ -246,14 +245,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index b8897adbd1..cd19d2fc91 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -1,70 +1,61 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); // Installs functions and macros implemented in MAL. +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); + static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); makeArgv(replEnv, argc - 2, argv + 2); if (argc > 1) { String filename = escape(argv[1]); - safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); + rep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { - String out = safeRep(input, replEnv); - if (out.length() > 0) - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } -static String safeRep(const String& input, malEnvPtr env) +String rep(const String& input, malEnvPtr env) { try { - return rep(input, env); + return PRINT(EVAL(READ(input), env)); } - catch (malEmptyInputException&) { - return String(); + catch (malValuePtr& mv) { + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; } - catch (String& s) { - return s; - }; } static void makeArgv(malEnvPtr env, int argc, char* argv[]) { - malValueVec* args = new malValueVec(); + auto args = new malList(); for (int i = 0; i < argc; i++) { args->push_back(mal::string(argv[i])); } - env->set("*ARGV*", mal::list(args)); -} - -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -74,19 +65,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -97,16 +97,16 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } if (special == "defmacro!") { checkArgsIs("defmacro!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("defmacro!", malSymbol, list->item(1)); malValuePtr body = EVAL(list->item(2), env); - const malLambda* lambda = VALUE_CAST(malLambda, body); + const malLambda* lambda = VALUE_CAST("defmacro!", malLambda, body); return env->set(id->value(), mal::macro(*lambda)); } @@ -124,15 +124,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -149,12 +153,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -175,21 +180,24 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - malValuePtr op = EVAL(list->item(0), env); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { - if (lambda->isMacro()) { - ast = lambda->apply(list->begin()+1, list->end()); - continue; // TCO - } - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - ast = lambda->getBody(); - env = lambda->makeEnv(items->begin(), items->end()); + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + if (lambda && lambda->isMacro()) { + ast = lambda->apply(list->begin()+1, list->end()); continue; // TCO } - else { - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - return APPLY(op, items->begin(), items->end()); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); + } + if (lambda) { + ast = lambda->getBody(); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); + continue; // TCO } + return op->apply(items.begin(), items.end()); } } @@ -198,15 +206,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static bool isSymbol(malValuePtr obj, const String& text) { const malSymbol* sym = DYNAMIC_CAST(malSymbol, obj); @@ -236,7 +235,7 @@ static malValuePtr quasiquote(malValuePtr obj) if (unquoted) return unquoted; - malValuePtr res = mal::list(new malValueVec(0)); + malValuePtr res = mal::list(); for (int i=seq->count()-1; 0<=i; i--) { const malValuePtr elt = seq->item(i); const malValuePtr spl_unq = starts_with(elt, "splice-unquote"); @@ -262,14 +261,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index c04ede8300..ee9f86e541 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -1,73 +1,60 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); // Installs functions and macros implemented in MAL. +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); makeArgv(replEnv, argc - 2, argv + 2); if (argc > 1) { String filename = escape(argv[1]); - safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); + rep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { - String out = safeRep(input, replEnv); - if (out.length() > 0) - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } -static String safeRep(const String& input, malEnvPtr env) +String rep(const String& input, malEnvPtr env) { try { - return rep(input, env); - } - catch (malEmptyInputException&) { - return String(); + return PRINT(EVAL(READ(input), env)); } catch (malValuePtr& mv) { - return "Error: " + mv->print(true); + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; } - catch (String& s) { - return "Error: " + s; - }; } static void makeArgv(malEnvPtr env, int argc, char* argv[]) { - malValueVec* args = new malValueVec(); + auto args = new malList(); for (int i = 0; i < argc; i++) { args->push_back(mal::string(argv[i])); } - env->set("*ARGV*", mal::list(args)); -} - -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -77,19 +64,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -100,16 +96,16 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } if (special == "defmacro!") { checkArgsIs("defmacro!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("defmacro!", malSymbol, list->item(1)); malValuePtr body = EVAL(list->item(2), env); - const malLambda* lambda = VALUE_CAST(malLambda, body); + const malLambda* lambda = VALUE_CAST("defmacro!", malLambda, body); return env->set(id->value(), mal::macro(*lambda)); } @@ -127,15 +123,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -152,12 +152,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -184,61 +185,49 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) continue; // TCO } checkArgsIs("try*", 2, argCount); - const malList* catchBlock = VALUE_CAST(malList, list->item(2)); - + const malList* catchBlock = VALUE_CAST("try*", malList, list->item(2)); + MAL_CHECK(!catchBlock->isEmpty() && + VALUE_CAST("catch*", malSymbol, catchBlock->item(0))->value() == "catch*", + "catch block must begin with catch*"); checkArgsIs("catch*", 2, catchBlock->count() - 1); - MAL_CHECK(VALUE_CAST(malSymbol, - catchBlock->item(0))->value() == "catch*", - "catch block must begin with catch*"); // We don't need excSym at this scope, but we want to check // that the catch block is valid always, not just in case of // an exception. const malSymbol* excSym = - VALUE_CAST(malSymbol, catchBlock->item(1)); - - malValuePtr excVal; + VALUE_CAST("catch*", malSymbol, catchBlock->item(1)); try { return EVAL(tryBody, env); } - catch(String& s) { - excVal = mal::string(s); - } - catch (malEmptyInputException&) { - // Not an error, continue as if we got nil - ast = mal::nilValue(); - } - catch(malValuePtr& o) { - excVal = o; - }; - - if (excVal) { - // we got some exception + catch(malValuePtr& excVal) { env = malEnvPtr(new malEnv(env)); env->set(excSym->value(), excVal); ast = catchBlock->item(2); + continue; // TCO } - continue; // TCO } } // Now we're left with the case of a regular list to be evaluated. - malValuePtr op = EVAL(list->item(0), env); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { - if (lambda->isMacro()) { - ast = lambda->apply(list->begin()+1, list->end()); - continue; // TCO - } - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - ast = lambda->getBody(); - env = lambda->makeEnv(items->begin(), items->end()); + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + if (lambda && lambda->isMacro()) { + ast = lambda->apply(list->begin()+1, list->end()); continue; // TCO } - else { - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - return APPLY(op, items->begin(), items->end()); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); } + if (lambda) { + ast = lambda->getBody(); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); + continue; // TCO + } + return op->apply(items.begin(), items.end()); } } @@ -247,15 +236,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static bool isSymbol(malValuePtr obj, const String& text) { const malSymbol* sym = DYNAMIC_CAST(malSymbol, obj); @@ -285,7 +265,7 @@ static malValuePtr quasiquote(malValuePtr obj) if (unquoted) return unquoted; - malValuePtr res = mal::list(new malValueVec(0)); + malValuePtr res = mal::list(); for (int i=seq->count()-1; 0<=i; i--) { const malValuePtr elt = seq->item(i); const malValuePtr spl_unq = starts_with(elt, "splice-unquote"); @@ -311,14 +291,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} - diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 1de24b5ed8..7dc5435f4d 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -1,74 +1,61 @@ -#include "MAL.h" - +#include "Core.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); // Installs functions, macros and constants implemented in MAL. +String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -static ReadLine s_readLine("~/.mal-history"); - -static malEnvPtr replEnv(new malEnv); +const malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + installCore(); installFunctions(replEnv); makeArgv(replEnv, argc - 2, argv + 2); if (argc > 1) { String filename = escape(argv[1]); - safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); + rep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } rep("(println (str \"Mal [\" *host-language* \"]\"))", replEnv); - while (s_readLine.get(prompt, input)) { - String out = safeRep(input, replEnv); - if (out.length() > 0) - std::cout << out << "\n"; + while (s_readLine_get(prompt, input)) { + std::cout << rep(input, replEnv) << "\n"; } return 0; } -static String safeRep(const String& input, malEnvPtr env) +String rep(const String& input, malEnvPtr env) { try { - return rep(input, env); - } - catch (malEmptyInputException&) { - return String(); + return PRINT(EVAL(READ(input), env)); } catch (malValuePtr& mv) { - return "Error: " + mv->print(true); + std::cerr << "Error: " << PRINT(mv) << "\n"; + return ""; } - catch (String& s) { - return "Error: " + s; - }; } static void makeArgv(malEnvPtr env, int argc, char* argv[]) { - malValueVec* args = new malValueVec(); + auto args = new malList(); for (int i = 0; i < argc; i++) { args->push_back(mal::string(argv[i])); } - env->set("*ARGV*", mal::list(args)); -} - -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -78,19 +65,28 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { - const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); - if (dbgenv && dbgenv->get("DEBUG-EVAL")->isTrue()) { + auto dbgenv = env->get("DEBUG-EVAL"); + if (dbgenv && dbgenv->isTrue()) { std::cout << "EVAL: " << PRINT(ast) << "\n"; } + if (auto symbol = DYNAMIC_CAST(malSymbol, ast)) { + auto key = symbol->value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; + } + if (auto map = DYNAMIC_CAST(malHash, ast)) { + return map->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } + if (auto vector = DYNAMIC_CAST(malVector, ast)) { + return vector->fmap([env] (malValuePtr x) { return EVAL(x, env); }); + } const malList* list = DYNAMIC_CAST(malList, ast); if (!list || (list->count() == 0)) { - return ast->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. @@ -101,16 +97,16 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "def!") { checkArgsIs("def!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("def!", malSymbol, list->item(1)); return env->set(id->value(), EVAL(list->item(2), env)); } if (special == "defmacro!") { checkArgsIs("defmacro!", 2, argCount); - const malSymbol* id = VALUE_CAST(malSymbol, list->item(1)); + const malSymbol* id = VALUE_CAST("defmacro!", malSymbol, list->item(1)); malValuePtr body = EVAL(list->item(2), env); - const malLambda* lambda = VALUE_CAST(malLambda, body); + const malLambda* lambda = VALUE_CAST("defmacro!", malLambda, body); return env->set(id->value(), mal::macro(*lambda)); } @@ -128,15 +124,19 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("fn*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("fn*", malSequence, list->item(1)); StringVec params; for (int i = 0; i < bindings->count(); i++) { const malSymbol* sym = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("fn*", malSymbol, bindings->item(i)); params.push_back(sym->value()); } - return mal::lambda(params, list->item(2), env); + malValuePtr body = list->item(2); + malLambda::ApplyFunc apply = + [body, env, params] (malValueIter b, malValueIter e) + { return EVAL(body, new malEnv(env, params, b, e)); }; + return mal::lambda(apply, params, body, env); } if (special == "if") { @@ -153,12 +153,13 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + VALUE_CAST("let*", malSequence, list->item(1)); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = - VALUE_CAST(malSymbol, bindings->item(i)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -185,61 +186,49 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) continue; // TCO } checkArgsIs("try*", 2, argCount); - const malList* catchBlock = VALUE_CAST(malList, list->item(2)); - + const malList* catchBlock = VALUE_CAST("try*", malList, list->item(2)); + MAL_CHECK(!catchBlock->isEmpty() && + VALUE_CAST("catch*", malSymbol, catchBlock->item(0))->value() == "catch*", + "catch block must begin with catch*"); checkArgsIs("catch*", 2, catchBlock->count() - 1); - MAL_CHECK(VALUE_CAST(malSymbol, - catchBlock->item(0))->value() == "catch*", - "catch block must begin with catch*"); // We don't need excSym at this scope, but we want to check // that the catch block is valid always, not just in case of // an exception. const malSymbol* excSym = - VALUE_CAST(malSymbol, catchBlock->item(1)); - - malValuePtr excVal; + VALUE_CAST("catch*", malSymbol, catchBlock->item(1)); try { return EVAL(tryBody, env); } - catch(String& s) { - excVal = mal::string(s); - } - catch (malEmptyInputException&) { - // Not an error, continue as if we got nil - ast = mal::nilValue(); - } - catch(malValuePtr& o) { - excVal = o; - }; - - if (excVal) { - // we got some exception + catch(malValuePtr& excVal) { env = malEnvPtr(new malEnv(env)); env->set(excSym->value(), excVal); ast = catchBlock->item(2); + continue; // TCO } - continue; // TCO } } // Now we're left with the case of a regular list to be evaluated. - malValuePtr op = EVAL(list->item(0), env); - if (const malLambda* lambda = DYNAMIC_CAST(malLambda, op)) { - if (lambda->isMacro()) { - ast = lambda->apply(list->begin()+1, list->end()); - continue; // TCO - } - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - ast = lambda->getBody(); - env = lambda->makeEnv(items->begin(), items->end()); + auto op = VALUE_CAST("EVAL apply phase", malApplicable, + EVAL(list->item(0), env)); + auto lambda = dynamic_cast(op); + if (lambda && lambda->isMacro()) { + ast = lambda->apply(list->begin()+1, list->end()); continue; // TCO } - else { - malValueVec* items = STATIC_CAST(malList, list->rest())->evalItems(env); - return APPLY(op, items->begin(), items->end()); + malValueVec items; + for (auto i = list->begin() + 1, e = list->end(); i != e; ++i) { + items.push_back(EVAL(*i, env)); } + if (lambda) { + ast = lambda->getBody(); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); + continue; // TCO + } + return op->apply(items.begin(), items.end()); } } @@ -248,15 +237,6 @@ String PRINT(malValuePtr ast) return ast->print(true); } -malValuePtr APPLY(malValuePtr op, malValueIter argsBegin, malValueIter argsEnd) -{ - const malApplicable* handler = DYNAMIC_CAST(malApplicable, op); - MAL_CHECK(handler != NULL, - "\"%s\" is not applicable", op->print(true).c_str()); - - return handler->apply(argsBegin, argsEnd); -} - static bool isSymbol(malValuePtr obj, const String& text) { const malSymbol* sym = DYNAMIC_CAST(malSymbol, obj); @@ -286,7 +266,7 @@ static malValuePtr quasiquote(malValuePtr obj) if (unquoted) return unquoted; - malValuePtr res = mal::list(new malValueVec(0)); + malValuePtr res = mal::list(); for (int i=seq->count()-1; 0<=i; i--) { const malValuePtr elt = seq->item(i); const malValuePtr spl_unq = starts_with(elt, "splice-unquote"); @@ -313,14 +293,3 @@ static void installFunctions(malEnvPtr env) { rep(function, env); } } - -// Added to keep the linker happy at step A -malValuePtr readline(const String& prompt) -{ - String input; - if (s_readLine.get(prompt, input)) { - return mal::string(input); - } - return mal::nilValue(); -} -