From ff06e1f0c7ae01938095749886cb2dc91f82323b Mon Sep 17 00:00:00 2001 From: leftibot Date: Mon, 13 Apr 2026 18:44:24 -0600 Subject: [PATCH] Address review: reject non-declaration statements inside namespace blocks Only def, var, auto, and global declarations are now allowed inside namespace { } blocks. Arbitrary expressions, assignments, and function calls are rejected with an eval_error. Added compiled tests verifying that expressions, function calls, and assignments are rejected. Requested by @lefticus in PR #675 review. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../chaiscript/language/chaiscript_eval.hpp | 2 +- unittests/compiled_tests.cpp | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/include/chaiscript/language/chaiscript_eval.hpp b/include/chaiscript/language/chaiscript_eval.hpp index f380c12b..2c3b12ad 100644 --- a/include/chaiscript/language/chaiscript_eval.hpp +++ b/include/chaiscript/language/chaiscript_eval.hpp @@ -948,7 +948,7 @@ namespace chaiscript { const auto &var_name = stmt.children[0]->text; target_ns[var_name] = Boxed_Value(); } else { - stmt.eval(t_ss); + throw exception::eval_error("Only declarations (def, var, auto, global) are allowed inside namespace blocks"); } }; diff --git a/unittests/compiled_tests.cpp b/unittests/compiled_tests.cpp index a3e08159..0b76df61 100644 --- a/unittests/compiled_tests.cpp +++ b/unittests/compiled_tests.cpp @@ -1877,3 +1877,26 @@ TEST_CASE("Namespace block with var declarations") { CHECK(chai.eval("config::pi") == Approx(3.14)); CHECK(chai.eval("config::name") == "hello"); } + +TEST_CASE("Namespace block rejects non-declaration statements") { + chaiscript::ChaiScript_Basic chai(create_chaiscript_stdlib(), create_chaiscript_parser()); + + CHECK_THROWS_AS(chai.eval(R"( + namespace bad { + 1 + 2 + } + )"), chaiscript::exception::eval_error); + + CHECK_THROWS_AS(chai.eval(R"( + namespace bad { + print("hello") + } + )"), chaiscript::exception::eval_error); + + CHECK_THROWS_AS(chai.eval(R"( + var x = 5 + namespace bad { + x = 10 + } + )"), chaiscript::exception::eval_error); +}