Files
mbs/src/script.cpp
Allan K. Koech cda2e9daa7 fix: harden arithmetic, string ops, and lexer error handling
- S4: add isfinite checks after all arithmetic ops (Add, Sub, Mul, Div,
  Pow, Neg) so NaN/Infinity can never enter JSON output
- S5: fix is_integral_number INT64_MAX boundary check to eliminate
  undefined behaviour from double rounding
- S6: cap string concatenation result at MAX_STRING_SIZE (1MB)
- S7: add optional max_source_length parameter to test/eval_val/eval_true
- S8: catch std::out_of_range in lexNumber() and report a descriptive
  ParseError instead of a bare 'stod' message
2026-08-20 14:00:17 +03:00

63 lines
1.9 KiB
C++

#include "../include/mbs/script.hpp"
#include "evaluator.hpp"
#include "parser.hpp"
#include <exception>
namespace mbs {
TestResult test(std::string_view source, std::size_t max_source_length) {
try {
if (max_source_length > 0 && source.size() > max_source_length) {
return TestResult{false, "source exceeds maximum length", std::nullopt};
}
const auto ast = parse(source);
if (const auto err = semantic_check(*ast); err.has_value()) {
return TestResult{false, *err, std::nullopt};
}
return TestResult{true, {}, std::nullopt};
} catch (const ParseError& ex) {
return TestResult{false, ex.what(), ex.loc};
} catch (const std::exception& ex) {
return TestResult{false, ex.what(), std::nullopt};
}
}
EvalValueResult eval_val(const std::string_view source, const nlohmann::json& context,
std::size_t max_source_length) {
try {
if (max_source_length > 0 && source.size() > max_source_length) {
return EvalErr{"source exceeds maximum length", std::nullopt};
}
const auto ast = parse(source);
if (const auto err = semantic_check(*ast); err.has_value()) {
return EvalErr{*err, std::nullopt};
}
return EvalOk{eval_expr(*ast, context)};
} catch (const ParseError& ex) {
return EvalErr{ex.what(), ex.loc};
} catch (const std::exception& ex) {
return EvalErr{ex.what(), std::nullopt};
}
}
EvalBoolResult eval_true(const std::string_view source, const nlohmann::json& context,
std::size_t max_source_length) {
const auto r = eval_val(source, context, max_source_length);
// Check if it resulted in an error
if (std::holds_alternative<EvalErr>(r)) {
const auto&[error, loc] = std::get<EvalErr>(r);
return EvalBoolResult{ false, false, error, loc};
}
// If all executed OK
const auto&[value] = std::get<EvalOk>(r);
return EvalBoolResult{true, json_truthy(value), {}, std::nullopt};
}
} // namespace mbs