Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
Vendored
+1
-1
@@ -7,7 +7,7 @@ The implementation can be found in the `common/jinja` directory.
|
||||
## Key Features
|
||||
|
||||
- Input marking: security against special token injection
|
||||
- Decoupled from `nlohmann::json`: this dependency is only used for JSON-to-internal type translation and is completely optional
|
||||
- Decoupled from `Json`: this dependency is only used for JSON-to-internal type translation and is completely optional
|
||||
- Minimal primitive types: int, float, bool, string, array, object, none, undefined
|
||||
- Detailed logging: allow source tracing on error
|
||||
- Clean architecture: workarounds are applied to input data before entering the runtime (see `common/chat.cpp`)
|
||||
|
||||
Vendored
+12
-2
@@ -4,20 +4,24 @@
|
||||
|
||||
// note: the json dependency is only for defining input in a convenient way
|
||||
// we can remove it in the future when we figure out a better way to define inputs using jinja::value
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <functional>
|
||||
#include <sstream>
|
||||
|
||||
#define FILENAME "jinja-caps"
|
||||
|
||||
using json = nlohmann::ordered_json;
|
||||
using json = rad::Json;
|
||||
|
||||
namespace jinja {
|
||||
|
||||
using caps_json_fn = std::function<json()>;
|
||||
using caps_analyze_fn = std::function<void(bool, value &, value &)>;
|
||||
|
||||
// RADIANCE: where caps_get collects the first exception of a probe that carried tools
|
||||
// (caps::probe_error).
|
||||
static thread_local std::string * caps_probe_error = nullptr;
|
||||
|
||||
static void caps_try_execute(jinja::program & prog,
|
||||
const caps_json_fn & messages_fn,
|
||||
const caps_json_fn & tools_fn,
|
||||
@@ -45,6 +49,10 @@ static void caps_try_execute(jinja::program & prog,
|
||||
success = true;
|
||||
} catch (const std::exception & e) {
|
||||
JJ_DEBUG("Exception during execution: %s", e.what());
|
||||
if (caps_probe_error && caps_probe_error->empty() && is_val<value_array>(tools) &&
|
||||
!tools->as_array().empty()) {
|
||||
*caps_probe_error = e.what();
|
||||
}
|
||||
result = "";
|
||||
// ignore exceptions during capability analysis
|
||||
}
|
||||
@@ -90,6 +98,7 @@ std::string caps::to_string() const {
|
||||
|
||||
caps caps_get(jinja::program & prog) {
|
||||
caps result;
|
||||
caps_probe_error = &result.probe_error;
|
||||
|
||||
static const auto has_op = [](value & v, const std::string & op_name) {
|
||||
return v->stats.ops.find(op_name) != v->stats.ops.end();
|
||||
@@ -475,6 +484,7 @@ caps caps_get(jinja::program & prog) {
|
||||
|
||||
JJ_DEBUG("%s\n", result.to_string().c_str());
|
||||
|
||||
caps_probe_error = nullptr;
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
Vendored
+5
@@ -20,6 +20,11 @@ struct caps {
|
||||
|
||||
bool supports_object_arguments = false;
|
||||
|
||||
// RADIANCE: what the first probe render that threw said, empty when none did. The probes
|
||||
// ignore exceptions, so a template calling something this engine lacks and a template
|
||||
// without tool support both come back supports_tools = false; this tells them apart.
|
||||
std::string probe_error;
|
||||
|
||||
// for reporting on server
|
||||
std::map<std::string, bool> to_map() const;
|
||||
|
||||
|
||||
+104
-69
@@ -18,16 +18,27 @@ void enable_debug(bool enable) {
|
||||
g_jinja_debug = enable;
|
||||
}
|
||||
|
||||
/* A block's statement results as one string value. A lone string result already is that
|
||||
* value -- regathering it would copy (or move) its parts into a fresh string for nothing,
|
||||
* and blocks with a single output statement are the common shape inside a message loop. */
|
||||
static value_string gather_array_result(const value_array & result) {
|
||||
if (result->val_arr.size() == 1) {
|
||||
if (auto s = std::dynamic_pointer_cast<value_string_t>(result->val_arr[0])) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
value_string str = mk_val<value_string>();
|
||||
gather_string_parts_recursive(result, str);
|
||||
return str;
|
||||
}
|
||||
|
||||
static value_string exec_statements(const statements & stmts, context & ctx) {
|
||||
auto result = mk_val<value_array>();
|
||||
for (const auto & stmt : stmts) {
|
||||
JJ_DEBUG("Executing statement of type %s", stmt->type().c_str());
|
||||
result->push_back(stmt->execute(ctx));
|
||||
}
|
||||
// convert to string parts
|
||||
value_string str = mk_val<value_string>();
|
||||
gather_string_parts_recursive(result, str);
|
||||
return str;
|
||||
return gather_array_result(result);
|
||||
}
|
||||
|
||||
static std::string get_line_col(const std::string & source, size_t pos) {
|
||||
@@ -82,14 +93,17 @@ value statement::execute(context & ctx) {
|
||||
|
||||
value identifier::execute_impl(context & ctx) {
|
||||
auto it = ctx.get_val(val);
|
||||
auto builtins = global_builtins();
|
||||
if (!it->is_undefined()) {
|
||||
if (ctx.is_get_stats) {
|
||||
value_t::stats_t::mark_used(it);
|
||||
}
|
||||
JJ_DEBUG("Identifier '%s' found, type = %s", val.c_str(), it->type().c_str());
|
||||
return it;
|
||||
} else if (builtins.find(val) != builtins.end()) {
|
||||
}
|
||||
// By reference, and only on the miss path: this used to copy the whole builtins map
|
||||
// (every std::function in it) for every identifier evaluated.
|
||||
const auto & builtins = global_builtins();
|
||||
if (builtins.find(val) != builtins.end()) {
|
||||
JJ_DEBUG("Identifier '%s' found in builtins", val.c_str());
|
||||
return mk_val<value_func>(val, builtins.at(val));
|
||||
} else {
|
||||
@@ -139,8 +153,8 @@ value binary_expression::execute_impl(context & ctx) {
|
||||
JJ_DEBUG("%s", "Workaround: treating null/undefined as empty string for string concatenation");
|
||||
string left_str = is_left_null ? string() : left_val->as_string();
|
||||
string right_str = is_right_null ? string() : right_val->as_string();
|
||||
auto output = left_str.append(right_str);
|
||||
res = mk_val<value_string>(std::move(output));
|
||||
left_str.append(right_str);
|
||||
res = mk_val<value_string>(std::move(left_str));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -245,7 +259,8 @@ value binary_expression::execute_impl(context & ctx) {
|
||||
if ((is_val<value_string>(left_val) || is_val<value_string>(right_val)) &&
|
||||
(op.value == "~" || op.value == "+")) {
|
||||
JJ_DEBUG("String concatenation with %s operator", op.value.c_str());
|
||||
auto output = left_val->as_string().append(right_val->as_string());
|
||||
string output = left_val->as_string();
|
||||
output.append(right_val->as_string());
|
||||
auto res = mk_val<value_string>();
|
||||
res->val_str = std::move(output);
|
||||
return res;
|
||||
@@ -263,7 +278,7 @@ value binary_expression::execute_impl(context & ctx) {
|
||||
return res;
|
||||
}
|
||||
for (int64_t i = 0; i < repeat; ++i) {
|
||||
res->val_str = res->val_str.append(str);
|
||||
res->val_str.append(str);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
@@ -299,7 +314,7 @@ static value try_builtin_func(context & ctx, const std::string & name, value & i
|
||||
value_t::stats_t::mark_used(input);
|
||||
input->stats.ops.insert(name);
|
||||
}
|
||||
auto builtins = input->get_builtins();
|
||||
const auto & builtins = input->get_builtins();
|
||||
auto it = builtins.find(name);
|
||||
if (it != builtins.end()) {
|
||||
JJ_DEBUG("Binding built-in '%s'", name.c_str());
|
||||
@@ -441,7 +456,7 @@ value unary_expression::execute_impl(context & ctx) {
|
||||
value if_statement::execute_impl(context & ctx) {
|
||||
value test_val = test->execute(ctx);
|
||||
|
||||
auto out = mk_val<value_array>();
|
||||
auto out = mk_val<value_stmt_results>();
|
||||
if (test_val->as_bool()) {
|
||||
for (auto & stmt : body) {
|
||||
JJ_DEBUG("IF --> Executing THEN body, current block: %s", stmt->type().c_str());
|
||||
@@ -453,10 +468,7 @@ value if_statement::execute_impl(context & ctx) {
|
||||
out->push_back(stmt->execute(ctx));
|
||||
}
|
||||
}
|
||||
// convert to string parts
|
||||
value_string str = mk_val<value_string>();
|
||||
gather_string_parts_recursive(out, str);
|
||||
return str;
|
||||
return out;
|
||||
}
|
||||
|
||||
value for_statement::execute_impl(context & ctx) {
|
||||
@@ -517,31 +529,36 @@ value for_statement::execute_impl(context & ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::function<void(context &)>> scope_update_fns;
|
||||
|
||||
std::vector<value> filtered_items;
|
||||
for (size_t i = 0; i < items.size(); ++i) {
|
||||
context loop_scope(scope);
|
||||
|
||||
value current = items[i];
|
||||
|
||||
std::function<void(context&)> scope_update_fn = [](context &) { /* no-op */};
|
||||
// Bind the loop variable(s) for items[i] in a context. One lambda for the whole loop:
|
||||
// this used to build a std::function per item (and a copied scope to test it on, selected
|
||||
// or not), which made filtering cost more than the iterations it sets up.
|
||||
auto apply_loop_var = [&](context & c, size_t i) {
|
||||
if (is_stmt<identifier>(loopvar)) {
|
||||
auto id = cast_stmt<identifier>(loopvar)->val;
|
||||
|
||||
if (is_val<value_object>(iterable_val)) {
|
||||
// case example: {% for key in dict %}
|
||||
current = items[i]->as_array()[0];
|
||||
scope_update_fn = [id, &items, i](context & ctx) {
|
||||
ctx.set_val(id, items[i]->as_array()[0]);
|
||||
};
|
||||
} else {
|
||||
// case example: {% for item in list %}
|
||||
scope_update_fn = [id, &items, i](context & ctx) {
|
||||
ctx.set_val(id, items[i]);
|
||||
};
|
||||
// {% for key in dict %} binds the key, {% for item in list %} the item.
|
||||
c.set_val(id, is_val<value_object>(iterable_val) ? items[i]->as_array()[0] : items[i]);
|
||||
} else {
|
||||
auto tuple = cast_stmt<tuple_literal>(loopvar);
|
||||
auto & c_arr = items[i]->as_array();
|
||||
for (size_t j = 0; j < tuple->val.size(); ++j) {
|
||||
if (!is_stmt<identifier>(tuple->val[j])) {
|
||||
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
|
||||
}
|
||||
auto id = cast_stmt<identifier>(tuple->val[j])->val;
|
||||
c.set_val(id, c_arr[j]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
std::vector<value> filtered_items;
|
||||
std::vector<size_t> filtered_idx;
|
||||
for (size_t i = 0; i < items.size(); ++i) {
|
||||
value current = items[i];
|
||||
|
||||
if (is_stmt<identifier>(loopvar)) {
|
||||
if (is_val<value_object>(iterable_val)) {
|
||||
current = items[i]->as_array()[0];
|
||||
}
|
||||
} else if (is_stmt<tuple_literal>(loopvar)) {
|
||||
// case example: {% for key, value in dict %}
|
||||
auto tuple = cast_stmt<tuple_literal>(loopvar);
|
||||
@@ -552,23 +569,13 @@ value for_statement::execute_impl(context & ctx) {
|
||||
if (tuple->val.size() != c_arr.size()) {
|
||||
throw std::runtime_error(std::string("Too ") + (tuple->val.size() > c_arr.size() ? "few" : "many") + " items to unpack");
|
||||
}
|
||||
scope_update_fn = [tuple, &items, i](context & ctx) {
|
||||
auto & c_arr = items[i]->as_array();
|
||||
for (size_t j = 0; j < tuple->val.size(); ++j) {
|
||||
if (!is_stmt<identifier>(tuple->val[j])) {
|
||||
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
|
||||
}
|
||||
auto id = cast_stmt<identifier>(tuple->val[j])->val;
|
||||
ctx.set_val(id, c_arr[j]);
|
||||
}
|
||||
};
|
||||
|
||||
} else {
|
||||
throw std::runtime_error("Invalid loop variable(s): " + loopvar->type());
|
||||
}
|
||||
|
||||
if (select_expr && test_expr) {
|
||||
scope_update_fn(loop_scope);
|
||||
context loop_scope(scope);
|
||||
apply_loop_var(loop_scope, i);
|
||||
value test_val = test_expr->execute(loop_scope);
|
||||
if (!test_val->as_bool()) {
|
||||
continue;
|
||||
@@ -576,28 +583,45 @@ value for_statement::execute_impl(context & ctx) {
|
||||
}
|
||||
JJ_DEBUG("For loop: adding item type %s at index %zu", current->type().c_str(), i);
|
||||
filtered_items.push_back(current);
|
||||
scope_update_fns.push_back(scope_update_fn);
|
||||
filtered_idx.push_back(i);
|
||||
}
|
||||
JJ_DEBUG("For loop: %zu items after filtering", filtered_items.size());
|
||||
|
||||
auto result = mk_val<value_array>();
|
||||
auto result = mk_val<value_stmt_results>();
|
||||
|
||||
// One loop object for the whole loop, its fields replaced per iteration (as in Jinja2,
|
||||
// where `loop` is one context object whose counters move): a fresh object per iteration
|
||||
// was nine hash nodes and a bucket array allocated to describe a counter.
|
||||
value_object loop_obj;
|
||||
if (!filtered_items.empty()) {
|
||||
loop_obj = mk_val<value_object>();
|
||||
loop_obj->has_builtins = false; // loop object has no builtins
|
||||
loop_obj->insert_new("index", mk_val<value_int>(1));
|
||||
loop_obj->insert_new("index0", mk_val<value_int>(0));
|
||||
loop_obj->insert_new("revindex", mk_val<value_int>(filtered_items.size()));
|
||||
loop_obj->insert_new("revindex0", mk_val<value_int>(filtered_items.size() - 1));
|
||||
loop_obj->insert_new("first", mk_val<value_bool>(true));
|
||||
loop_obj->insert_new("last", mk_val<value_bool>(filtered_items.size() == 1));
|
||||
loop_obj->insert_new("length", mk_val<value_int>(filtered_items.size()));
|
||||
loop_obj->insert_new("previtem", mk_val<value_undefined>("previtem"));
|
||||
loop_obj->insert_new("nextitem", filtered_items.size() > 1 ? filtered_items[1] : mk_val<value_undefined>("nextitem"));
|
||||
}
|
||||
|
||||
bool noIteration = true;
|
||||
for (size_t i = 0; i < filtered_items.size(); i++) {
|
||||
JJ_DEBUG("For loop iteration %zu/%zu", i + 1, filtered_items.size());
|
||||
value_object loop_obj = mk_val<value_object>();
|
||||
loop_obj->has_builtins = false; // loop object has no builtins
|
||||
loop_obj->insert("index", mk_val<value_int>(i + 1));
|
||||
loop_obj->insert("index0", mk_val<value_int>(i));
|
||||
loop_obj->insert("revindex", mk_val<value_int>(filtered_items.size() - i));
|
||||
loop_obj->insert("revindex0", mk_val<value_int>(filtered_items.size() - i - 1));
|
||||
loop_obj->insert("first", mk_val<value_bool>(i == 0));
|
||||
loop_obj->insert("last", mk_val<value_bool>(i == filtered_items.size() - 1));
|
||||
loop_obj->insert("length", mk_val<value_int>(filtered_items.size()));
|
||||
loop_obj->insert("previtem", i > 0 ? filtered_items[i - 1] : mk_val<value_undefined>("previtem"));
|
||||
loop_obj->insert("nextitem", i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem"));
|
||||
if (i > 0) {
|
||||
loop_obj->at("index") = mk_val<value_int>(i + 1);
|
||||
loop_obj->at("index0") = mk_val<value_int>(i);
|
||||
loop_obj->at("revindex") = mk_val<value_int>(filtered_items.size() - i);
|
||||
loop_obj->at("revindex0") = mk_val<value_int>(filtered_items.size() - i - 1);
|
||||
loop_obj->at("first") = mk_val<value_bool>(false);
|
||||
loop_obj->at("last") = mk_val<value_bool>(i == filtered_items.size() - 1);
|
||||
loop_obj->at("previtem") = filtered_items[i - 1];
|
||||
loop_obj->at("nextitem") = i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem");
|
||||
}
|
||||
scope.set_val("loop", loop_obj);
|
||||
scope_update_fns[i](scope);
|
||||
apply_loop_var(scope, filtered_idx[i]);
|
||||
try {
|
||||
for (auto & stmt : body) {
|
||||
value val = stmt->execute(scope);
|
||||
@@ -619,10 +643,7 @@ value for_statement::execute_impl(context & ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
// convert to string parts
|
||||
value_string str = mk_val<value_string>();
|
||||
gather_string_parts_recursive(result, str);
|
||||
return str;
|
||||
return result;
|
||||
}
|
||||
|
||||
value set_statement::execute_impl(context & ctx) {
|
||||
@@ -790,8 +811,7 @@ value member_expression::execute_impl(context & ctx) {
|
||||
if (!is_stmt<identifier>(this->property)) {
|
||||
throw std::runtime_error("Static member property must be an identifier");
|
||||
}
|
||||
property = mk_val<value_string>(cast_stmt<identifier>(this->property)->val);
|
||||
std::string prop = property->as_string().str();
|
||||
const std::string & prop = cast_stmt<identifier>(this->property)->val;
|
||||
JJ_DEBUG("Member expression, object type %s, static property '%s'", object->type().c_str(), prop.c_str());
|
||||
|
||||
// behavior of jinja2: obj having prop as a built-in function AND 'prop', as an object key,
|
||||
@@ -803,6 +823,21 @@ value member_expression::execute_impl(context & ctx) {
|
||||
if (!is_val<value_undefined>(val)) {
|
||||
return val;
|
||||
}
|
||||
if (is_val<value_object>(object)) {
|
||||
// The common case (a message field): look the name up directly instead of
|
||||
// allocating a key value and hashing it, then trying the builtins a second time.
|
||||
value out = mk_val<value_undefined>("object_property");
|
||||
out = object->at(prop, out);
|
||||
if (ctx.is_get_stats && out && object) {
|
||||
value prop_val = mk_val<value_string>(prop);
|
||||
value_t::stats_t::mark_used(out);
|
||||
value_t::stats_t::mark_used(object);
|
||||
value_t::stats_t::mark_used(prop_val);
|
||||
object->stats.ops.insert("object_access");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
property = mk_val<value_string>(prop);
|
||||
// else, fallthrough to normal property access below
|
||||
}
|
||||
|
||||
|
||||
Vendored
+103
-27
@@ -69,18 +69,17 @@ struct context {
|
||||
|
||||
context(const context & parent) : context() {
|
||||
// inherit variables (for example, when entering a new scope)
|
||||
auto & pvar = parent.env->as_ordered_object();
|
||||
for (const auto & pair : pvar) {
|
||||
set_val(pair.first, pair.second);
|
||||
}
|
||||
env->copy_entries_from(*parent.env);
|
||||
current_time = parent.current_time;
|
||||
is_get_stats = parent.is_get_stats;
|
||||
src = parent.src;
|
||||
}
|
||||
|
||||
value get_val(const std::string & name) {
|
||||
value default_val = mk_val<value_undefined>(name);
|
||||
return env->at(name, default_val);
|
||||
if (value * v = env->find_string_key(name)) {
|
||||
return *v;
|
||||
}
|
||||
return mk_val<value_undefined>(name);
|
||||
}
|
||||
|
||||
void set_val(const std::string & name, const value & val) {
|
||||
@@ -316,30 +315,37 @@ struct identifier : public expression {
|
||||
|
||||
// Literals
|
||||
|
||||
/* A literal's value made once, at parse time: literals sit inside the loops a template runs
|
||||
* per message, and allocating a fresh value (and copying the text) for every evaluation was
|
||||
* thousands of allocations per render for values nothing ever mutates -- every operation on
|
||||
* a string works on an as_string() copy, and numbers are only read. */
|
||||
struct integer_literal : public expression {
|
||||
int64_t val;
|
||||
explicit integer_literal(int64_t val) : val(val) {}
|
||||
value cached;
|
||||
explicit integer_literal(int64_t val) : val(val), cached(mk_val<value_int>(val)) {}
|
||||
std::string type() const override { return "IntegerLiteral"; }
|
||||
value execute_impl(context &) override {
|
||||
return mk_val<value_int>(val);
|
||||
return cached;
|
||||
}
|
||||
};
|
||||
|
||||
struct float_literal : public expression {
|
||||
double val;
|
||||
explicit float_literal(double val) : val(val) {}
|
||||
value cached;
|
||||
explicit float_literal(double val) : val(val), cached(mk_val<value_float>(val)) {}
|
||||
std::string type() const override { return "FloatLiteral"; }
|
||||
value execute_impl(context &) override {
|
||||
return mk_val<value_float>(val);
|
||||
return cached;
|
||||
}
|
||||
};
|
||||
|
||||
struct string_literal : public expression {
|
||||
std::string val;
|
||||
explicit string_literal(const std::string & val) : val(val) {}
|
||||
value cached;
|
||||
explicit string_literal(const std::string & val) : val(val), cached(mk_val<value_string>(val)) {}
|
||||
std::string type() const override { return "StringLiteral"; }
|
||||
value execute_impl(context &) override {
|
||||
return mk_val<value_string>(val);
|
||||
return cached;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -598,19 +604,35 @@ struct rethrown_exception : public std::exception {
|
||||
static void gather_string_parts_recursive(const value & val, value_string & parts) {
|
||||
// TODO: probably allow print value_none as "None" string? currently this breaks some templates
|
||||
if (is_val<value_string>(val)) {
|
||||
const auto & str_val = cast_val<value_string>(val)->val_str;
|
||||
parts->val_str.append(str_val);
|
||||
// A uniquely owned string is a statement result being consumed by this gather; move its
|
||||
// parts instead of copying every byte again at each nesting level. A shared one is an
|
||||
// input value the context still holds, and is copied as before.
|
||||
if (val.use_count() == 1) {
|
||||
auto & src = const_cast<value_string_t *>(cast_val<value_string>(val))->val_str.parts;
|
||||
auto & dst = parts->val_str.parts;
|
||||
dst.reserve(dst.size() + src.size());
|
||||
for (auto & part : src) {
|
||||
dst.push_back(std::move(part));
|
||||
}
|
||||
src.clear();
|
||||
} else {
|
||||
const auto & str_val = cast_val<value_string>(val)->val_str;
|
||||
parts->val_str.append(str_val);
|
||||
}
|
||||
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
|
||||
std::string str_val = val->as_string().str();
|
||||
parts->val_str.append(str_val);
|
||||
} else if (is_val<value_array>(val)) {
|
||||
auto items = cast_val<value_array>(val)->as_array();
|
||||
const auto & items = cast_val<value_array>(val)->as_array();
|
||||
for (const auto & item : items) {
|
||||
/* RADIANCE: `val` is a block's statement results, and every block statement returns
|
||||
* a string, so a list or a dict among them is the value of an expression the template
|
||||
* prints. jinja2 prints its repr; flattening it ran its strings together and printed
|
||||
* nothing for a dict. */
|
||||
if (is_val<value_array>(item) || is_val<value_object>(item)) {
|
||||
* nothing for a dict. A statement-results carrier is the one array that is not a
|
||||
* value: flattening it is its whole purpose. */
|
||||
if (is_val<value_stmt_results>(item)) {
|
||||
gather_string_parts_recursive(item, parts);
|
||||
} else if (is_val<value_array>(item) || is_val<value_object>(item)) {
|
||||
parts->val_str.append(item->as_string().str());
|
||||
} else {
|
||||
gather_string_parts_recursive(item, parts);
|
||||
@@ -620,11 +642,54 @@ static void gather_string_parts_recursive(const value & val, value_string & part
|
||||
}
|
||||
|
||||
static std::string render_string_parts(const value_string & parts) {
|
||||
std::ostringstream oss;
|
||||
std::string out;
|
||||
out.reserve(parts->val_str.length());
|
||||
for (const auto & part : parts->val_str.parts) {
|
||||
oss << part.val;
|
||||
out += part.val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The flat text of a statement-result tree, gathered without building a parts list: the parts
|
||||
// (and their is_input flags) matter to the capability probe, but a caller that only wants the
|
||||
// rendered string otherwise pays to copy every byte into parts, join them, and copy them out.
|
||||
static size_t gather_string_length_recursive(const value & val) {
|
||||
if (is_val<value_string>(val)) {
|
||||
return cast_val<value_string>(val)->val_str.length();
|
||||
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
|
||||
return val->as_string().str().size();
|
||||
} else if (is_val<value_array>(val)) {
|
||||
size_t len = 0;
|
||||
for (const auto & item : cast_val<value_array>(val)->as_array()) {
|
||||
if (!is_val<value_stmt_results>(item) &&
|
||||
(is_val<value_array>(item) || is_val<value_object>(item))) {
|
||||
len += item->as_string().str().size();
|
||||
} else {
|
||||
len += gather_string_length_recursive(item);
|
||||
}
|
||||
}
|
||||
return len;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void gather_string_recursive(const value & val, std::string & out) {
|
||||
if (is_val<value_string>(val)) {
|
||||
for (const auto & part : cast_val<value_string>(val)->val_str.parts) {
|
||||
out += part.val;
|
||||
}
|
||||
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
|
||||
out += val->as_string().str();
|
||||
} else if (is_val<value_array>(val)) {
|
||||
for (const auto & item : cast_val<value_array>(val)->as_array()) {
|
||||
if (!is_val<value_stmt_results>(item) &&
|
||||
(is_val<value_array>(item) || is_val<value_object>(item))) {
|
||||
out += item->as_string().str();
|
||||
} else {
|
||||
gather_string_recursive(item, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
struct runtime {
|
||||
@@ -643,18 +708,29 @@ struct runtime {
|
||||
static value_string gather_string_parts(const value & val) {
|
||||
value_string parts = mk_val<value_string>();
|
||||
gather_string_parts_recursive(val, parts);
|
||||
// join consecutive parts with the same type
|
||||
// Join consecutive parts with the same type, in one compaction pass: erasing each
|
||||
// merged part from the middle shifts the rest of the vector every time.
|
||||
auto & p = parts->val_str.parts;
|
||||
for (size_t i = 1; i < p.size(); ) {
|
||||
if (p[i].is_input == p[i - 1].is_input) {
|
||||
p[i - 1].val += p[i].val;
|
||||
p.erase(p.begin() + i);
|
||||
} else {
|
||||
i++;
|
||||
if (!p.empty()) {
|
||||
size_t w = 0;
|
||||
for (size_t r = 1; r < p.size(); ++r) {
|
||||
if (p[r].is_input == p[w].is_input) {
|
||||
p[w].val += p[r].val;
|
||||
} else {
|
||||
p[++w] = std::move(p[r]);
|
||||
}
|
||||
}
|
||||
p.resize(w + 1);
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
static std::string gather_string(const value & val) {
|
||||
std::string out;
|
||||
out.reserve(gather_string_length_recursive(val));
|
||||
gather_string_recursive(val, out);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace jinja
|
||||
Vendored
+41
-12
@@ -2,6 +2,7 @@
|
||||
#include "jinja/value.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
@@ -46,11 +47,38 @@ std::string string::str() const {
|
||||
if (parts.size() == 1) {
|
||||
return parts[0].val;
|
||||
}
|
||||
std::ostringstream oss;
|
||||
std::string out;
|
||||
out.reserve(length());
|
||||
for (const auto & part : parts) {
|
||||
oss << part.val;
|
||||
out += part.val;
|
||||
}
|
||||
return oss.str();
|
||||
return out;
|
||||
}
|
||||
|
||||
bool string::equals(const string & other) const {
|
||||
if (parts.size() == 1 && other.parts.size() == 1) {
|
||||
return parts[0].val == other.parts[0].val;
|
||||
}
|
||||
if (length() != other.length()) {
|
||||
return false;
|
||||
}
|
||||
size_t i = 0, j = 0; // part cursors
|
||||
size_t a = 0, b = 0; // byte offsets within the cursors' parts
|
||||
while (i < parts.size() && j < other.parts.size()) {
|
||||
const std::string & pa = parts[i].val;
|
||||
const std::string & pb = other.parts[j].val;
|
||||
const size_t n = std::min(pa.size() - a, pb.size() - b);
|
||||
if (n > 0 && std::memcmp(pa.data() + a, pb.data() + b, n) != 0) {
|
||||
return false;
|
||||
}
|
||||
a += n;
|
||||
b += n;
|
||||
if (a == pa.size()) { ++i; a = 0; }
|
||||
if (b == pb.size()) { ++j; b = 0; }
|
||||
}
|
||||
// The lengths are equal and every byte compared equal; what is left on either side is
|
||||
// empty parts.
|
||||
return true;
|
||||
}
|
||||
|
||||
size_t string::length() const {
|
||||
@@ -103,7 +131,8 @@ void string::mark_input_based_on(const string & other) {
|
||||
}
|
||||
}
|
||||
|
||||
string string::append(const string & other) {
|
||||
string & string::append(const string & other) {
|
||||
parts.reserve(parts.size() + other.parts.size());
|
||||
for (const auto & part : other.parts) {
|
||||
parts.push_back(part);
|
||||
}
|
||||
@@ -113,29 +142,29 @@ string string::append(const string & other) {
|
||||
// in-place transformation
|
||||
|
||||
using transform_fn = std::function<std::string(const std::string&)>;
|
||||
static string apply_transform(string & self, const transform_fn & fn) {
|
||||
static string apply_transform(string && self, const transform_fn & fn) {
|
||||
for (auto & part : self.parts) {
|
||||
part.val = fn(part.val);
|
||||
}
|
||||
return self;
|
||||
return std::move(self);
|
||||
}
|
||||
|
||||
string string::uppercase() {
|
||||
return apply_transform(*this, [](const std::string & s) {
|
||||
return apply_transform(std::move(*this), [](const std::string & s) {
|
||||
std::string res = s;
|
||||
std::transform(res.begin(), res.end(), res.begin(), ::toupper);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
string string::lowercase() {
|
||||
return apply_transform(*this, [](const std::string & s) {
|
||||
return apply_transform(std::move(*this), [](const std::string & s) {
|
||||
std::string res = s;
|
||||
std::transform(res.begin(), res.end(), res.begin(), ::tolower);
|
||||
return res;
|
||||
});
|
||||
}
|
||||
string string::capitalize() {
|
||||
return apply_transform(*this, [](const std::string & s) {
|
||||
return apply_transform(std::move(*this), [](const std::string & s) {
|
||||
if (s.empty()) return s;
|
||||
std::string res = s;
|
||||
res[0] = ::toupper(static_cast<unsigned char>(res[0]));
|
||||
@@ -144,7 +173,7 @@ string string::capitalize() {
|
||||
});
|
||||
}
|
||||
string string::titlecase() {
|
||||
return apply_transform(*this, [](const std::string & s) {
|
||||
return apply_transform(std::move(*this), [](const std::string & s) {
|
||||
std::string res = s;
|
||||
bool capitalize_next = true;
|
||||
for (char &c : res) {
|
||||
@@ -180,7 +209,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
|
||||
return s.substr(start, end - start);
|
||||
};
|
||||
if (parts.empty()) {
|
||||
return *this;
|
||||
return std::move(*this);
|
||||
}
|
||||
if (left) {
|
||||
for (size_t i = 0; i < parts.size(); ++i) {
|
||||
@@ -207,7 +236,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
|
||||
}
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
return std::move(*this);
|
||||
}
|
||||
|
||||
} // namespace jinja
|
||||
Vendored
+7
-1
@@ -27,6 +27,9 @@ struct string {
|
||||
string(const std::string & v, bool user_input = false) {
|
||||
parts.push_back({user_input, v});
|
||||
}
|
||||
string(std::string && v, bool user_input = false) {
|
||||
parts.push_back({user_input, std::move(v)});
|
||||
}
|
||||
string(int v) {
|
||||
parts.push_back({false, std::to_string(v)});
|
||||
}
|
||||
@@ -38,6 +41,8 @@ struct string {
|
||||
void mark_input();
|
||||
|
||||
std::string str() const;
|
||||
// Flattened equality without flattening: walk both part lists segment by segment.
|
||||
bool equals(const string & other) const;
|
||||
size_t length() const;
|
||||
void hash_update(hasher & hash) const noexcept;
|
||||
bool all_parts_are_input() const;
|
||||
@@ -47,7 +52,8 @@ struct string {
|
||||
// mark this string as input if other has ALL parts as input
|
||||
void mark_input_based_on(const string & other);
|
||||
|
||||
string append(const string & other);
|
||||
// In place: the parts are appended to this string. Returns *this so callers can move it on.
|
||||
string & append(const string & other);
|
||||
|
||||
// in-place transformations
|
||||
|
||||
|
||||
Vendored
+65
-9
@@ -3,7 +3,7 @@
|
||||
#include "value.h"
|
||||
|
||||
// for converting from JSON to jinja values
|
||||
#include <nlohmann/json.hpp>
|
||||
#include "util/json.h"
|
||||
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
@@ -299,6 +299,58 @@ static value minmax_fn(const func_args & args) {
|
||||
return best;
|
||||
}
|
||||
|
||||
/* jinja2's unique() over a sequence: the first occurrence of each item, in order, compared by
|
||||
* `attribute` where one is given. Strings compare lowercased unless `case_sensitive` is true
|
||||
* (jinja2's default is false). A tuple stays a tuple. */
|
||||
static value unique_fn(const func_args & args) {
|
||||
args.ensure_count(1, 3);
|
||||
if (!is_val<value_array>(args.get_pos(0))) {
|
||||
throw raised_exception("unique: first argument must be an array");
|
||||
}
|
||||
value val = args.get_pos(0);
|
||||
value cs = args.get_kwarg_or_pos("case_sensitive", 1);
|
||||
value attribute = args.get_kwarg_or_pos("attribute", 2);
|
||||
const bool case_sensitive = !cs->is_undefined() && cs->as_bool();
|
||||
const bool attr_is_int = is_val<value_int>(attribute);
|
||||
const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
|
||||
const std::vector<value> & arr = val->as_array();
|
||||
auto key = [&](const value & v) -> value {
|
||||
value k = v;
|
||||
if (!attribute->is_undefined()) {
|
||||
if (attr_is_int && is_val<value_array>(v)) {
|
||||
k = v->at(attr_int);
|
||||
} else if (!attr_is_int && is_val<value_object>(v)) {
|
||||
k = v->at(attribute);
|
||||
} else {
|
||||
throw raised_exception("unique: unsupported object attribute comparison on " + v->type());
|
||||
}
|
||||
}
|
||||
if (!case_sensitive && is_val<value_string>(k)) {
|
||||
jinja::string low = k->as_string().lowercase();
|
||||
return mk_val<value_string>(low);
|
||||
}
|
||||
return k;
|
||||
};
|
||||
std::vector<value> keys, out;
|
||||
for (const auto & item : arr) {
|
||||
value k = key(item);
|
||||
bool seen = false;
|
||||
for (const auto & have : keys) {
|
||||
/* value_compare reads a number against a string as text; jinja2 keeps 1 and "1" apart */
|
||||
if (is_val<value_string>(k) == is_val<value_string>(have) &&
|
||||
value_compare(k, have, value_compare_op::eq)) {
|
||||
seen = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!seen) {
|
||||
keys.push_back(std::move(k));
|
||||
out.push_back(item);
|
||||
}
|
||||
}
|
||||
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(out)) : mk_val<value_array>(std::move(out));
|
||||
}
|
||||
|
||||
template<bool is_reject>
|
||||
static value selectattr(const func_args & args) {
|
||||
args.ensure_count(2, 4);
|
||||
@@ -924,10 +976,6 @@ const func_builtins & value_bool_t::get_builtins() const {
|
||||
return builtins;
|
||||
}
|
||||
|
||||
[[noreturn]] static value array_unique_not_implemented(const func_args &) {
|
||||
throw not_implemented_exception("Array unique builtin not implemented");
|
||||
}
|
||||
|
||||
const func_builtins & value_array_t::get_builtins() const {
|
||||
static const func_builtins builtins = {
|
||||
{"default", default_value},
|
||||
@@ -1133,7 +1181,10 @@ const func_builtins & value_array_t::get_builtins() const {
|
||||
std::reverse(arr.begin(), arr.end());
|
||||
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
|
||||
}},
|
||||
{"unique", array_unique_not_implemented},
|
||||
/* RADIANCE: upstream leaves `unique` a stub that throws, with the same result as a
|
||||
* missing min or max above: GLM-5.3-Flash's template checks its tool-call ids with it,
|
||||
* and the model was reported as having no tool support. */
|
||||
{"unique", unique_fn},
|
||||
};
|
||||
return builtins;
|
||||
}
|
||||
@@ -1297,7 +1348,7 @@ const func_builtins & value_undefined_t::get_builtins() const {
|
||||
//////////////////////////////////
|
||||
|
||||
|
||||
static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
|
||||
static value from_json(const rad::Json & j, bool mark_input) {
|
||||
if (j.is_null()) {
|
||||
return mk_val<value_none>();
|
||||
} else if (j.is_boolean()) {
|
||||
@@ -1307,7 +1358,7 @@ static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
|
||||
} else if (j.is_number_float()) {
|
||||
return mk_val<value_float>(j.get<double>());
|
||||
} else if (j.is_string()) {
|
||||
auto str = mk_val<value_string>(j.get<std::string>());
|
||||
auto str = mk_val<value_string>(j.get_ref<const std::string &>());
|
||||
if (mark_input) {
|
||||
str->mark_input();
|
||||
}
|
||||
@@ -1394,7 +1445,7 @@ bool value_compare(const value & a, const value & b, value_compare_op op) {
|
||||
}
|
||||
|
||||
template<>
|
||||
void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bool mark_input) {
|
||||
void global_from_json(context & ctx, const rad::Json & json_obj, bool mark_input) {
|
||||
// printf("global_from_json: %s\n" , json_obj.dump(2).c_str());
|
||||
if (json_obj.is_null() || !json_obj.is_object()) {
|
||||
throw std::runtime_error("global_from_json: input JSON value must be an object");
|
||||
@@ -1405,6 +1456,11 @@ void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bo
|
||||
}
|
||||
}
|
||||
|
||||
void global_set_from_json(context & ctx, const std::string & key,
|
||||
const rad::Json & j, bool mark_input) {
|
||||
ctx.set_val(key, from_json(j, mark_input));
|
||||
}
|
||||
|
||||
// recursively convert value to JSON string
|
||||
// TODO: avoid circular references
|
||||
static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep) {
|
||||
|
||||
Vendored
+170
-28
@@ -3,6 +3,8 @@
|
||||
#include "string.h"
|
||||
#include "utils.h"
|
||||
|
||||
#include "util/json.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
@@ -86,10 +88,16 @@ struct context; // forward declaration
|
||||
// marking input can be useful for tracking data provenance
|
||||
// and preventing template injection attacks
|
||||
//
|
||||
// Note: T_JSON can be nlohmann::ordered_json
|
||||
// Note: T_JSON can be rad::Json
|
||||
template<typename T_JSON>
|
||||
void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input);
|
||||
|
||||
/* One global from a JSON value, converted in place: a caller assembling several globals from
|
||||
* JSON values it already holds (a chat render's messages and tools) need not first copy them
|
||||
* into an intermediate JSON object for global_from_json to convert back out. */
|
||||
void global_set_from_json(context & ctx, const std::string & key,
|
||||
const rad::Json & j, bool mark_input);
|
||||
|
||||
//
|
||||
// base value type
|
||||
//
|
||||
@@ -290,7 +298,9 @@ using value_float = std::shared_ptr<value_float_t>;
|
||||
struct value_string_t : public value_t {
|
||||
value_string_t() { val_str = string(); }
|
||||
value_string_t(const std::string & v) { val_str = string(v); }
|
||||
value_string_t(std::string && v) { val_str = string(std::move(v)); }
|
||||
value_string_t(const string & v) { val_str = v; }
|
||||
value_string_t(string && v) { val_str = std::move(v); }
|
||||
virtual std::string type() const override { return "String"; }
|
||||
virtual string as_string() const override { return val_str; }
|
||||
virtual std::string as_repr() const override {
|
||||
@@ -317,7 +327,7 @@ struct value_string_t : public value_t {
|
||||
}
|
||||
protected:
|
||||
virtual bool equivalent(const value_t & other) const override {
|
||||
return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str();
|
||||
return typeid(*this) == typeid(other) && val_str.equals(other.val_str);
|
||||
}
|
||||
};
|
||||
using value_string = std::shared_ptr<value_string_t>;
|
||||
@@ -459,6 +469,15 @@ protected:
|
||||
};
|
||||
using value_array = std::shared_ptr<value_array_t>;
|
||||
|
||||
/* A block statement's results, carried up to the gather that actually needs text. If and for
|
||||
* statements used to gather their bodies into a fresh string at every nesting level, copying
|
||||
* every shared part's bytes each time; as a carrier, the parts are only flattened once -- by
|
||||
* the top-level render, or by exec_statements where a real string value is required (a set
|
||||
* block, a macro body). It is an array for storage only: the gathers recurse into it where a
|
||||
* plain array value would print its repr, and it never reaches template expressions. */
|
||||
struct value_stmt_results_t : public value_array_t {};
|
||||
using value_stmt_results = std::shared_ptr<value_stmt_results_t>;
|
||||
|
||||
|
||||
struct value_tuple_t : public value_array_t {
|
||||
value_tuple_t(value & v) {
|
||||
@@ -482,13 +501,40 @@ using value_tuple = std::shared_ptr<value_tuple_t>;
|
||||
|
||||
struct value_object_t : public value_t {
|
||||
std::unordered_map<value, value, value_hasher, value_equivalence> unordered;
|
||||
/* The hash index over val_obj, built only once an object outgrows a linear scan. The
|
||||
* objects a chat render builds by the thousand -- messages, calls, scopes -- hold a
|
||||
* handful of keys each, and for those the map's bucket array and per-key nodes cost more
|
||||
* than every lookup they would ever serve. val_obj stays the ordered authority either way. */
|
||||
bool unordered_built_ = false;
|
||||
static constexpr size_t kHashIndexThreshold = 32;
|
||||
void build_unordered() {
|
||||
if (unordered_built_) {
|
||||
return;
|
||||
}
|
||||
unordered.reserve(val_obj.size() * 2);
|
||||
for (const auto & pair : val_obj) {
|
||||
unordered.emplace(pair.first, pair.second);
|
||||
}
|
||||
unordered_built_ = true;
|
||||
}
|
||||
void maybe_build_unordered() {
|
||||
if (val_obj.size() > kHashIndexThreshold) {
|
||||
build_unordered();
|
||||
}
|
||||
}
|
||||
value * find_key_linear(const value & key) {
|
||||
for (auto & pair : val_obj) {
|
||||
if (*(pair.first) == *key) {
|
||||
return &pair.second;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
bool has_builtins = true; // context and loop objects do not have builtins
|
||||
value_object_t() = default;
|
||||
value_object_t(value & v) {
|
||||
val_obj = v->val_obj;
|
||||
for (const auto & pair : val_obj) {
|
||||
unordered[pair.first] = pair.second;
|
||||
}
|
||||
maybe_build_unordered();
|
||||
}
|
||||
value_object_t(const std::map<value, value> & obj) {
|
||||
for (const auto & pair : obj) {
|
||||
@@ -501,8 +547,32 @@ struct value_object_t : public value_t {
|
||||
}
|
||||
}
|
||||
void insert(const std::string & key, const value & val) {
|
||||
// The common case is re-binding a name that is already present (a loop variable, a
|
||||
// scope copy): find it by name first so no key value is allocated for the lookup.
|
||||
if (is_immutable()) {
|
||||
throw std::runtime_error("Attempting to modify immutable type");
|
||||
}
|
||||
for (auto & pair : val_obj) {
|
||||
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
|
||||
if (ks && ks->val_str.parts.size() == 1 && ks->val_str.parts[0].val == key) {
|
||||
pair.second = val;
|
||||
if (unordered_built_) {
|
||||
unordered[pair.first] = val;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
insert(mk_val<value_string>(key), val);
|
||||
}
|
||||
/* Take another object's entries wholesale (a scope inheriting its parent's variables):
|
||||
* the ordered list copies in one allocation instead of a key allocation and a scan per
|
||||
* variable. The hash index, if the size calls for one, is rebuilt from the copy. */
|
||||
void copy_entries_from(const value_object_t & other) {
|
||||
val_obj = other.val_obj;
|
||||
unordered.clear();
|
||||
unordered_built_ = false;
|
||||
maybe_build_unordered();
|
||||
}
|
||||
virtual std::string type() const override { return "Object"; }
|
||||
virtual bool is_immutable() const override { return false; }
|
||||
virtual const std::vector<std::pair<value, value>> & as_ordered_object() const override { return val_obj; }
|
||||
@@ -518,53 +588,125 @@ struct value_object_t : public value_t {
|
||||
return ss.str();
|
||||
}
|
||||
virtual bool as_bool() const override {
|
||||
return !unordered.empty();
|
||||
return !val_obj.empty();
|
||||
}
|
||||
virtual bool has_key(const value & key) override {
|
||||
if (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->type());
|
||||
}
|
||||
return unordered.find(key) != unordered.end();
|
||||
if (unordered_built_) {
|
||||
return unordered.find(key) != unordered.end();
|
||||
}
|
||||
return find_key_linear(key) != nullptr;
|
||||
}
|
||||
virtual void insert(const value & key, const value & val) override {
|
||||
bool replaced = false;
|
||||
if (is_immutable()) {
|
||||
throw std::runtime_error("Attempting to modify immutable type");
|
||||
}
|
||||
if (has_key(key)) {
|
||||
// if key exists, replace value in ordered list instead of appending
|
||||
for (auto & pair : val_obj) {
|
||||
if (*(pair.first) == *key) {
|
||||
pair.second = val;
|
||||
replaced = true;
|
||||
break;
|
||||
if (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->type());
|
||||
}
|
||||
if (unordered_built_) {
|
||||
auto it = unordered.find(key);
|
||||
if (it != unordered.end()) {
|
||||
// if key exists, replace value in ordered list instead of appending
|
||||
it->second = val;
|
||||
for (auto & pair : val_obj) {
|
||||
if (*(pair.first) == *key) {
|
||||
pair.second = val;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
unordered[key] = val;
|
||||
if (!replaced) {
|
||||
unordered.emplace(key, val);
|
||||
val_obj.push_back({key, val});
|
||||
return;
|
||||
}
|
||||
if (value * existing = find_key_linear(key)) {
|
||||
*existing = val;
|
||||
return;
|
||||
}
|
||||
val_obj.push_back({key, val});
|
||||
maybe_build_unordered();
|
||||
}
|
||||
/* Insert a key the caller knows is absent (a fresh object's fields): no lookup first. */
|
||||
void insert_new(const value & key, const value & val) {
|
||||
if (is_immutable()) {
|
||||
throw std::runtime_error("Attempting to modify immutable type");
|
||||
}
|
||||
if (unordered_built_) {
|
||||
unordered.emplace(key, val);
|
||||
}
|
||||
val_obj.push_back({key, val});
|
||||
maybe_build_unordered();
|
||||
}
|
||||
void insert_new(const std::string & key, const value & val) {
|
||||
insert_new(mk_val<value_string>(key), val);
|
||||
}
|
||||
virtual value & at(const value & key, value & default_val) override {
|
||||
if (!has_key(key)) {
|
||||
return default_val;
|
||||
if (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->type());
|
||||
}
|
||||
return unordered.at(key);
|
||||
if (unordered_built_) {
|
||||
auto it = unordered.find(key);
|
||||
return it == unordered.end() ? default_val : it->second;
|
||||
}
|
||||
if (value * v = find_key_linear(key)) {
|
||||
return *v;
|
||||
}
|
||||
return default_val;
|
||||
}
|
||||
virtual value & at(const value & key) override {
|
||||
if (!has_key(key)) {
|
||||
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
|
||||
if (!key->is_immutable() || !key->is_hashable()) {
|
||||
throw std::runtime_error("Object key of unhashable type: " + key->type());
|
||||
}
|
||||
return unordered.at(key);
|
||||
if (unordered_built_) {
|
||||
auto it = unordered.find(key);
|
||||
if (it == unordered.end()) {
|
||||
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
if (value * v = find_key_linear(key)) {
|
||||
return *v;
|
||||
}
|
||||
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
|
||||
}
|
||||
/* A string key by value, without allocating a key value and hashing it: objects here are
|
||||
* message/argument records of a few keys, so the ordered scan is the cheaper lookup. */
|
||||
value * find_string_key(const std::string & key) {
|
||||
for (auto & pair : val_obj) {
|
||||
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
|
||||
if (!ks) {
|
||||
continue;
|
||||
}
|
||||
size_t off = 0;
|
||||
bool eq = true;
|
||||
for (const auto & part : ks->val_str.parts) {
|
||||
if (key.compare(off, part.val.size(), part.val) != 0) {
|
||||
eq = false;
|
||||
break;
|
||||
}
|
||||
off += part.val.size();
|
||||
}
|
||||
if (eq && off == key.size()) {
|
||||
return &pair.second;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
virtual value & at(const std::string & key, value & default_val) override {
|
||||
value key_val = mk_val<value_string>(key);
|
||||
return at(key_val, default_val);
|
||||
if (value * v = find_string_key(key)) {
|
||||
return *v;
|
||||
}
|
||||
return default_val;
|
||||
}
|
||||
virtual value & at(const std::string & key) override {
|
||||
value key_val = mk_val<value_string>(key);
|
||||
return at(key_val);
|
||||
if (value * v = find_string_key(key)) {
|
||||
return *v;
|
||||
}
|
||||
throw std::runtime_error("Key '" + key + "' not found in value of type " + type());
|
||||
}
|
||||
virtual const func_builtins & get_builtins() const override;
|
||||
virtual bool is_hashable() const override {
|
||||
|
||||
Reference in new issue
Block a user