From 417961607fe9817d7f10286b819da5476f60a8ab Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Tue, 18 Aug 2026 14:47:14 +0200 Subject: [PATCH 01/19] c++: improve Makefile Compute system name with only one subprocess. Use predefined Make rules and variables when possible. Keep *FLAGS from the environment or command line. Allow the Make command line to override for example the -O option. Split LDLIBS from LDFLAGS and CPPFLAGS from CXXFLAGS. Pass compiler flags to the linker (this is necessary for -Og, safe otherwise). --- impls/cpp/Makefile | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/impls/cpp/Makefile b/impls/cpp/Makefile index 1c81812297..d0f30c5f36 100644 --- a/impls/cpp/Makefile +++ b/impls/cpp/Makefile @@ -1,4 +1,4 @@ -uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') +uname_S != uname -s 2>/dev/null CXX=g++ ifeq ($(uname_S),Darwin) @@ -8,12 +8,17 @@ ifeq ($(uname_S),Darwin) LIBPATHS=-L$(READLINE)/lib endif -LD=$(CXX) +LINK.o = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) AR=ar DEBUG=-ggdb -CXXFLAGS=-O3 -Wall $(DEBUG) $(INCPATHS) -std=c++11 -LDFLAGS=-O3 $(DEBUG) $(LIBPATHS) -L. -lreadline -lhistory +OPT = -O3 +WARN = -Wall +STDCXX = -std=c++11 + +CPPFLAGS += $(INCPATHS) +CXXFLAGS += $(OPT) $(WARN) $(DEBUG) $(STDCXX) +LDLIBS += $(LIBPATHS) -lreadline -lhistory LIBSOURCES=Core.cpp Environment.cpp Reader.cpp ReadLine.cpp String.cpp \ Types.cpp Validation.cpp @@ -22,9 +27,7 @@ LIBOBJS=$(LIBSOURCES:%.cpp=%.o) MAINS=$(wildcard step*.cpp) TARGETS=$(MAINS:%.cpp=%) -.PHONY: all clean - -.SUFFIXES: .cpp .o +.PHONY: all clean dist all: $(TARGETS) @@ -34,18 +37,14 @@ mal: stepA_mal cp $< $@ .deps: *.cpp *.h - $(CXX) $(CXXFLAGS) -MM *.cpp > .deps + $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM *.cpp > .deps -$(TARGETS): %: %.o libmal.a - $(LD) $^ -o $@ $(LDFLAGS) +$(TARGETS): libmal.a libmal.a: $(LIBOBJS) $(AR) rcs $@ $^ -.cpp.o: - $(CXX) $(CXXFLAGS) -c $< -o $@ - clean: - rm -rf *.o $(TARGETS) libmal.a .deps mal + rm -f *.o $(TARGETS) libmal.a .deps mal -include .deps From b801441c56d0acf2769b6a08186db97bfd98ee9b Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Wed, 26 Aug 2026 11:19:02 +0200 Subject: [PATCH 02/19] c++: reduce the diff between steps 345 Best viewed with `git diff -b`, only the indentation changes. This will help when applying the same patch to each step. --- impls/cpp/step3_env.cpp | 70 +++++++++---------- impls/cpp/step4_if_fn_do.cpp | 132 +++++++++++++++++------------------ 2 files changed, 101 insertions(+), 101 deletions(-) diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index fe76214a71..90ac02a778 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -51,47 +51,47 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr 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); - } + 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; + // 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(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(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)); + } + 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. + std::unique_ptr items(list->evalItems(env)); + malValuePtr op = items->at(0); + return APPLY(op, items->begin()+1, items->end()); } String PRINT(malValuePtr ast) diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index cef3c4ed99..0269f4ec37 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -53,87 +53,87 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr 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)); + 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); } - 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(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); - if (special == "if") { - checkArgsBetween("if", 2, 3, 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()); + } - bool isTrue = EVAL(list->item(1), env)->isTrue(); - if (!isTrue && (argCount == 2)) { - return mal::nilValue(); + return mal::lambda(params, list->item(2), 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 == "if") { + checkArgsBetween("if", 2, 3, argCount); + + bool isTrue = EVAL(list->item(1), env)->isTrue(); + if (!isTrue && (argCount == 2)) { + return mal::nilValue(); + } + 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)); + } + 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. + 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()); + } } String PRINT(malValuePtr ast) From 7d6c3fcc4003572b021e190a23a2caa4cd3d976a Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 11:44:25 +0200 Subject: [PATCH 03/19] c++: replace include guards with pragma once --- impls/cpp/Debug.h | 5 +---- impls/cpp/Environment.h | 5 +---- impls/cpp/ReadLine.h | 5 +---- impls/cpp/String.h | 5 +---- impls/cpp/Types.h | 5 +---- impls/cpp/Validation.h | 5 +---- 6 files changed, 6 insertions(+), 24 deletions(-) diff --git a/impls/cpp/Debug.h b/impls/cpp/Debug.h index c2ee75c78c..10b5814a15 100644 --- a/impls/cpp/Debug.h +++ b/impls/cpp/Debug.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_DEBUG_H -#define INCLUDE_DEBUG_H +#pragma once #include #include @@ -41,5 +40,3 @@ #define ASSERT(condition, ...) \ _ASSERT(__FILE__, __LINE__, condition, __VA_ARGS__) - -#endif // INCLUDE_DEBUG_H diff --git a/impls/cpp/Environment.h b/impls/cpp/Environment.h index 9753a22ead..0d0a93a31b 100644 --- a/impls/cpp/Environment.h +++ b/impls/cpp/Environment.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_ENVIRONMENT_H -#define INCLUDE_ENVIRONMENT_H +#pragma once #include "MAL.h" @@ -25,5 +24,3 @@ class malEnv : public RefCounted { Map m_map; malEnvPtr m_outer; }; - -#endif // INCLUDE_ENVIRONMENT_H diff --git a/impls/cpp/ReadLine.h b/impls/cpp/ReadLine.h index 94327aad97..d03be7eb1c 100644 --- a/impls/cpp/ReadLine.h +++ b/impls/cpp/ReadLine.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_READLINE_H -#define INCLUDE_READLINE_H +#pragma once #include "String.h" @@ -13,5 +12,3 @@ class ReadLine { private: String m_historyPath; }; - -#endif // INCLUDE_READLINE_H diff --git a/impls/cpp/String.h b/impls/cpp/String.h index bbedf9b33d..b2adcdd8c9 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 @@ -14,5 +13,3 @@ 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.h b/impls/cpp/Types.h index f92887c0fa..15ddb90ed1 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_TYPES_H -#define INCLUDE_TYPES_H +#pragma once #include "MAL.h" @@ -370,5 +369,3 @@ namespace mal { malValuePtr vector(malValueVec* items); malValuePtr vector(malValueIter begin, malValueIter end); }; - -#endif // INCLUDE_TYPES_H diff --git a/impls/cpp/Validation.h b/impls/cpp/Validation.h index d65e0fb64d..94f597a1cd 100644 --- a/impls/cpp/Validation.h +++ b/impls/cpp/Validation.h @@ -1,5 +1,4 @@ -#ifndef INCLUDE_VALIDATION_H -#define INCLUDE_VALIDATION_H +#pragma once #include "String.h" @@ -12,5 +11,3 @@ 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 From 184f4bf7ecec691dedf420f76737cfe2afdfdfd1 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Wed, 19 Aug 2026 17:20:27 +0200 Subject: [PATCH 04/19] c++: remove APPLY and evalitems, fix a memory leak In steps8A, unique_ptr was forgotten during the EVAL/macroexpand merge. Simply remove the dynamic allocation. --- impls/cpp/Core.cpp | 12 ++++++------ impls/cpp/MAL.h | 2 -- impls/cpp/Types.cpp | 29 +++++++--------------------- impls/cpp/Types.h | 1 - impls/cpp/step0_repl.cpp | 1 - impls/cpp/step1_read_print.cpp | 6 ------ impls/cpp/step2_eval.cpp | 25 +++++++++++++----------- impls/cpp/step3_env.cpp | 19 ++++++------------ impls/cpp/step4_if_fn_do.cpp | 23 +++++----------------- impls/cpp/step5_tco.cpp | 26 +++++++++---------------- impls/cpp/step6_file.cpp | 26 +++++++++---------------- impls/cpp/step7_quote.cpp | 26 +++++++++---------------- impls/cpp/step8_macros.cpp | 35 +++++++++++++--------------------- impls/cpp/step9_try.cpp | 35 +++++++++++++--------------------- impls/cpp/stepA_mal.cpp | 35 +++++++++++++--------------------- 15 files changed, 104 insertions(+), 197 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 9e91edcec1..85f13cff1d 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -139,7 +139,7 @@ BUILTIN("=") 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); @@ -150,7 +150,7 @@ BUILTIN("apply") args.push_back(lastArg->item(i)); } - return APPLY(op, args.begin(), args.end()); + return op->apply(args.begin(), args.end()); } BUILTIN("assoc") @@ -332,14 +332,14 @@ 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 it = source->begin(); for (int i = 0; i < length; i++) { - items->at(i) = APPLY(op, it+i, it+i+1); + items->at(i) = op->apply(it+i, it+i+1); } return mal::list(items); @@ -471,13 +471,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); } diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h index c82b50cc09..8fbc84a880 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -17,8 +17,6 @@ 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); diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index daf47cf748..75f437e055 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -329,18 +329,9 @@ malValuePtr malList::conj(malValueIter argsBegin, return mal::list(items); } -malValuePtr malList::eval(malEnvPtr env) +malValuePtr malList::eval(malEnvPtr) { - // 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()); + MAL_FAIL("lists are evaluated in EVAL"); } String malList::print(bool readably) const @@ -422,16 +413,6 @@ bool malSequence::doIsEqualTo(const malValue* rhs) const 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; -} - malValuePtr malSequence::first() const { return count() == 0 ? mal::nilValue() : item(0); @@ -489,7 +470,11 @@ malValuePtr malVector::conj(malValueIter argsBegin, malValuePtr malVector::eval(malEnvPtr env) { - return mal::vector(evalItems(env)); + malValueVec* items = new malValueVec;; + for (const auto &x : *this) { + items->push_back(EVAL(x, env)); + } + return mal::vector(items); } String malVector::print(bool readably) const diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 15ddb90ed1..37f7e0c139 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -166,7 +166,6 @@ class malSequence : public malValue { 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]; } diff --git a/impls/cpp/step0_repl.cpp b/impls/cpp/step0_repl.cpp index 6b9b29c8d6..772a5d7ae9 100644 --- a/impls/cpp/step0_repl.cpp +++ b/impls/cpp/step0_repl.cpp @@ -2,7 +2,6 @@ #include "ReadLine.h" #include -#include String READ(const String& input); String EVAL(const String& ast); diff --git a/impls/cpp/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index 9075c45295..c435fd5427 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -4,7 +4,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -59,8 +58,3 @@ 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..e9e6164823 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -53,7 +52,20 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { // std::cout << "EVAL: " << PRINT(ast) << "\n"; - return ast->eval(env); + 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. + + // Now we're left with the case of a regular list to be evaluated. + auto op = VALUE_CAST(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,15 +73,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); -} - #define ARG(type, name) type* name = VALUE_CAST(type, *argsBegin++) #define CHECK_ARGS_IS(expected) \ diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 90ac02a778..557f4f9c7b 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -89,9 +88,12 @@ 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); - return APPLY(op, items->begin()+1, items->end()); + auto op = VALUE_CAST(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,15 +101,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); -} - // Added to keep the linker happy at step A malValuePtr readline(const String& prompt) { diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index 0269f4ec37..f4c083bcea 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -125,15 +124,12 @@ 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)) { - return EVAL(lambda->getBody(), - lambda->makeEnv(items->begin()+1, items->end())); - } - else { - return APPLY(op, items->begin()+1, items->end()); + auto op = VALUE_CAST(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 +137,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)))", }; diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 0766d53f02..8e7f82c695 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -130,16 +129,18 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -148,15 +149,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)))", }; diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index e0c15e6109..b3f8975a52 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -153,16 +152,18 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -171,15 +172,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) \ diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index 1ced69952a..403020aa2b 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -165,16 +164,18 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); continue; // TCO } - else { - return APPLY(op, items->begin()+1, items->end()); - } + return op->apply(items.begin(), items.end()); } } @@ -183,15 +184,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); diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index b8897adbd1..e1c965e328 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -175,21 +174,22 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); + continue; // TCO } + return op->apply(items.begin(), items.end()); } } @@ -198,15 +198,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); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index c04ede8300..d6ec7a22ae 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -224,21 +223,22 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); + continue; // TCO } + return op->apply(items.begin(), items.end()); } } @@ -247,15 +247,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); diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 1de24b5ed8..f2291bd306 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -5,7 +5,6 @@ #include "Types.h" #include -#include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); @@ -225,21 +224,22 @@ 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(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 = lambda->makeEnv(items.begin(), items.end()); + continue; // TCO } + return op->apply(items.begin(), items.end()); } } @@ -248,15 +248,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); From d2de3724ae891ce726f42b8ac0d2ecee346c2644 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 11:58:02 +0200 Subject: [PATCH 05/19] c++: improve trace of object lifetimes --- impls/cpp/Debug.h | 25 +------------------------ impls/cpp/Environment.cpp | 17 +++++++++++++---- impls/cpp/MAL.h | 1 - impls/cpp/Reader.cpp | 1 + impls/cpp/RefCountedPtr.h | 2 -- impls/cpp/String.cpp | 1 - impls/cpp/Types.cpp | 20 ++++++++++++++++++++ impls/cpp/Types.h | 11 ++--------- 8 files changed, 37 insertions(+), 41 deletions(-) diff --git a/impls/cpp/Debug.h b/impls/cpp/Debug.h index 10b5814a15..5ff647b8cb 100644 --- a/impls/cpp/Debug.h +++ b/impls/cpp/Debug.h @@ -3,32 +3,9 @@ #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)) { \ diff --git a/impls/cpp/Environment.cpp b/impls/cpp/Environment.cpp index 1ae8f3e562..e271c11547 100644 --- a/impls/cpp/Environment.cpp +++ b/impls/cpp/Environment.cpp @@ -1,19 +1,26 @@ +#include "Debug.h" #include "Environment.h" #include "Types.h" #include +// make CPPFLAGS=-DDEBUG_ENV_LIFETIMES +#if DEBUG_ENV_LIFETIMES +static size_t allocs = 0; +#endif + malEnv::malEnv(malEnvPtr outer) : m_outer(outer) { - TRACE_ENV("Creating malEnv %p, outer=%p\n", this, m_outer.ptr()); +#if DEBUG_ENV_LIFETIMES + TRACE("Create env %lu %p outer=%p\n", ++allocs, this, m_outer.ptr()); +#endif } 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++) { @@ -32,7 +39,9 @@ malEnv::malEnv(malEnvPtr outer, const StringVec& bindings, malEnv::~malEnv() { - TRACE_ENV("Destroying malEnv %p, outer=%p\n", this, m_outer.ptr()); +#if DEBUG_ENV_LIFETIMES + TRACE("Destroy env %lu %p outer=%p\n", --allocs, this, m_outer.ptr()); +#endif } malEnvPtr malEnv::find(const String& symbol) diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h index 8fbc84a880..7fed2ad681 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -1,7 +1,6 @@ #ifndef INCLUDE_MAL_H #define INCLUDE_MAL_H -#include "Debug.h" #include "RefCountedPtr.h" #include "String.h" #include "Validation.h" diff --git a/impls/cpp/Reader.cpp b/impls/cpp/Reader.cpp index dbcb6c9c83..28bac8a266 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -1,3 +1,4 @@ +#include "Debug.h" #include "MAL.h" #include "Types.h" diff --git a/impls/cpp/RefCountedPtr.h b/impls/cpp/RefCountedPtr.h index 04cb952dc1..3bc8bbe7f4 100644 --- a/impls/cpp/RefCountedPtr.h +++ b/impls/cpp/RefCountedPtr.h @@ -1,8 +1,6 @@ #ifndef INCLUDE_REFCOUNTEDPTR_H #define INCLUDE_REFCOUNTEDPTR_H -#include "Debug.h" - #include class RefCounted { diff --git a/impls/cpp/String.cpp b/impls/cpp/String.cpp index dcdce2b0c1..e065c6b24e 100644 --- a/impls/cpp/String.cpp +++ b/impls/cpp/String.cpp @@ -1,4 +1,3 @@ -#include "Debug.h" #include "String.h" #include diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index 75f437e055..523756168b 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -6,6 +6,11 @@ #include #include +// make CPPFLAGS=-DDEBUG_OBJECT_LIFETIMES +#if DEBUG_OBJECT_LIFETIMES +static size_t allocs = 0; +#endif + namespace mal { malValuePtr atom(malValuePtr value) { return malValuePtr(new malAtom(value)); @@ -339,6 +344,21 @@ String malList::print(bool readably) const return '(' + malSequence::print(readably) + ')'; } +malValue::malValue(malValuePtr meta) +: m_meta(meta) +{ +#if DEBUG_OBJECT_LIFETIMES + TRACE("Create form %lu %p\n", ++allocs, this); +#endif +} + +malValue::~malValue() +{ +#if DEBUG_OBJECT_LIFETIMES + TRACE("Destroy form %lu %p\n", --allocs, this); +#endif +} + malValuePtr malValue::eval(malEnvPtr env) { // Default case of eval is just to return the object itself. diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 37f7e0c139..5ec2683d23 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -9,15 +9,8 @@ class malEmptyInputException : public std::exception { }; 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); - } + malValue(malValuePtr meta = NULL); + virtual ~malValue(); malValuePtr withMeta(malValuePtr meta) const; virtual malValuePtr doWithMeta(malValuePtr meta) const = 0; From c8d734808c37525528ba1dcd11de2d3aec518b72 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Sat, 22 Aug 2026 18:57:13 +0200 Subject: [PATCH 06/19] c++: improve the ReadLine module Minimize the .h interface. Drop unused C headers. Avoid C++ strings for encapsulated manipulations. Only write once the history at program exit. Add a macro producing debug information. Report errors with the history file (but do not crash tests for that). Create it when it is missing. --- impls/cpp/Core.cpp | 7 +++- impls/cpp/MAL.h | 1 - impls/cpp/ReadLine.cpp | 59 +++++++++++++++++++++++++++------- impls/cpp/ReadLine.h | 11 +------ impls/cpp/String.cpp | 10 ------ impls/cpp/String.h | 1 - impls/cpp/step0_repl.cpp | 4 +-- impls/cpp/step1_read_print.cpp | 4 +-- impls/cpp/step2_eval.cpp | 3 +- impls/cpp/step3_env.cpp | 15 +-------- impls/cpp/step4_if_fn_do.cpp | 15 +-------- impls/cpp/step5_tco.cpp | 15 +-------- impls/cpp/step6_file.cpp | 15 +-------- impls/cpp/step7_quote.cpp | 15 +-------- impls/cpp/step8_macros.cpp | 15 +-------- impls/cpp/step9_try.cpp | 15 +-------- impls/cpp/stepA_mal.cpp | 15 +-------- 17 files changed, 66 insertions(+), 154 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 85f13cff1d..271f665b30 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -1,5 +1,6 @@ #include "MAL.h" #include "Environment.h" +#include "ReadLine.h" #include "StaticList.h" #include "Types.h" @@ -395,7 +396,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!") diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h index 7fed2ad681..199382f7fd 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -17,7 +17,6 @@ typedef RefCountedPtr malEnvPtr; // step*.cpp extern malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -extern malValuePtr readline(const String& prompt); extern String rep(const String& input, malEnvPtr env); // Core.cpp 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 d03be7eb1c..748f581281 100644 --- a/impls/cpp/ReadLine.h +++ b/impls/cpp/ReadLine.h @@ -2,13 +2,4 @@ #include "String.h" -class ReadLine { -public: - ReadLine(const String& historyFile); - ~ReadLine(); - - bool get(const String& prompt, String& line); - -private: - String m_historyPath; -}; +bool s_readLine_get(const String& prompt, String& line); diff --git a/impls/cpp/String.cpp b/impls/cpp/String.cpp index e065c6b24e..2c972919ef 100644 --- a/impls/cpp/String.cpp +++ b/impls/cpp/String.cpp @@ -1,8 +1,6 @@ #include "String.h" #include -#include -#include #include // Adapted from: http://stackoverflow.com/questions/2342162 @@ -27,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; @@ -84,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 b2adcdd8c9..679d806d50 100644 --- a/impls/cpp/String.h +++ b/impls/cpp/String.h @@ -10,6 +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); diff --git a/impls/cpp/step0_repl.cpp b/impls/cpp/step0_repl.cpp index 772a5d7ae9..f6e794b394 100644 --- a/impls/cpp/step0_repl.cpp +++ b/impls/cpp/step0_repl.cpp @@ -8,13 +8,11 @@ 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[]) { 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 c435fd5427..cde2c1cf91 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -8,8 +8,6 @@ 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); @@ -17,7 +15,7 @@ int main(int argc, char* argv[]) { String prompt = "user> "; String input; - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out; try { out = rep(input); diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index e9e6164823..0e352c7807 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -9,7 +9,6 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); -static ReadLine s_readLine("~/.mal-history"); static malBuiltIn::ApplyFunc builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; @@ -22,7 +21,7 @@ int main(int argc, char* argv[]) replEnv->set("-", mal::builtin("-", &builtIn_sub)); replEnv->set("*", mal::builtin("+", &builtIn_mul)); replEnv->set("/", mal::builtin("/", &builtIn_div)); - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out; try { out = rep(input, replEnv); diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 557f4f9c7b..d7effdf4dd 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -9,8 +9,6 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); -static ReadLine s_readLine("~/.mal-history"); - static malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) @@ -18,7 +16,7 @@ int main(int argc, char* argv[]) String prompt = "user> "; String input; installCore(replEnv); - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out; try { out = rep(input, replEnv); @@ -100,14 +98,3 @@ String PRINT(malValuePtr ast) { return ast->print(true); } - -// 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/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index f4c083bcea..58b9a39b56 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -10,8 +10,6 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); -static ReadLine s_readLine("~/.mal-history"); - static malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) @@ -20,7 +18,7 @@ int main(int argc, char* argv[]) String input; installCore(replEnv); installFunctions(replEnv); - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out; try { out = rep(input, replEnv); @@ -146,14 +144,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 8e7f82c695..3ded1839d7 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -10,8 +10,6 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); -static ReadLine s_readLine("~/.mal-history"); - static malEnvPtr replEnv(new malEnv); int main(int argc, char* argv[]) @@ -20,7 +18,7 @@ int main(int argc, char* argv[]) String input; installCore(replEnv); installFunctions(replEnv); - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out; try { out = rep(input, replEnv); @@ -158,14 +156,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 b3f8975a52..ed8363e4d4 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -13,8 +13,6 @@ static void installFunctions(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); int main(int argc, char* argv[]) @@ -29,7 +27,7 @@ int main(int argc, char* argv[]) safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out = safeRep(input, replEnv); if (out.length() > 0) std::cout << out << "\n"; @@ -183,14 +181,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 403020aa2b..b82ab0bbba 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -14,8 +14,6 @@ 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); int main(int argc, char* argv[]) @@ -30,7 +28,7 @@ int main(int argc, char* argv[]) safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out = safeRep(input, replEnv); if (out.length() > 0) std::cout << out << "\n"; @@ -238,14 +236,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 e1c965e328..3ba9d0ad84 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -15,8 +15,6 @@ 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); int main(int argc, char* argv[]) @@ -31,7 +29,7 @@ int main(int argc, char* argv[]) safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out = safeRep(input, replEnv); if (out.length() > 0) std::cout << out << "\n"; @@ -253,14 +251,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 d6ec7a22ae..63a5a026e1 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -15,8 +15,6 @@ 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); int main(int argc, char* argv[]) @@ -31,7 +29,7 @@ int main(int argc, char* argv[]) safeRep(STRF("(load-file %s)", filename.c_str()), replEnv); return 0; } - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out = safeRep(input, replEnv); if (out.length() > 0) std::cout << out << "\n"; @@ -302,14 +300,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 f2291bd306..15149d093d 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -15,8 +15,6 @@ 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); int main(int argc, char* argv[]) @@ -32,7 +30,7 @@ int main(int argc, char* argv[]) return 0; } rep("(println (str \"Mal [\" *host-language* \"]\"))", replEnv); - while (s_readLine.get(prompt, input)) { + while (s_readLine_get(prompt, input)) { String out = safeRep(input, replEnv); if (out.length() > 0) std::cout << out << "\n"; @@ -304,14 +302,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(); -} - From 2b5b046893ef5f6099485b019dfdd93bbd2799bc Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Sat, 22 Aug 2026 19:51:03 +0200 Subject: [PATCH 07/19] c++: give Reader a .h header --- impls/cpp/Core.cpp | 1 + impls/cpp/MAL.h | 3 --- impls/cpp/Reader.cpp | 8 ++++---- impls/cpp/Reader.h | 6 ++++++ impls/cpp/step1_read_print.cpp | 1 + impls/cpp/step2_eval.cpp | 1 + impls/cpp/step3_env.cpp | 1 + impls/cpp/step4_if_fn_do.cpp | 1 + impls/cpp/step5_tco.cpp | 1 + impls/cpp/step6_file.cpp | 1 + impls/cpp/step7_quote.cpp | 1 + impls/cpp/step8_macros.cpp | 1 + impls/cpp/step9_try.cpp | 1 + impls/cpp/stepA_mal.cpp | 1 + 14 files changed, 21 insertions(+), 7 deletions(-) create mode 100644 impls/cpp/Reader.h diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 271f665b30..80a01ca8da 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -1,5 +1,6 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "StaticList.h" #include "Types.h" diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h index 199382f7fd..55205b3bef 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -22,7 +22,4 @@ 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/Reader.cpp b/impls/cpp/Reader.cpp index 28bac8a266..b9da432bf2 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -1,6 +1,6 @@ #include "Debug.h" -#include "MAL.h" -#include "Types.h" +#include "Reader.h" +#include "Validation.h" #include @@ -163,7 +163,7 @@ static malValuePtr readAtom(Tokeniser& tokeniser) const char* token; const char* symbol; }; - ReaderMacro macroTable[] = { + const static ReaderMacro macroTable[] = { { "@", "deref" }, { "`", "quasiquote" }, { "'", "quote" }, @@ -175,7 +175,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() }, 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/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index cde2c1cf91..0fe7d1352c 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index 0e352c7807..a45841318d 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index d7effdf4dd..cff2ca6774 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index 58b9a39b56..a49615d5c4 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 3ded1839d7..907a6e1a1b 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index ed8363e4d4..321b72511b 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index b82ab0bbba..fcb95db8bb 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index 3ba9d0ad84..387d69fa6f 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index 63a5a026e1..bfe8ba4c0b 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 15149d093d..67cdb65b30 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -1,6 +1,7 @@ #include "MAL.h" #include "Environment.h" +#include "Reader.h" #include "ReadLine.h" #include "Types.h" From 58261dc2bd0844276e88c89a2b60ced5daa6bb84 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Sat, 22 Aug 2026 20:09:48 +0200 Subject: [PATCH 08/19] c++: give Core a .h header, drop StaticList, build step3 without it Remove the confusing NULL env work-around from EVAL. Copy integer operations from step2 to step3 so step3 does not require Core. --- impls/cpp/Core.cpp | 28 +++++++++++------ impls/cpp/Core.h | 9 ++++++ impls/cpp/MAL.h | 3 -- impls/cpp/StaticList.h | 50 ----------------------------- impls/cpp/step3_env.cpp | 61 +++++++++++++++++++++++++++++++++--- impls/cpp/step4_if_fn_do.cpp | 9 ++---- impls/cpp/step5_tco.cpp | 8 ++--- impls/cpp/step6_file.cpp | 8 ++--- impls/cpp/step7_quote.cpp | 8 ++--- impls/cpp/step8_macros.cpp | 8 ++--- impls/cpp/step9_try.cpp | 8 ++--- impls/cpp/stepA_mal.cpp | 8 ++--- 12 files changed, 104 insertions(+), 104 deletions(-) create mode 100644 impls/cpp/Core.h delete mode 100644 impls/cpp/StaticList.h diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 80a01ca8da..1c936f6811 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -1,13 +1,13 @@ -#include "MAL.h" -#include "Environment.h" +#include "Core.h" #include "Reader.h" #include "ReadLine.h" -#include "StaticList.h" -#include "Types.h" +#include "String.h" +#include "Validation.h" #include #include #include +#include #define CHECK_ARGS_IS(expected) \ checkArgsIs(name.c_str(), expected, \ @@ -24,7 +24,16 @@ static String printValues(malValueIter begin, malValueIter end, const String& sep, bool readably); -static StaticList handlers; +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; +} #define ARG(type, name) type* name = VALUE_CAST(type, *argsBegin++) @@ -32,8 +41,7 @@ static StaticList handlers; #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) @@ -258,7 +266,7 @@ BUILTIN("empty?") BUILTIN("eval") { CHECK_ARGS_IS(1); - return EVAL(*argsBegin, NULL); + return EVAL(*argsBegin, replEnv); } BUILTIN("first") @@ -539,10 +547,10 @@ BUILTIN("with-meta") return obj->withMeta(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); } } 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/MAL.h b/impls/cpp/MAL.h index 55205b3bef..10abf5c1d4 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -19,7 +19,4 @@ typedef RefCountedPtr malEnvPtr; extern malValuePtr EVAL(malValuePtr ast, malEnvPtr env); extern String rep(const String& input, malEnvPtr env); -// Core.cpp -extern void installCore(malEnvPtr env); - #endif // INCLUDE_MAL_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/step3_env.cpp b/impls/cpp/step3_env.cpp index cff2ca6774..53c777f628 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -12,11 +12,17 @@ String PRINT(malValuePtr ast); static malEnvPtr replEnv(new malEnv); +static malBuiltIn::ApplyFunc + builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; + int main(int argc, char* argv[]) { String prompt = "user> "; String input; - installCore(replEnv); + 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 { @@ -45,10 +51,6 @@ 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"; @@ -99,3 +101,52 @@ String PRINT(malValuePtr ast) { return ast->print(true); } + +#define ARG(type, name) type* name = VALUE_CAST(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) +{ + CHECK_ARGS_IS(2); + ARG(malInteger, lhs); + ARG(malInteger, rhs); + return mal::integer(lhs->value() + rhs->value()); +} + +static malValuePtr builtIn_sub(const String& name, + malValueIter argsBegin, malValueIter argsEnd) +{ + int argCount = CHECK_ARGS_BETWEEN(1, 2); + ARG(malInteger, lhs); + if (argCount == 1) { + return mal::integer(- lhs->value()); + } + ARG(malInteger, rhs); + return mal::integer(lhs->value() - rhs->value()); +} + +static malValuePtr builtIn_mul(const String& name, + malValueIter argsBegin, malValueIter argsEnd) +{ + 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 a49615d5c4..bb0200a8c0 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -11,13 +12,13 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); -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); while (s_readLine_get(prompt, input)) { String out; @@ -47,10 +48,6 @@ 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"; diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 907a6e1a1b..944c3fe835 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -11,13 +12,13 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); -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); while (s_readLine_get(prompt, input)) { String out; @@ -47,9 +48,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index 321b72511b..e984cb267b 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -14,13 +15,13 @@ static void installFunctions(malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); static String safeRep(const String& input, malEnvPtr env); -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) { @@ -70,9 +71,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index fcb95db8bb..dde0d3c38d 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -15,13 +16,13 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]); static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -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) { @@ -71,9 +72,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index 387d69fa6f..51b1297109 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -16,13 +17,13 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]); static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -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) { @@ -72,9 +73,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index bfe8ba4c0b..5f408ef2b4 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -16,13 +17,13 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]); static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -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) { @@ -75,9 +76,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 67cdb65b30..85ea1cbdf4 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -1,5 +1,6 @@ #include "MAL.h" +#include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" @@ -16,13 +17,13 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]); static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); -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) { @@ -76,9 +77,6 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - if (!env) { - env = replEnv; - } while (1) { const malEnvPtr dbgenv = env->find("DEBUG-EVAL"); From 795d44e90e5e7ae6619c97846badb1ab7ce0007a Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Sat, 22 Aug 2026 19:32:03 +0200 Subject: [PATCH 09/19] c++: only throw MAL objects as exceptions Merge rep and safeRep. FIX: errors during the non-interactive startup are now reported. Move the implementation of value_cast from Types.h to .cpp so that it can see all headers. Remove the confusing malEmptyInputException. Simplify try* accordingly. --- impls/cpp/MAL.h | 1 - impls/cpp/Reader.cpp | 4 +--- impls/cpp/Types.cpp | 20 ++++++++++++++++ impls/cpp/Types.h | 10 +------- impls/cpp/Validation.cpp | 1 + impls/cpp/Validation.h | 2 +- impls/cpp/step1_read_print.cpp | 20 +++++++--------- impls/cpp/step2_eval.cpp | 21 +++++++--------- impls/cpp/step3_env.cpp | 21 +++++++--------- impls/cpp/step4_if_fn_do.cpp | 21 +++++++--------- impls/cpp/step5_tco.cpp | 21 +++++++--------- impls/cpp/step6_file.cpp | 25 +++++++------------ impls/cpp/step7_quote.cpp | 25 +++++++------------ impls/cpp/step8_macros.cpp | 26 +++++++------------- impls/cpp/step9_try.cpp | 44 +++++++--------------------------- impls/cpp/stepA_mal.cpp | 44 +++++++--------------------------- 16 files changed, 111 insertions(+), 195 deletions(-) diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h index 10abf5c1d4..570491fde2 100644 --- a/impls/cpp/MAL.h +++ b/impls/cpp/MAL.h @@ -17,6 +17,5 @@ typedef RefCountedPtr malEnvPtr; // step*.cpp extern malValuePtr EVAL(malValuePtr ast, malEnvPtr env); -extern String rep(const String& input, malEnvPtr env); #endif // INCLUDE_MAL_H diff --git a/impls/cpp/Reader.cpp b/impls/cpp/Reader.cpp index b9da432bf2..ada8d61111 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -122,9 +122,7 @@ 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); } diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index 523756168b..3031bce645 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -11,6 +11,26 @@ static size_t allocs = 0; #endif +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 INSTANTIATE_VALUE_CAST(T) \ + template T* value_cast(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) { return malValuePtr(new malAtom(value)); diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 5ec2683d23..804af625cb 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -2,11 +2,8 @@ #include "MAL.h" -#include #include -class malEmptyInputException : public std::exception { }; - class malValue : public RefCounted { public: malValue(malValuePtr meta = NULL); @@ -31,12 +28,7 @@ class malValue : public RefCounted { }; 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; -} +T* value_cast(malValuePtr obj, const char* typeName); #define VALUE_CAST(Type, Value) value_cast(Value, #Type) #define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value).ptr())) diff --git a/impls/cpp/Validation.cpp b/impls/cpp/Validation.cpp index 5b03b0f8ae..d297703a6b 100644 --- a/impls/cpp/Validation.cpp +++ b/impls/cpp/Validation.cpp @@ -1,3 +1,4 @@ +#include "Types.h" #include "Validation.h" int checkArgsIs(const char* name, int expected, int got) diff --git a/impls/cpp/Validation.h b/impls/cpp/Validation.h index 94f597a1cd..587065ce12 100644 --- a/impls/cpp/Validation.h +++ b/impls/cpp/Validation.h @@ -3,7 +3,7 @@ #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__) diff --git a/impls/cpp/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index 0fe7d1352c..27559b2bde 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -17,24 +17,20 @@ int main(int argc, char* argv[]) 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"; + 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) diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index a45841318d..29ede308b5 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -9,6 +9,7 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); +String rep(const String& input, malEnvPtr env); static malBuiltIn::ApplyFunc builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; @@ -23,24 +24,20 @@ int main(int argc, char* argv[]) 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"; + 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) diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 53c777f628..68d42ce11f 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -9,6 +9,7 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); +String rep(const String& input, malEnvPtr env); static malEnvPtr replEnv(new malEnv); @@ -24,24 +25,20 @@ int main(int argc, char* argv[]) 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"; + 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) diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index bb0200a8c0..de78b16498 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -11,6 +11,7 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); const malEnvPtr replEnv(new malEnv); @@ -21,24 +22,20 @@ int main(int argc, char* argv[]) 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"; + 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) diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 944c3fe835..e98ed65aa9 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -11,6 +11,7 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); const malEnvPtr replEnv(new malEnv); @@ -21,24 +22,20 @@ int main(int argc, char* argv[]) 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"; + 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) diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index e984cb267b..640c2bd000 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -11,9 +11,9 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); const malEnvPtr replEnv(new malEnv); @@ -26,28 +26,24 @@ int main(int argc, char* argv[]) 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"; + 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[]) @@ -59,11 +55,6 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]) env->set("*ARGV*", mal::list(args)); } -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); -} - malValuePtr READ(const String& input) { return readStr(input); diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index dde0d3c38d..f56cb8c910 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -11,9 +11,9 @@ malValuePtr READ(const String& input); String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); +String rep(const String& input, malEnvPtr env); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); const malEnvPtr replEnv(new malEnv); @@ -27,28 +27,24 @@ int main(int argc, char* argv[]) 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"; + 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[]) @@ -60,11 +56,6 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]) env->set("*ARGV*", mal::list(args)); } -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); -} - malValuePtr READ(const String& input) { return readStr(input); diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index 51b1297109..a6b590d9b7 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -13,8 +13,9 @@ String PRINT(malValuePtr ast); static void installFunctions(malEnvPtr env); // Installs functions and macros implemented in MAL. +String rep(const String& input, malEnvPtr env); + static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); const malEnvPtr replEnv(new malEnv); @@ -28,28 +29,24 @@ int main(int argc, char* argv[]) 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"; + 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[]) @@ -61,11 +58,6 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]) env->set("*ARGV*", mal::list(args)); } -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); -} - malValuePtr READ(const String& input) { return readStr(input); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index 5f408ef2b4..4a06ce8516 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -12,9 +12,9 @@ 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); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); const malEnvPtr replEnv(new malEnv); @@ -28,31 +28,24 @@ int main(int argc, char* argv[]) 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"; + 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[]) @@ -64,11 +57,6 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]) env->set("*ARGV*", mal::list(args)); } -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); -} - malValuePtr READ(const String& input) { return readStr(input); @@ -193,29 +181,15 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) const malSymbol* excSym = VALUE_CAST(malSymbol, catchBlock->item(1)); - malValuePtr excVal; - 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 } } diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 85ea1cbdf4..0c798e9655 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -12,9 +12,9 @@ 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); static void makeArgv(malEnvPtr env, int argc, char* argv[]); -static String safeRep(const String& input, malEnvPtr env); static malValuePtr quasiquote(malValuePtr obj); const malEnvPtr replEnv(new malEnv); @@ -28,32 +28,25 @@ int main(int argc, char* argv[]) 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"; + 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[]) @@ -65,11 +58,6 @@ static void makeArgv(malEnvPtr env, int argc, char* argv[]) env->set("*ARGV*", mal::list(args)); } -String rep(const String& input, malEnvPtr env) -{ - return PRINT(EVAL(READ(input), env)); -} - malValuePtr READ(const String& input) { return readStr(input); @@ -194,29 +182,15 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) const malSymbol* excSym = VALUE_CAST(malSymbol, catchBlock->item(1)); - malValuePtr excVal; - 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 } } From 38dfedba0f127f55c4d07edacbd4d9807b8bd8c7 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 11:25:38 +0200 Subject: [PATCH 10/19] c++: improve Environment --- impls/cpp/Environment.cpp | 30 ++++-------------------------- impls/cpp/Environment.h | 16 +++++++++------- impls/cpp/Types.cpp | 5 ++++- impls/cpp/step3_env.cpp | 4 ++-- impls/cpp/step4_if_fn_do.cpp | 4 ++-- impls/cpp/step5_tco.cpp | 4 ++-- impls/cpp/step6_file.cpp | 4 ++-- impls/cpp/step7_quote.cpp | 4 ++-- impls/cpp/step8_macros.cpp | 4 ++-- impls/cpp/step9_try.cpp | 4 ++-- impls/cpp/stepA_mal.cpp | 4 ++-- 11 files changed, 33 insertions(+), 50 deletions(-) diff --git a/impls/cpp/Environment.cpp b/impls/cpp/Environment.cpp index e271c11547..2528f8751b 100644 --- a/impls/cpp/Environment.cpp +++ b/impls/cpp/Environment.cpp @@ -1,8 +1,6 @@ #include "Debug.h" #include "Environment.h" -#include "Types.h" - -#include +#include "Validation.h" // make CPPFLAGS=-DDEBUG_ENV_LIFETIMES #if DEBUG_ENV_LIFETIMES @@ -44,25 +42,15 @@ malEnv::~malEnv() #endif } -malEnvPtr malEnv::find(const String& symbol) -{ - 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) +malValuePtr malEnv::get(const String& symbol) const { - for (malEnvPtr env = this; env; env = env->m_outer) { + for (auto env = this; env; env = env->m_outer.ptr()) { 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) @@ -70,13 +58,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 0d0a93a31b..4762190ae1 100644 --- a/impls/cpp/Environment.h +++ b/impls/cpp/Environment.h @@ -1,8 +1,10 @@ #pragma once -#include "MAL.h" +#include "RefCountedPtr.h" +#include "String.h" +#include "Types.h" -#include +#include class malEnv : public RefCounted { public: @@ -14,13 +16,13 @@ class malEnv : public RefCounted { ~malEnv(); - malValuePtr get(const String& symbol); - malEnvPtr find(const String& symbol); + malValuePtr get(const String& symbol) const; + // NULL means not found + malValuePtr set(const String& symbol, malValuePtr value); - malEnvPtr getRoot(); private: - typedef std::map Map; + typedef std::unordered_map Map; Map m_map; - malEnvPtr m_outer; + const malEnvPtr m_outer; }; diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index 3031bce645..859a57368e 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -492,7 +492,10 @@ String malString::print(bool readably) const malValuePtr malSymbol::eval(malEnvPtr env) { - return env->get(value()); + auto key = value(); + auto value = env->get(key); + MAL_CHECK(value, "'%s' not found", key.c_str()); + return value; } malValuePtr malVector::conj(malValueIter argsBegin, diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 68d42ce11f..1e9cd919aa 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -48,8 +48,8 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - 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"; } diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index de78b16498..aae8c5131f 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -45,8 +45,8 @@ malValuePtr READ(const String& input) malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { - 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"; } diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index e98ed65aa9..a135bafb88 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -47,8 +47,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index 640c2bd000..4045468870 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -64,8 +64,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index f56cb8c910..2bc4dc2e60 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -65,8 +65,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index a6b590d9b7..1d17a17bce 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -67,8 +67,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index 4a06ce8516..37ac40ac2a 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -66,8 +66,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 0c798e9655..bd8b8b537c 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -67,8 +67,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { 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"; } From 26ea12d384a488a5aa6445cea7b610ce79a4f64d Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 14:06:46 +0200 Subject: [PATCH 11/19] c++: drop the isEvaluated bool from maps --- impls/cpp/Core.cpp | 2 +- impls/cpp/Reader.cpp | 2 +- impls/cpp/Types.cpp | 13 +++---------- impls/cpp/Types.h | 8 +++----- 4 files changed, 8 insertions(+), 17 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 1c936f6811..ccbedb4cf4 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -304,7 +304,7 @@ BUILTIN("get") BUILTIN("hash-map") { - return mal::hash(argsBegin, argsEnd, true); + return mal::hash(argsBegin, argsEnd); } BUILTIN("keys") diff --git a/impls/cpp/Reader.cpp b/impls/cpp/Reader.cpp index ada8d61111..22b94766f0 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -150,7 +150,7 @@ static malValuePtr readForm(Tokeniser& tokeniser) tokeniser.next(); malValueVec items; readList(tokeniser, &items, "}"); - return mal::hash(items.begin(), items.end(), false); + return mal::hash(items.begin(), items.end()); } return readAtom(tokeniser); } diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index 859a57368e..1fec26e5c6 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -54,9 +54,8 @@ namespace mal { return malValuePtr(new malHash(map)); } - malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, - bool isEvaluated) { - return malValuePtr(new malHash(argsBegin, argsEnd, isEvaluated)); + malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd) { + return malValuePtr(new malHash(argsBegin, argsEnd)); } malValuePtr integer(int64_t value) { @@ -174,16 +173,14 @@ static malHash::Map createMap(malValueIter argsBegin, malValueIter argsEnd) return addToMap(map, argsBegin, argsEnd); } -malHash::malHash(malValueIter argsBegin, malValueIter argsEnd, bool isEvaluated) +malHash::malHash(malValueIter argsBegin, malValueIter argsEnd) : m_map(createMap(argsBegin, argsEnd)) -, m_isEvaluated(isEvaluated) { } malHash::malHash(const malHash::Map& map) : m_map(map) -, m_isEvaluated(true) { } @@ -217,10 +214,6 @@ malHash::dissoc(malValueIter argsBegin, malValueIter argsEnd) const malValuePtr malHash::eval(malEnvPtr env) { - if (m_isEvaluated) { - return malValuePtr(this); - } - malHash::Map map; for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { map[it->first] = EVAL(it->second, env); diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 804af625cb..ed8b1e6ba7 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -217,10 +217,10 @@ class malHash : public malValue { public: typedef std::map Map; - malHash(malValueIter argsBegin, malValueIter argsEnd, bool isEvaluated); + malHash(malValueIter argsBegin, malValueIter argsEnd); malHash(const malHash::Map& map); malHash(const malHash& that, malValuePtr meta) - : malValue(meta), m_map(that.m_map), m_isEvaluated(that.m_isEvaluated) { } + : malValue(meta), m_map(that.m_map) { } malValuePtr assoc(malValueIter argsBegin, malValueIter argsEnd) const; malValuePtr dissoc(malValueIter argsBegin, malValueIter argsEnd) const; @@ -238,7 +238,6 @@ class malHash : public malValue { private: const Map m_map; - const bool m_isEvaluated; }; class malBuiltIn : public malApplicable { @@ -333,8 +332,7 @@ namespace mal { malValuePtr boolean(bool value); malValuePtr builtin(const String& name, malBuiltIn::ApplyFunc handler); malValuePtr falseValue(); - malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, - bool isEvaluated); + malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd); malValuePtr hash(const malHash::Map& map); malValuePtr integer(int64_t value); malValuePtr integer(const String& token); From 396729cfc604ff923076093b01067ee55e9539b6 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 14:29:27 +0200 Subject: [PATCH 12/19] c++: remove the static archive, build modules in the order of the guide Ensure that Types does not need Environmen for steps 12. * Remove the dependency on EVAL (which differs between steps23). * Embed a closure into malLambda. * Move symbol evaluation to steps (it differs between steps 23). * Add an fmap function to malVector and malHash. * Remove malLambda::makeEnv because its implementation needs to call a malEnv function (the constructor). --- impls/cpp/MAL.h | 21 -------------- impls/cpp/Makefile | 37 +++++++++++++++---------- impls/cpp/Types.cpp | 50 ++++++++++++---------------------- impls/cpp/Types.h | 33 ++++++++++++++-------- impls/cpp/step1_read_print.cpp | 8 ------ impls/cpp/step2_eval.cpp | 37 +++++++++++++++++++------ impls/cpp/step3_env.cpp | 18 ++++++++++-- impls/cpp/step4_if_fn_do.cpp | 24 +++++++++++++--- impls/cpp/step5_tco.cpp | 27 ++++++++++++++---- impls/cpp/step6_file.cpp | 27 ++++++++++++++---- impls/cpp/step7_quote.cpp | 27 ++++++++++++++---- impls/cpp/step8_macros.cpp | 27 ++++++++++++++---- impls/cpp/step9_try.cpp | 27 ++++++++++++++---- impls/cpp/stepA_mal.cpp | 27 ++++++++++++++---- 14 files changed, 259 insertions(+), 131 deletions(-) delete mode 100644 impls/cpp/MAL.h diff --git a/impls/cpp/MAL.h b/impls/cpp/MAL.h deleted file mode 100644 index 570491fde2..0000000000 --- a/impls/cpp/MAL.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef INCLUDE_MAL_H -#define INCLUDE_MAL_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 EVAL(malValuePtr ast, malEnvPtr env); - -#endif // INCLUDE_MAL_H diff --git a/impls/cpp/Makefile b/impls/cpp/Makefile index d0f30c5f36..ce97d785ca 100644 --- a/impls/cpp/Makefile +++ b/impls/cpp/Makefile @@ -1,3 +1,20 @@ +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++ @@ -9,7 +26,6 @@ ifeq ($(uname_S),Darwin) endif LINK.o = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) -AR=ar DEBUG=-ggdb OPT = -O3 @@ -20,16 +36,9 @@ CPPFLAGS += $(INCPATHS) CXXFLAGS += $(OPT) $(WARN) $(DEBUG) $(STDCXX) LDLIBS += $(LIBPATHS) -lreadline -lhistory -LIBSOURCES=Core.cpp Environment.cpp Reader.cpp ReadLine.cpp String.cpp \ - Types.cpp Validation.cpp -LIBOBJS=$(LIBSOURCES:%.cpp=%.o) - -MAINS=$(wildcard step*.cpp) -TARGETS=$(MAINS:%.cpp=%) - .PHONY: all clean dist -all: $(TARGETS) +all: $(step0A) dist: mal @@ -39,12 +48,12 @@ mal: stepA_mal .deps: *.cpp *.h $(CXX) $(CXXFLAGS) $(CPPFLAGS) -MM *.cpp > .deps -$(TARGETS): libmal.a - -libmal.a: $(LIBOBJS) - $(AR) rcs $@ $^ +$(step0A): ReadLine.o String.o +$(step1A): Reader.o Types.o Validation.o +$(step3A): Environment.o +$(step4A): Core.o clean: - rm -f *.o $(TARGETS) libmal.a .deps mal + rm -f *.o $(step0A) .deps mal -include .deps diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index 1fec26e5c6..d1b8e80b7b 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -1,6 +1,7 @@ #include "Debug.h" #include "Environment.h" #include "Types.h" +#include "Validation.h" #include #include @@ -70,9 +71,10 @@ 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) { @@ -212,11 +214,11 @@ malHash::dissoc(malValueIter argsBegin, malValueIter argsEnd) const return mal::hash(map); } -malValuePtr malHash::eval(malEnvPtr env) +malValuePtr malHash::fmap(std::function f) const { malHash::Map map; for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { - map[it->first] = EVAL(it->second, env); + map[it->first] = f(it->second); } return mal::hash(map); } @@ -288,9 +290,11 @@ bool malHash::doIsEqualTo(const malValue* rhs) const return true; } -malLambda::malLambda(const StringVec& bindings, +malLambda::malLambda(ApplyFunc apply, + const StringVec& bindings, malValuePtr body, malEnvPtr env) -: m_bindings(bindings) +: m_apply(apply) +, m_bindings(bindings) , m_body(body) , m_env(env) , m_isMacro(false) @@ -300,6 +304,7 @@ malLambda::malLambda(const StringVec& bindings, malLambda::malLambda(const malLambda& that, malValuePtr meta) : malApplicable(meta) +, m_apply(that.m_apply) , m_bindings(that.m_bindings) , m_body(that.m_body) , m_env(that.m_env) @@ -310,6 +315,7 @@ malLambda::malLambda(const malLambda& that, malValuePtr meta) malLambda::malLambda(const malLambda& that, bool isMacro) : malApplicable(that.m_meta) +, m_apply(that.m_apply) , m_bindings(that.m_bindings) , m_body(that.m_body) , m_env(that.m_env) @@ -321,18 +327,17 @@ 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::doWithMeta(malValuePtr meta) const { return new malLambda(*this, meta); } -malEnvPtr malLambda::makeEnv(malValueIter argsBegin, malValueIter argsEnd) const -{ - return malEnvPtr(new malEnv(m_env, m_bindings, argsBegin, argsEnd)); -} +malEnvPtr malLambda::getEnv() const { return m_env; } malValuePtr malList::conj(malValueIter argsBegin, malValueIter argsEnd) const @@ -347,11 +352,6 @@ malValuePtr malList::conj(malValueIter argsBegin, return mal::list(items); } -malValuePtr malList::eval(malEnvPtr) -{ - MAL_FAIL("lists are evaluated in EVAL"); -} - String malList::print(bool readably) const { return '(' + malSequence::print(readably) + ')'; @@ -372,12 +372,6 @@ malValue::~malValue() #endif } -malValuePtr malValue::eval(malEnvPtr env) -{ - // Default case of eval is just to return the object itself. - return malValuePtr(this); -} - bool malValue::isEqualTo(const malValue* rhs) const { // Special-case. Vectors and Lists can be compared. @@ -483,14 +477,6 @@ String malString::print(bool readably) const return readably ? escapedValue() : value(); } -malValuePtr malSymbol::eval(malEnvPtr env) -{ - auto key = value(); - auto value = env->get(key); - MAL_CHECK(value, "'%s' not found", key.c_str()); - return value; -} - malValuePtr malVector::conj(malValueIter argsBegin, malValueIter argsEnd) const { @@ -504,11 +490,11 @@ malValuePtr malVector::conj(malValueIter argsBegin, return mal::vector(items); } -malValuePtr malVector::eval(malEnvPtr env) +malValuePtr malVector::fmap(std::function f) const { malValueVec* items = new malValueVec;; for (const auto &x : *this) { - items->push_back(EVAL(x, env)); + items->push_back(f(x)); } return mal::vector(items); } diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index ed8b1e6ba7..5719ddd548 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -1,8 +1,19 @@ #pragma once -#include "MAL.h" +#include "RefCountedPtr.h" +#include "String.h" +#include #include +#include + +class malValue; +typedef RefCountedPtr malValuePtr; +typedef std::vector malValueVec; +typedef malValueVec::const_iterator malValueIter; + +class malEnv; // Environment.h +typedef RefCountedPtr malEnvPtr; class malValue : public RefCounted { public: @@ -17,8 +28,6 @@ class malValue : public RefCounted { bool isEqualTo(const malValue* rhs) const; - virtual malValuePtr eval(malEnvPtr env); - virtual String print(bool readably) const = 0; protected: @@ -133,8 +142,6 @@ class malSymbol : public malStringBase { 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(); } @@ -179,7 +186,6 @@ class malList : public malSequence { : malSequence(that, meta) { } virtual String print(bool readably) const; - virtual malValuePtr eval(malEnvPtr env); virtual malValuePtr conj(malValueIter argsBegin, malValueIter argsEnd) const; @@ -195,7 +201,7 @@ class malVector : public malSequence { malVector(const malVector& that, malValuePtr meta) : malSequence(that, meta) { } - virtual malValuePtr eval(malEnvPtr env); + malValuePtr fmap(std::function f) const; virtual String print(bool readably) const; virtual malValuePtr conj(malValueIter argsBegin, @@ -225,7 +231,7 @@ class malHash : public malValue { 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; @@ -274,15 +280,18 @@ class malBuiltIn : public malApplicable { class malLambda : public malApplicable { public: - malLambda(const StringVec& bindings, malValuePtr body, malEnvPtr env); + typedef std::function ApplyFunc; + malLambda(ApplyFunc apply, const StringVec& bindings, malValuePtr body, + malEnvPtr env); malLambda(const malLambda& that, malValuePtr meta); malLambda(const malLambda& that, bool isMacro); virtual malValuePtr apply(malValueIter argsBegin, malValueIter argsEnd) const; + StringVec getBindings() const; malValuePtr getBody() const { return m_body; } - malEnvPtr makeEnv(malValueIter argsBegin, malValueIter argsEnd) const; + malEnvPtr getEnv() const; virtual bool doIsEqualTo(const malValue* rhs) const { return this == rhs; // do we need to do a deep inspection? @@ -297,6 +306,7 @@ class malLambda : public malApplicable { virtual malValuePtr doWithMeta(malValuePtr meta) const; private: + const ApplyFunc m_apply; const StringVec m_bindings; const malValuePtr m_body; const malEnvPtr m_env; @@ -337,7 +347,8 @@ namespace mal { 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); diff --git a/impls/cpp/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index 27559b2bde..64a67bfeeb 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -1,5 +1,3 @@ -#include "MAL.h" - #include "Reader.h" #include "ReadLine.h" #include "Types.h" @@ -47,9 +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; -} diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index 29ede308b5..9550db306e 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -1,15 +1,23 @@ -#include "MAL.h" - -#include "Environment.h" #include "Reader.h" #include "ReadLine.h" +#include "RefCountedPtr.h" +#include "String.h" #include "Types.h" +#include "Validation.h" #include +#include + +class malEnv + : public std::unordered_map, + public RefCounted +{ +}; malValuePtr READ(const String& input); String PRINT(malValuePtr ast); String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static malBuiltIn::ApplyFunc builtIn_add, builtIn_sub, builtIn_mul, builtIn_div; @@ -19,10 +27,10 @@ int main(int argc, char* argv[]) 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)); + (*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"; } @@ -49,9 +57,22 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) { // std::cout << "EVAL: " << PRINT(ast) << "\n"; + 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->eval(env); + return ast; } // From here on down we are evaluating a non-empty list. diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 1e9cd919aa..a4ad09df74 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -1,15 +1,15 @@ -#include "MAL.h" - #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include malValuePtr READ(const String& input); String PRINT(malValuePtr ast); String rep(const String& input, malEnvPtr env); +malValuePtr EVAL(malValuePtr ast, malEnvPtr env); static malEnvPtr replEnv(new malEnv); @@ -53,9 +53,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index aae8c5131f..eb74e2ec51 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -12,6 +11,7 @@ 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); const malEnvPtr replEnv(new malEnv); @@ -50,9 +50,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -88,7 +100,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index a135bafb88..b29e2d7fc5 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -12,6 +11,7 @@ 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); const malEnvPtr replEnv(new malEnv); @@ -52,9 +52,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -91,7 +103,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -131,7 +147,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index 4045468870..e3448705f0 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -12,6 +11,7 @@ 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[]); @@ -69,9 +69,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -108,7 +120,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -148,7 +164,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index 2bc4dc2e60..bf7f3f0d6a 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -12,6 +11,7 @@ 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 malValuePtr quasiquote(malValuePtr obj); @@ -70,9 +70,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -109,7 +121,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -160,7 +176,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index 1d17a17bce..5201d10400 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -14,6 +13,7 @@ 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 malValuePtr quasiquote(malValuePtr obj); @@ -72,9 +72,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -120,7 +132,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -175,7 +191,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index 37ac40ac2a..b776e820f2 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -13,6 +12,7 @@ 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 malValuePtr quasiquote(malValuePtr obj); @@ -71,9 +71,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -119,7 +131,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -206,7 +222,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index bd8b8b537c..5d641df85d 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -1,10 +1,9 @@ -#include "MAL.h" - #include "Core.h" #include "Environment.h" #include "Reader.h" #include "ReadLine.h" #include "Types.h" +#include "Validation.h" #include @@ -13,6 +12,7 @@ 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 malValuePtr quasiquote(malValuePtr obj); @@ -72,9 +72,21 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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. @@ -120,7 +132,11 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) 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") { @@ -207,7 +223,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } if (lambda) { ast = lambda->getBody(); - env = lambda->makeEnv(items.begin(), items.end()); + env = new malEnv(lambda->getEnv(), lambda->getBindings(), + items.begin(), items.end()); continue; // TCO } return op->apply(items.begin(), items.end()); From a9ad2ae29dd66cda9d540ce5a0412679b1fd69a0 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Fri, 21 Aug 2026 16:07:15 +0200 Subject: [PATCH 13/19] c++: add context to value_cast messages --- impls/cpp/Core.cpp | 6 +++--- impls/cpp/Types.cpp | 6 +++--- impls/cpp/Types.h | 4 ++-- impls/cpp/step2_eval.cpp | 5 +++-- impls/cpp/step3_env.cpp | 11 ++++++----- impls/cpp/step4_if_fn_do.cpp | 13 +++++++------ impls/cpp/step5_tco.cpp | 13 +++++++------ impls/cpp/step6_file.cpp | 13 +++++++------ impls/cpp/step7_quote.cpp | 13 +++++++------ impls/cpp/step8_macros.cpp | 17 +++++++++-------- impls/cpp/step9_try.cpp | 23 ++++++++++++----------- impls/cpp/stepA_mal.cpp | 23 ++++++++++++----------- 12 files changed, 78 insertions(+), 69 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index ccbedb4cf4..ce3783a753 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -35,7 +35,7 @@ bool addHandler(const String &name, malBuiltIn::ApplyFunc handler) return false; } -#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 @@ -155,7 +155,7 @@ BUILTIN("apply") 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)); } @@ -182,7 +182,7 @@ BUILTIN("concat") { int count = 0; for (auto it = argsBegin; it != argsEnd; ++it) { - const malSequence* seq = VALUE_CAST(malSequence, *it); + const malSequence* seq = VALUE_CAST(name, malSequence, *it); count += seq->count(); } diff --git a/impls/cpp/Types.cpp b/impls/cpp/Types.cpp index d1b8e80b7b..dc7788eb3d 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -13,15 +13,15 @@ static size_t allocs = 0; #endif template -T* value_cast(malValuePtr obj, const char* typeName) +T* value_cast(const String& context, malValuePtr obj, const char* typeName) { T* dest = dynamic_cast(obj.ptr()); - MAL_CHECK(dest != NULL, "%s is not a %s", + 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(malValuePtr, const char*) + template T* value_cast(const String&, malValuePtr, const char*) INSTANTIATE_VALUE_CAST(malApplicable); INSTANTIATE_VALUE_CAST(malAtom); INSTANTIATE_VALUE_CAST(malHash); diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 5719ddd548..31a669d246 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -37,9 +37,9 @@ class malValue : public RefCounted { }; template -T* value_cast(malValuePtr obj, const char* typeName); +T* value_cast(const String& context, malValuePtr obj, const char* typeName); -#define VALUE_CAST(Type, Value) value_cast(Value, #Type) +#define VALUE_CAST(context, Type, Value) value_cast(context, Value, #Type) #define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value).ptr())) #define STATIC_CAST(Type, Value) (static_cast((Value).ptr())) diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index 9550db306e..4d6067a5c0 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -78,7 +78,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) // 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(malApplicable, EVAL(list->item(0), env)); + 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)); @@ -91,7 +92,7 @@ String PRINT(malValuePtr ast) return ast->print(true); } -#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)) diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index a4ad09df74..928fc2bef7 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -78,19 +78,19 @@ 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 == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } return EVAL(list->item(2), inner); @@ -98,7 +98,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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)); @@ -111,7 +112,7 @@ String PRINT(malValuePtr ast) return ast->print(true); } -#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)) diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index eb74e2ec51..88be24d756 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -75,7 +75,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)); } @@ -92,11 +92,11 @@ 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()); } @@ -120,12 +120,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } return EVAL(list->item(2), inner); @@ -133,7 +133,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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)); diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index b29e2d7fc5..efe8218a6b 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -77,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)); } @@ -95,11 +95,11 @@ 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()); } @@ -124,12 +124,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -139,7 +139,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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) { diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index e3448705f0..aff6263379 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -94,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)); } @@ -112,11 +112,11 @@ 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()); } @@ -141,12 +141,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -156,7 +156,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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) { diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index bf7f3f0d6a..a6538282d9 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -95,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)); } @@ -113,11 +113,11 @@ 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()); } @@ -142,12 +142,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -168,7 +168,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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) { diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index 5201d10400..e6c2ab500a 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -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,11 +124,11 @@ 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()); } @@ -153,12 +153,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -179,7 +179,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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()); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index b776e820f2..d31f342dfa 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -96,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)); } @@ -123,11 +123,11 @@ 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()); } @@ -152,12 +152,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -184,10 +184,10 @@ 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)); checkArgsIs("catch*", 2, catchBlock->count() - 1); - MAL_CHECK(VALUE_CAST(malSymbol, + MAL_CHECK(VALUE_CAST("catch*", malSymbol, catchBlock->item(0))->value() == "catch*", "catch block must begin with catch*"); @@ -195,7 +195,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) // that the catch block is valid always, not just in case of // an exception. const malSymbol* excSym = - VALUE_CAST(malSymbol, catchBlock->item(1)); + VALUE_CAST("catch*", malSymbol, catchBlock->item(1)); try { return EVAL(tryBody, env); @@ -210,7 +210,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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()); diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 5d641df85d..57e77b583a 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -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,11 +124,11 @@ 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()); } @@ -153,12 +153,12 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) if (special == "let*") { checkArgsIs("let*", 2, argCount); const malSequence* bindings = - VALUE_CAST(malSequence, list->item(1)); + VALUE_CAST("let*", 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)); + VALUE_CAST("let*", malSymbol, bindings->item(i)); inner->set(var->value(), EVAL(bindings->item(i+1), inner)); } ast = list->item(2); @@ -185,10 +185,10 @@ 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)); checkArgsIs("catch*", 2, catchBlock->count() - 1); - MAL_CHECK(VALUE_CAST(malSymbol, + MAL_CHECK(VALUE_CAST("catch*", malSymbol, catchBlock->item(0))->value() == "catch*", "catch block must begin with catch*"); @@ -196,7 +196,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) // that the catch block is valid always, not just in case of // an exception. const malSymbol* excSym = - VALUE_CAST(malSymbol, catchBlock->item(1)); + VALUE_CAST("catch*", malSymbol, catchBlock->item(1)); try { return EVAL(tryBody, env); @@ -211,7 +211,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } // Now we're left with the case of a regular list to be evaluated. - auto op = VALUE_CAST(malApplicable, EVAL(list->item(0), env)); + 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()); From f8dbbc54632bf737da8d881d5dff912f35aa3e23 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Tue, 18 Aug 2026 17:37:25 +0200 Subject: [PATCH 14/19] c++: fix a few -Wextra warnings about unused arguments --- impls/cpp/Core.cpp | 8 ++++++++ impls/cpp/Makefile | 2 +- impls/cpp/step0_repl.cpp | 2 +- impls/cpp/step1_read_print.cpp | 2 +- impls/cpp/step2_eval.cpp | 2 +- impls/cpp/step3_env.cpp | 2 +- impls/cpp/step4_if_fn_do.cpp | 2 +- impls/cpp/step5_tco.cpp | 2 +- 8 files changed, 15 insertions(+), 7 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index ce3783a753..68ab1bfdb4 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -35,6 +35,8 @@ bool addHandler(const String &name, malBuiltIn::ApplyFunc handler) return false; } +#define BUILTIN_UNUSED_PARAMETER_NAME (void)name + #define ARG(type, var) type* var = VALUE_CAST(name, type, *argsBegin++) #define FUNCNAME(uniq) builtIn ## uniq @@ -327,6 +329,7 @@ BUILTIN("keyword") BUILTIN("list") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::list(argsBegin, argsEnd); } @@ -377,17 +380,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(); } @@ -477,6 +483,7 @@ BUILTIN("slurp") BUILTIN("str") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::string(printValues(argsBegin, argsEnd, "", false)); } @@ -536,6 +543,7 @@ BUILTIN("vec") BUILTIN("vector") { + BUILTIN_UNUSED_PARAMETER_NAME; return mal::vector(argsBegin, argsEnd); } diff --git a/impls/cpp/Makefile b/impls/cpp/Makefile index ce97d785ca..07a91ab8e1 100644 --- a/impls/cpp/Makefile +++ b/impls/cpp/Makefile @@ -29,7 +29,7 @@ LINK.o = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(LDFLAGS) DEBUG=-ggdb OPT = -O3 -WARN = -Wall +WARN = -Wall -Wextra STDCXX = -std=c++11 CPPFLAGS += $(INCPATHS) diff --git a/impls/cpp/step0_repl.cpp b/impls/cpp/step0_repl.cpp index f6e794b394..20bbca8755 100644 --- a/impls/cpp/step0_repl.cpp +++ b/impls/cpp/step0_repl.cpp @@ -8,7 +8,7 @@ String EVAL(const String& ast); String PRINT(const String& ast); String rep(const String& input); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; diff --git a/impls/cpp/step1_read_print.cpp b/impls/cpp/step1_read_print.cpp index 64a67bfeeb..82abd56610 100644 --- a/impls/cpp/step1_read_print.cpp +++ b/impls/cpp/step1_read_print.cpp @@ -10,7 +10,7 @@ String PRINT(malValuePtr ast); 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; diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index 4d6067a5c0..d7814fdf96 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -22,7 +22,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env); 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; diff --git a/impls/cpp/step3_env.cpp b/impls/cpp/step3_env.cpp index 928fc2bef7..e447e35c06 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -16,7 +16,7 @@ static malEnvPtr replEnv(new malEnv); 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; diff --git a/impls/cpp/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index 88be24d756..bbbccaa6c7 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -15,7 +15,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env); const malEnvPtr replEnv(new malEnv); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index efe8218a6b..2e616d782d 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -15,7 +15,7 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env); const malEnvPtr replEnv(new malEnv); -int main(int argc, char* argv[]) +int main(int, char*[]) { String prompt = "user> "; String input; From de21b75c18b796610818e7e6dd31d7296ef96b86 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Thu, 13 Aug 2026 22:10:40 +0200 Subject: [PATCH 15/19] c++: Validation: stop returning the argument count --- impls/cpp/Core.cpp | 4 ++-- impls/cpp/Validation.cpp | 12 ++++-------- impls/cpp/Validation.h | 8 ++++---- impls/cpp/step2_eval.cpp | 4 ++-- impls/cpp/step3_env.cpp | 7 ++++--- impls/cpp/step4_if_fn_do.cpp | 3 ++- impls/cpp/step5_tco.cpp | 3 ++- impls/cpp/step6_file.cpp | 3 ++- impls/cpp/step7_quote.cpp | 3 ++- impls/cpp/step8_macros.cpp | 3 ++- impls/cpp/step9_try.cpp | 3 ++- impls/cpp/stepA_mal.cpp | 3 ++- 12 files changed, 30 insertions(+), 26 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 68ab1bfdb4..8ec0df0ef2 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -93,9 +93,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()); } diff --git a/impls/cpp/Validation.cpp b/impls/cpp/Validation.cpp index d297703a6b..3f07923073 100644 --- a/impls/cpp/Validation.cpp +++ b/impls/cpp/Validation.cpp @@ -1,34 +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 587065ce12..96cd08d6f2 100644 --- a/impls/cpp/Validation.h +++ b/impls/cpp/Validation.h @@ -7,7 +7,7 @@ #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); +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/step2_eval.cpp b/impls/cpp/step2_eval.cpp index d7814fdf96..cba4f8da0b 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -113,9 +113,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 e447e35c06..397580ae2f 100644 --- a/impls/cpp/step3_env.cpp +++ b/impls/cpp/step3_env.cpp @@ -86,7 +86,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = @@ -133,9 +134,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/step4_if_fn_do.cpp b/impls/cpp/step4_if_fn_do.cpp index bbbccaa6c7..4360ed875a 100644 --- a/impls/cpp/step4_if_fn_do.cpp +++ b/impls/cpp/step4_if_fn_do.cpp @@ -121,7 +121,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/step5_tco.cpp b/impls/cpp/step5_tco.cpp index 2e616d782d..b92472ecae 100644 --- a/impls/cpp/step5_tco.cpp +++ b/impls/cpp/step5_tco.cpp @@ -125,7 +125,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index aff6263379..e13bbe39dd 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -142,7 +142,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index a6538282d9..ce9b28c609 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -143,7 +143,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index e6c2ab500a..dc39a3e9fd 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -154,7 +154,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index d31f342dfa..a74c9e4c2d 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -153,7 +153,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 57e77b583a..644d8244ca 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -154,7 +154,8 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) checkArgsIs("let*", 2, argCount); const malSequence* bindings = VALUE_CAST("let*", malSequence, list->item(1)); - int count = checkArgsEven("let*", bindings->count()); + int count = bindings->count(); + checkArgsEven("let*", count); malEnvPtr inner(new malEnv(env)); for (int i = 0; i < count; i += 2) { const malSymbol* var = From a142116d1b153739374c1856f312d7e4f838473d Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 17 Aug 2026 12:15:56 +0200 Subject: [PATCH 16/19] c++: move printValues from Core to Types --- impls/cpp/Core.cpp | 21 --------------------- impls/cpp/Types.cpp | 14 ++++++++------ impls/cpp/Types.h | 5 +++-- 3 files changed, 11 insertions(+), 29 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index 8ec0df0ef2..d2d72cc6d7 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -21,9 +21,6 @@ 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). @@ -561,21 +558,3 @@ void installCore() { 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/Types.cpp b/impls/cpp/Types.cpp index dc7788eb3d..eb42922f41 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -354,7 +354,7 @@ malValuePtr malList::conj(malValueIter argsBegin, String malList::print(bool readably) const { - return '(' + malSequence::print(readably) + ')'; + return '(' + printValues(begin(), end(), " ", readably) + ')'; } malValue::malValue(malValuePtr meta) @@ -445,19 +445,21 @@ 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; } @@ -501,5 +503,5 @@ malValuePtr malVector::fmap(std::function f) const 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 31a669d246..5cb283b409 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -156,8 +156,6 @@ class malSequence : public malValue { malSequence(const malSequence& that, malValuePtr meta); virtual ~malSequence(); - virtual String print(bool readably) const; - int count() const { return m_items->size(); } bool isEmpty() const { return m_items->empty(); } malValuePtr item(int index) const { return (*m_items)[index]; } @@ -362,3 +360,6 @@ namespace mal { malValuePtr vector(malValueVec* items); malValuePtr vector(malValueIter begin, malValueIter end); }; + +String printValues(malValueIter begin, malValueIter end, + const String& sep, bool readably); From d13087639b73c0320df1b8115c8350a82754a659 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Thu, 20 Aug 2026 15:33:13 +0200 Subject: [PATCH 17/19] c++: improve the Types interface Move implementations from Types.h to .cpp so that they are not compiled on each inclusion. Encapsulate the representation of maps, and change it from binary trees to hash maps. Avoid a level of reference in sequences (like for maps) and remove the last explicit destructor. Also make them mutable and improve encapsulation. Merge both isEqual functions. Merge both withMeta functions. Add optional override qualifiers, only mark as virtual the methods intended for override. --- impls/cpp/Core.cpp | 46 +++-- impls/cpp/Reader.cpp | 28 +-- impls/cpp/Types.cpp | 362 ++++++++++++++++++++----------------- impls/cpp/Types.h | 299 +++++++++--------------------- impls/cpp/step6_file.cpp | 4 +- impls/cpp/step7_quote.cpp | 6 +- impls/cpp/step8_macros.cpp | 6 +- impls/cpp/step9_try.cpp | 6 +- impls/cpp/stepA_mal.cpp | 6 +- 9 files changed, 340 insertions(+), 423 deletions(-) diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index d2d72cc6d7..cf48df4486 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -142,7 +142,7 @@ BUILTIN("=") const malValue* lhs = (*argsBegin++).ptr(); const malValue* rhs = (*argsBegin++).ptr(); - return mal::boolean(lhs->isEqualTo(rhs)); + return mal::boolean(lhs->doIsEqualTo(rhs)); } BUILTIN("apply") @@ -179,21 +179,15 @@ BUILTIN("atom") BUILTIN("concat") { - int count = 0; + auto items = new malList(); for (auto it = argsBegin; it != argsEnd; ++it) { const malSequence* seq = VALUE_CAST(name, 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(); + for (const auto &x : *seq) { + items->push_back(x); + } } - return mal::list(items); + return malValuePtr(items); } BUILTIN("conj") @@ -210,11 +204,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?") @@ -303,7 +299,7 @@ BUILTIN("get") BUILTIN("hash-map") { - return mal::hash(argsBegin, argsEnd); + return mal::hash(argsBegin, argsEnd, name); } BUILTIN("keys") @@ -346,13 +342,13 @@ BUILTIN("map") 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) = op->apply(it+i, it+i+1); + items->push_back(op->apply(it+i, it+i+1)); } - return mal::list(items); + return malValuePtr(items); } BUILTIN("meta") @@ -426,7 +422,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(); @@ -449,11 +445,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()); } @@ -549,7 +545,7 @@ BUILTIN("with-meta") CHECK_ARGS_IS(2); malValuePtr obj = *argsBegin++; malValuePtr meta = *argsBegin++; - return obj->withMeta(meta); + return obj->doWithMeta(meta); } void installCore() { diff --git a/impls/cpp/Reader.cpp b/impls/cpp/Reader.cpp index 22b94766f0..804d18194a 100644 --- a/impls/cpp/Reader.cpp +++ b/impls/cpp/Reader.cpp @@ -3,6 +3,7 @@ #include "Validation.h" #include +#include typedef std::regex Regex; @@ -115,7 +116,8 @@ 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); @@ -136,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()); + readList(tokeniser, + [&items] (malValuePtr x) { items.push_back(x); }, "}"); + return mal::hash(items.begin(), items.end(), "{ } map literal"); } return readAtom(tokeniser); } @@ -208,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) { @@ -217,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/Types.cpp b/impls/cpp/Types.cpp index eb42922f41..61eb133aa0 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -3,10 +3,6 @@ #include "Types.h" #include "Validation.h" -#include -#include -#include - // make CPPFLAGS=-DDEBUG_OBJECT_LIFETIMES #if DEBUG_OBJECT_LIFETIMES static size_t allocs = 0; @@ -50,13 +46,9 @@ namespace mal { return malValuePtr(c); }; - - malValuePtr hash(const malHash::Map& map) { - return malValuePtr(new malHash(map)); - } - - malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd) { - return malValuePtr(new malHash(argsBegin, argsEnd)); + malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, + const String& context) { + return malValuePtr(new malHash(argsBegin, argsEnd, context)); } malValuePtr integer(int64_t value) { @@ -77,37 +69,32 @@ namespace mal { 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() { @@ -128,61 +115,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.ptr()); +} + +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) -: m_map(createMap(argsBegin, argsEnd)) -{ - -} - -malHash::malHash(const malHash::Map& map) -: m_map(map) +malHash::malHash(const Map &map, malValuePtr meta) +: malValue(meta) +, m_map(map) { } @@ -190,68 +198,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::doWithMeta(malValuePtr meta) const +{ + return malValuePtr(new malHash(m_map, meta)); } malValuePtr malHash::fmap(std::function f) const { - malHash::Map map; + auto map = new malHash(); for (auto it = m_map.begin(), end = m_map.end(); it != end; ++it) { - map[it->first] = f(it->second); + 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 @@ -260,11 +264,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 + "}"; @@ -272,7 +277,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; } @@ -280,45 +289,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.ptr())) { return false; } - if (!it0->second->isEqualTo(it1->second.ptr())) { + if (!it0->second->doIsEqualTo(it1->second.ptr())) { return false; } } return true; } -malLambda::malLambda(ApplyFunc apply, - const StringVec& bindings, - malValuePtr body, malEnvPtr env) -: m_apply(apply) -, 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_apply(that.m_apply) -, 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_apply(that.m_apply) -, 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) { @@ -332,24 +341,45 @@ malValuePtr malLambda::apply(malValueIter argsBegin, 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::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 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::doWithMeta(malValuePtr meta) const +{ + return malValuePtr(new malList(begin(), end(), meta)); } String malList::print(bool readably) const @@ -372,14 +402,10 @@ malValue::~malValue() #endif } -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 @@ -393,52 +419,41 @@ 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) -{ - -} - -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).ptr())) { return false; } } return true; } +malValueIter malSequence::end() const { return m_items.end(); } malValuePtr malSequence::first() const { @@ -462,6 +477,11 @@ String printValues(malValueIter begin, malValueIter end, 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 { @@ -469,36 +489,50 @@ 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(); +} + +malSymbol::malSymbol(const String& token) : malStringBase(token) { } +bool malSymbol::doIsEqualTo(const malValue* rhs) const +{ + 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); - - return mal::vector(items); + auto items = new malVector(begin(), end()); + for ( ; argsBegin != argsEnd; ++argsBegin) { + items->push_back(*argsBegin); + } + return malValuePtr(items); } malValuePtr malVector::fmap(std::function f) const { - malValueVec* items = new malValueVec;; + auto items = new malVector(); for (const auto &x : *this) { items->push_back(f(x)); } - return mal::vector(items); + return malValuePtr(items); +} + +malValuePtr malVector::doWithMeta(malValuePtr meta) const +{ + return new malVector(begin(), end(), meta); } String malVector::print(bool readably) const diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 5cb283b409..1d8397a172 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -4,7 +4,7 @@ #include "String.h" #include -#include +#include #include class malValue; @@ -17,23 +17,16 @@ typedef RefCountedPtr malEnvPtr; class malValue : public RefCounted { public: - malValue(malValuePtr meta = NULL); virtual ~malValue(); - - malValuePtr withMeta(malValuePtr meta) const; - virtual malValuePtr doWithMeta(malValuePtr meta) const = 0; + virtual malValuePtr doWithMeta(malValuePtr meta) const; malValuePtr meta() const; - bool isTrue() const; - - bool isEqualTo(const malValue* rhs) const; - + 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 @@ -43,189 +36,108 @@ T* value_cast(const String& context, malValuePtr obj, const char* typeName); #define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value).ptr())) #define STATIC_CAST(Type, Value) (static_cast((Value).ptr())) -#define WITH_META(Type) \ - virtual malValuePtr doWithMeta(malValuePtr meta) const { \ - return new Type(*this, meta); \ - } \ - 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 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(); - - 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 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) { } - + malVector(); + malVector(malValueIter begin, malValueIter end, malValuePtr meta = NULL); malValuePtr fmap(std::function f) const; - virtual String print(bool readably) const; - - virtual malValuePtr conj(malValueIter argsBegin, - malValueIter argsEnd) const; - - WITH_META(malVector); + 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); - malHash(const malHash::Map& map); - malHash(const malHash& that, malValuePtr meta) - : malValue(meta), m_map(that.m_map) { } - + 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; @@ -233,15 +145,23 @@ class malHash : public malValue { 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; + 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 { @@ -249,28 +169,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; @@ -280,28 +184,19 @@ class malLambda : public malApplicable { public: typedef std::function ApplyFunc; malLambda(ApplyFunc apply, const StringVec& bindings, malValuePtr body, - malEnvPtr env); - malLambda(const malLambda& that, malValuePtr meta); - malLambda(const malLambda& that, bool isMacro); + 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; StringVec getBindings() const; - malValuePtr getBody() const { return m_body; } + 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; @@ -313,23 +208,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; @@ -340,8 +222,8 @@ namespace mal { malValuePtr boolean(bool value); malValuePtr builtin(const String& name, malBuiltIn::ApplyFunc handler); malValuePtr falseValue(); - malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd); - malValuePtr hash(const malHash::Map& map); + malValuePtr hash(malValueIter argsBegin, malValueIter argsEnd, + const String& context); malValuePtr integer(int64_t value); malValuePtr integer(const String& token); malValuePtr keyword(const String& token); @@ -349,7 +231,7 @@ namespace mal { 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); @@ -357,7 +239,6 @@ namespace mal { malValuePtr string(const String& token); malValuePtr symbol(const String& token); malValuePtr trueValue(); - malValuePtr vector(malValueVec* items); malValuePtr vector(malValueIter begin, malValueIter end); }; diff --git a/impls/cpp/step6_file.cpp b/impls/cpp/step6_file.cpp index e13bbe39dd..7b504a679e 100644 --- a/impls/cpp/step6_file.cpp +++ b/impls/cpp/step6_file.cpp @@ -48,11 +48,11 @@ String rep(const String& input, malEnvPtr env) 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)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) diff --git a/impls/cpp/step7_quote.cpp b/impls/cpp/step7_quote.cpp index ce9b28c609..0c267c1a28 100644 --- a/impls/cpp/step7_quote.cpp +++ b/impls/cpp/step7_quote.cpp @@ -49,11 +49,11 @@ String rep(const String& input, malEnvPtr env) 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)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -220,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"); diff --git a/impls/cpp/step8_macros.cpp b/impls/cpp/step8_macros.cpp index dc39a3e9fd..cd19d2fc91 100644 --- a/impls/cpp/step8_macros.cpp +++ b/impls/cpp/step8_macros.cpp @@ -51,11 +51,11 @@ String rep(const String& input, malEnvPtr env) 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)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -235,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"); diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index a74c9e4c2d..fec3ea6e92 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -50,11 +50,11 @@ String rep(const String& input, malEnvPtr env) 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)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -266,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"); diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 644d8244ca..98b6fc2032 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -51,11 +51,11 @@ String rep(const String& input, malEnvPtr env) 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)); + env->set("*ARGV*", malValuePtr(args)); } malValuePtr READ(const String& input) @@ -267,7 +267,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"); From 757bf674ce35a624166f7819d092d2252578684e Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Mon, 24 Aug 2026 18:37:47 +0200 Subject: [PATCH 18/19] c++: switch to the Boehm garbage collector library This fixes the memory leaks caused by cycles like (let* [f (fn* [] nil)] nil) --- impls/cpp/Core.cpp | 8 +++-- impls/cpp/Dockerfile | 2 +- impls/cpp/Environment.cpp | 17 +-------- impls/cpp/Environment.h | 14 +++++--- impls/cpp/Makefile | 2 +- impls/cpp/README.md | 15 +++++++- impls/cpp/RefCountedPtr.h | 75 --------------------------------------- impls/cpp/Types.cpp | 32 +++++------------ impls/cpp/Types.h | 20 ++++++----- impls/cpp/step2_eval.cpp | 8 +++-- 10 files changed, 55 insertions(+), 138 deletions(-) delete mode 100644 impls/cpp/RefCountedPtr.h diff --git a/impls/cpp/Core.cpp b/impls/cpp/Core.cpp index cf48df4486..35c71e7c51 100644 --- a/impls/cpp/Core.cpp +++ b/impls/cpp/Core.cpp @@ -4,6 +4,8 @@ #include "String.h" #include "Validation.h" +#include + #include #include #include @@ -21,7 +23,7 @@ checkArgsAtLeast(name.c_str(), expected, \ std::distance(argsBegin, argsEnd)) -std::vector handlers; +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. @@ -139,8 +141,8 @@ 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->doIsEqualTo(rhs)); } 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 2528f8751b..affc7a5f1f 100644 --- a/impls/cpp/Environment.cpp +++ b/impls/cpp/Environment.cpp @@ -2,17 +2,9 @@ #include "Environment.h" #include "Validation.h" -// make CPPFLAGS=-DDEBUG_ENV_LIFETIMES -#if DEBUG_ENV_LIFETIMES -static size_t allocs = 0; -#endif - malEnv::malEnv(malEnvPtr outer) : m_outer(outer) { -#if DEBUG_ENV_LIFETIMES - TRACE("Create env %lu %p outer=%p\n", ++allocs, this, m_outer.ptr()); -#endif } malEnv::malEnv(malEnvPtr outer, const StringVec& bindings, @@ -35,16 +27,9 @@ malEnv::malEnv(malEnvPtr outer, const StringVec& bindings, MAL_CHECK(it == argsEnd, "Too many parameters"); } -malEnv::~malEnv() -{ -#if DEBUG_ENV_LIFETIMES - TRACE("Destroy env %lu %p outer=%p\n", --allocs, this, m_outer.ptr()); -#endif -} - malValuePtr malEnv::get(const String& symbol) const { - for (auto env = this; env; env = env->m_outer.ptr()) { + 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; diff --git a/impls/cpp/Environment.h b/impls/cpp/Environment.h index 4762190ae1..1c915395aa 100644 --- a/impls/cpp/Environment.h +++ b/impls/cpp/Environment.h @@ -1,12 +1,14 @@ #pragma once -#include "RefCountedPtr.h" #include "String.h" #include "Types.h" +#include +#include + #include -class malEnv : public RefCounted { +class malEnv : public gc { public: malEnv(malEnvPtr outer = NULL); malEnv(malEnvPtr outer, @@ -14,15 +16,17 @@ class malEnv : public RefCounted { malValueIter argsBegin, malValueIter argsEnd); - ~malEnv(); - malValuePtr get(const String& symbol) const; // NULL means not found malValuePtr set(const String& symbol, malValuePtr value); private: - typedef std::unordered_map Map; + typedef std::unordered_map, std::equal_to, + gc_allocator>> + Map; Map m_map; const malEnvPtr m_outer; }; diff --git a/impls/cpp/Makefile b/impls/cpp/Makefile index 07a91ab8e1..13664b0ed3 100644 --- a/impls/cpp/Makefile +++ b/impls/cpp/Makefile @@ -34,7 +34,7 @@ STDCXX = -std=c++11 CPPFLAGS += $(INCPATHS) CXXFLAGS += $(OPT) $(WARN) $(DEBUG) $(STDCXX) -LDLIBS += $(LIBPATHS) -lreadline -lhistory +LDLIBS += $(LIBPATHS) -lreadline -lhistory -lgccpp -lgc .PHONY: all clean dist 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/RefCountedPtr.h b/impls/cpp/RefCountedPtr.h deleted file mode 100644 index 3bc8bbe7f4..0000000000 --- a/impls/cpp/RefCountedPtr.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef INCLUDE_REFCOUNTEDPTR_H -#define INCLUDE_REFCOUNTEDPTR_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/Types.cpp b/impls/cpp/Types.cpp index 61eb133aa0..14bf21e9cd 100644 --- a/impls/cpp/Types.cpp +++ b/impls/cpp/Types.cpp @@ -1,17 +1,11 @@ #include "Debug.h" -#include "Environment.h" #include "Types.h" #include "Validation.h" -// make CPPFLAGS=-DDEBUG_OBJECT_LIFETIMES -#if DEBUG_OBJECT_LIFETIMES -static size_t allocs = 0; -#endif - template T* value_cast(const String& context, malValuePtr obj, const char* typeName) { - T* dest = dynamic_cast(obj.ptr()); + 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; @@ -157,7 +151,7 @@ String malConstant::print(bool) const { return m_name; } bool malHash::malKeyEqual::operator()(const malValuePtr& lhs, const malValuePtr& rhs) const { - return lhs->doIsEqualTo(rhs.ptr()); + return lhs->doIsEqualTo(rhs); } size_t malHash::malKeyHash::operator()(const malValuePtr& key) const @@ -289,10 +283,10 @@ 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->doIsEqualTo(it1->first.ptr())) { + if (!it0->first->doIsEqualTo(it1->first)) { return false; } - if (!it0->second->doIsEqualTo(it1->second.ptr())) { + if (!it0->second->doIsEqualTo(it1->second)) { return false; } } @@ -390,16 +384,6 @@ String malList::print(bool readably) const malValue::malValue(malValuePtr meta) : m_meta(meta) { -#if DEBUG_OBJECT_LIFETIMES - TRACE("Create form %lu %p\n", ++allocs, this); -#endif -} - -malValue::~malValue() -{ -#if DEBUG_OBJECT_LIFETIMES - TRACE("Destroy form %lu %p\n", --allocs, this); -#endif } bool malValue::doIsEqualTo(const malValue*) const { return false; } @@ -410,13 +394,13 @@ malValuePtr malValue::doWithMeta(malValuePtr) const 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; + return m_meta == NULL ? mal::nilValue() : m_meta; } malSequence::malSequence() @@ -447,7 +431,7 @@ bool malSequence::doIsEqualTo(const malValue* rhs) const it1 = rhsSeq->begin(), end = m_items.end(); it0 != end; ++it0, ++it1) { - if (!(*it0)->doIsEqualTo((*it1).ptr())) { + if (!(*it0)->doIsEqualTo((*it1))) { return false; } } diff --git a/impls/cpp/Types.h b/impls/cpp/Types.h index 1d8397a172..ce44b95b5b 100644 --- a/impls/cpp/Types.h +++ b/impls/cpp/Types.h @@ -1,23 +1,24 @@ #pragma once -#include "RefCountedPtr.h" #include "String.h" +#include +#include + #include #include #include class malValue; -typedef RefCountedPtr malValuePtr; -typedef std::vector malValueVec; +typedef malValue* malValuePtr; +typedef std::vector> malValueVec; typedef malValueVec::const_iterator malValueIter; class malEnv; // Environment.h -typedef RefCountedPtr malEnvPtr; +typedef malEnv* malEnvPtr; -class malValue : public RefCounted { +class malValue : public gc { public: - virtual ~malValue(); virtual malValuePtr doWithMeta(malValuePtr meta) const; malValuePtr meta() const; bool isTrue() const; @@ -33,8 +34,8 @@ template T* value_cast(const String& context, malValuePtr obj, const char* typeName); #define VALUE_CAST(context, Type, Value) value_cast(context, Value, #Type) -#define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value).ptr())) -#define STATIC_CAST(Type, Value) (static_cast((Value).ptr())) +#define DYNAMIC_CAST(Type, Value) (dynamic_cast((Value))) +#define STATIC_CAST(Type, Value) (static_cast((Value))) class malConstant : public malValue { public: @@ -156,7 +157,8 @@ class malHash : public malValue { bool operator()(const malValuePtr& lhs, const malValuePtr& rhs) const; }; typedef std::unordered_map Map; + malKeyEqual, gc_allocator>> + Map; void addToMap(malValueIter argsBegin, malValueIter argsEnd, const String& context); malHash(); diff --git a/impls/cpp/step2_eval.cpp b/impls/cpp/step2_eval.cpp index cba4f8da0b..53f65efd82 100644 --- a/impls/cpp/step2_eval.cpp +++ b/impls/cpp/step2_eval.cpp @@ -1,16 +1,18 @@ #include "Reader.h" #include "ReadLine.h" -#include "RefCountedPtr.h" #include "String.h" #include "Types.h" #include "Validation.h" +#include + #include #include class malEnv - : public std::unordered_map, - public RefCounted + : public std::unordered_map, + std::equal_to, + gc_allocator>> { }; From d8f0ef52e43e450277f3f2c1cb5306ac273277a3 Mon Sep 17 00:00:00 2001 From: Nicolas Boulenguez Date: Tue, 25 Aug 2026 22:46:48 +0200 Subject: [PATCH 19/19] c++: improve the error message for fix (try* nil ()) --- impls/cpp/step9_try.cpp | 7 +++---- impls/cpp/stepA_mal.cpp | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/impls/cpp/step9_try.cpp b/impls/cpp/step9_try.cpp index fec3ea6e92..ee9f86e541 100644 --- a/impls/cpp/step9_try.cpp +++ b/impls/cpp/step9_try.cpp @@ -186,11 +186,10 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } checkArgsIs("try*", 2, argCount); 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("catch*", 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 diff --git a/impls/cpp/stepA_mal.cpp b/impls/cpp/stepA_mal.cpp index 98b6fc2032..7dc5435f4d 100644 --- a/impls/cpp/stepA_mal.cpp +++ b/impls/cpp/stepA_mal.cpp @@ -187,11 +187,10 @@ malValuePtr EVAL(malValuePtr ast, malEnvPtr env) } checkArgsIs("try*", 2, argCount); 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("catch*", 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