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) <noreply@anthropic.com>
This commit is contained in:
leftibot 2026-04-13 18:44:24 -06:00
parent 7aaceab4e5
commit ff06e1f0c7
2 changed files with 24 additions and 1 deletions

View File

@ -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");
}
};

View File

@ -1877,3 +1877,26 @@ TEST_CASE("Namespace block with var declarations") {
CHECK(chai.eval<double>("config::pi") == Approx(3.14));
CHECK(chai.eval<std::string>("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);
}