mirror of
https://github.com/ikawrakow/ik_llama.cpp.git
synced 2026-08-12 22:29:39 +04:00
e0596bf614
* Autoparser - complete refactoring of parser architecture Autoparser: add optional argument reshuffle capability Autoparser: True streaming (#20177) * Relax atomicity constraint for nicer, more pleasent, True Streaming parsing * Whitespace * Remove redundant atomics Revert to OAI-compatible args (#20213) * Revert to OAI-compatible args * Apply workaround::func_args_not_string Fix structured outputs (#20223) * Fix structured outputs * Update common/chat-auto-parser-generator.cpp Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Aldehir Rojas <hello@alde.dev> Fix compile bug (#20203) * Fix compile bug * Update common/chat-auto-parser-helpers.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> # Conflicts: # common/chat-auto-parser-helpers.cpp common : gracefully handle incomplete output (#20191) * common : handle incomplete UTF-8 at end of input in PEG parser * cont : if reached end prematurely, emit needs_more_input to propagate partial output * cont: refactor peg parse context to add lenient flag * cont : remove partial flag, keep lenient flag PEG parser for LFM2 (#20251) * PEG parser for LFM2 * Simplify using python_value() common: map developer role to system (#20215) * Map developer role to system * Simplify common: consolidate PEG string parsers (#20263) * common : consolidate PEG string parsers * cont : fix json_string_content() examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Reduce level of content parser warning message to avoid log spam on non-debug verbosity (#20347) do not return if template parse failed add arg to enable parallel tool call common : fix incorrect uses of stoul (#20313) # Conflicts: # common/arg.cpp # src/llama-grammar.cpp examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Add support for MiroThinker with new jinja template common/parser: handle reasoning budget (#20297) * v1 * Finished! * Handlie cli * Reasoning sampler * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Less explosive terminology :) * Add utf-8 case and tests * common : migrate reasoning budget sampler to common * cont : clean up * cont : expose state and allow passing as initial state * cont : remove unused imports * cont : update state machine doc string --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Co-authored-by: Alde Rojas <hello@alde.dev> common/parser: use nlohmann::ordered_json to preserve parameter order (#20385) common/parser: add GigaChatV3/3.1 models support (#19931) Co-authored-by: Mishusha <pmv26021975@gmail.com> common/parser: gracefully handle undetected tool parser, print error message. (#20286) fix: prevent nullptr dereference (#20552) common : fix iterator::end() dereference (#20445) # Conflicts: # common/regex-partial.cpp jinja : add capability check for object args (#20612) common/parser: add `--skip-chat-parsing` to force a pure content parser. (#20289) * Add `--force-pure-content` to force a pure content parser. * Update common/arg.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : rework gpt-oss parser (#20393) * common : rework gpt-oss parser * cont : fix gpt-oss tests * cont : add structured output test * cont : rename final to final_msg common : fix gpt-oss content removal (#20745) common/parser: add proper reasoning tag prefill reading (#20424) * Implement proper prefill extraction * Refactor cli parameters, update docs, move reasoning budget sampler part to common/reasoning-budget.cpp * Update tools/server/server-task.cpp * refactor: move grammars to variant, remove grammar_external, handle exception internally * Make code less C++y Co-authored-by: Georgi Gerganov <ggerganov@gmail.com> chat : handle tool calls with no required args in TAG_WITH_TAGGED format (#20764) * chat : handle tool calls with no required args in TAG_WITH_TAGGED format * Update tests/test-chat.cpp [no ci] Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: Aldehir Rojas <hello@alde.dev> common/parser : fix out_of_range crash in throw path (#20424 regression) (#20777) * chat : fix out_of_range crash in throw path (#20424 regression) #20424 introduced effective_input = generation_prompt + input, but the throw path uses input.substr(result.end) where result.end is a position within effective_input. Every thinking model with a non-empty generation_prompt crashes with std::out_of_range instead of the intended error message. Test crashes on unpatched master, passes with fix: cmake -B build -DLLAMA_BUILD_TESTS=ON -DLLAMA_BUILD_TOOLS=OFF cmake --build build --target test-chat ./build/bin/test-chat * Update test-chat.cpp * Update test-chat.cpp * Update test-chat.cpp --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> jinja : fix heap OOB read in value equality comparison (#20782) Address GHSA-q9j6-4hhc-rq9p and GHSA-2q4c-9gq5-5vfp. The three-iterator overload of std::equal in value_array_t::equivalent() and value_object_t::equivalent() reads past the end of the shorter container when comparing arrays or objects of different lengths. Use the four-iterator overload (C++14) which checks both range lengths. Found-by: Pwno common : fix typo in debug log ('extracft' -> 'extract') (#20807) common/parser: fix nasty bug causing subtle corruption of generation prompt (#20825) jinja : refactor token advancement (#20864) * refactor token advancement * exercise sub-expressions common/autoparser : detect reasoning markers when enable_thinking changes system prompt (#20859) common : replace wrap_for_generation with a prefix convenience function and fix gpt-oss (#20912) jinja: fix macro with kwargs (#20960) * jinja: fix macro with kwargs * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * fix newline problem --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : inhibit lazy grammar sampler while reasoning is active (#20970) * common : inhibit grammar while reasoning budget is active * cont : update force_pos in accept * cont : fix tests * cont : tweak should apply logic * cont : return early not using grammar sampler * Add tests * cont : prevent backend sampling when reasoning budget enabled * cont : fix typo --------- Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com> # Conflicts: # common/reasoning-budget.h # common/sampling.cpp # tools/cli/cli.cpp # tools/server/server-common.cpp # tools/server/server-task.cpp common/parser: fix reasoning whitespace bugs + extra parser tests (#21085) * fix whitespace reasoning issues + add reconstruction tests * Proper fix * fix Nemotron autoparser test expectations to include newline in marker common : add reasoning_format = none support to gpt-oss (#21094) common/json-schema: fix: handle non-capturing groups (?:...) in JSON schema pattern converter (#21124) The regex-to-grammar converter in _visit_pattern() crashes with SIGSEGV when a JSON schema "pattern" field contains a non-capturing group (?:...). Root cause: when the parser sees '(' followed by '?', it pushes a warning but does not advance past '?:'. The recursive transform() call then interprets '?' as a quantifier and calls seq.back() on an empty vector, causing undefined behavior. This commonly occurs when serving OpenAI-compatible tool calls from clients that include complex regex patterns in their JSON schemas (e.g., date validation patterns like ^(?:(?:\d\d[2468][048]|...)-02-29|...)$). The fix: - Skip '?:' after '(' to treat non-capturing groups as regular groups - For unsupported syntax (?=, ?!, etc.), skip to matching ')' safely, handling escaped characters to avoid miscounting parenthesis depth - Adjust the ')' unbalanced-parentheses check using direct char comparisons instead of substr - Add test cases for non-capturing groups (C++ only, as the JS/Python implementations do not yet support this syntax) common/parser: fix handling of tool definition with missing properties key (#21128) jinja : handle empty expressions correctly (#20913) * Reject empty computed member expressions before returning slices[0] from parse_member_expression_arguments(). * Treat empty computed member expressions with Jinja2 undefined semantics Treat empty computed member expressions like `a[]` as undefined instead of raising a parser error, to match Jinja2 behavior. - return a noop expression for empty computed member arguments - return undefined when a computed member key evaluates to undefined - add Jinja tests covering `a[]|default('fallback')` and `a[] is undefined` * Handle undefined computed member properties Move undefined-property handling to the common member access path, and add a test covering `a[undefined] is undefined`. * Use default undefined value in member access Initialize val and then return it when property is undefined. Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * empty statement parses to blank_expression instead of noop_statement --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : gpt-oss handle builtin and unsolicited tool calls (#21213) fix: tool call parsing for LFM2 and LFM2.5 models (#21242) * fix: tool call parsing for LFM2 and LFM2.5 models' * refactor: add test / break out lfm2 and lfm2.5 parsing logic # Conflicts: # common/chat.cpp Relax prefill parser to allow space. (#21240) * Relax prefill parser to allow space. * Move changes from prefix() to parser generation * Only allow spaces if we're not having a pure content parser next common : add commentary rules for gpt-oss-20b (#21286) add reasoning budget model, mtmd: fix gguf conversion for audio/vision mmproj (#21309) * fix gguf conversion for audio/vision mmproj * fix test # Conflicts: # convert_hf_to_gguf.py # examples/eval-callback/eval-callback.cpp # examples/mtmd/CMakeLists.txt # examples/mtmd/clip-impl.h # examples/mtmd/mtmd.cpp # gguf-py/gguf/constants.py # gguf-py/gguf/gguf_writer.py # gguf-py/gguf/tensor_mapping.py # src/CMakeLists.txt # src/llama-arch.cpp # src/llama-arch.h # src/llama-model.cpp # src/llama-model.h # src/llama-vocab.cpp # src/models/models.h # tests/test-llama-archs.cpp # tools/mtmd/clip-graph.h # tools/mtmd/clip-model.h # tools/mtmd/clip.cpp # tools/mtmd/models/models.h fix: gemma 4 template (#21326) chat : avoid including json in chat.h (#21306) jinja: coerce input for string-specific filters (#21370) common : fix tool call type detection for nullable and enum schemas (#21327) * common : fix tool call type detection for nullable and enum schemas * common, tests : fix grammar delegation for nullable/enum schemas and add tests Fix enum type inference to scan all enum values (not just index 0) so schemas like {"enum": [0, "celsius"]} correctly detect string type. Fix schema_delegates in peg-parser to handle nullable type arrays (["string", "null"]) and typeless enum schemas in raw mode, allowing the tagged parser to use raw text instead of JSON-formatted strings. Add test cases for Qwen3-Coder (TAG_WITH_TAGGED format): - nullable string ["string", "null"] - nullable string with null first ["null", "string"] - nullable integer ["integer", "null"] - enum without explicit type key common/parser: fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers (#21230) * Fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers * Rename * Update common/chat-auto-parser-generator.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : add gemma 4 specialized parser (#21418) * common : add gemma4 dedicated parser * cont : add '<|tool_response>' as eog * cont : emit JSON from Gemma4 tool call AST * cont : more fixes * cont : refactor convert function * cont : refine rules and mapping * cont : add more tests * cont : clean up * cont : remove autoparser gemma4 implementation * cont : more cleanup * cont : rename gemma4.jinja to match the others * cont : add custom template to support interleaved thinking * cont : preserve reasoning in model turns * cont : fix initializer error * cont : fix unused vars * cont : fix accidental static * cont : fix specialized_template signature * fix extra semicolon * remove debug line and extra space [no ci] fix reasoning budget parser: fix MiniMax handling (#21573) jinja : support ensure_ascii=true, string repetition and int/float self-filtering (#21623) * feat: jinja engine improvements for reka-edge Port three Jinja engine improvements needed for the reka-edge model: 1. Python-style string repetition ("ab" * 3 → "ababab") 2. ensure_ascii=true support for tojson filter (escapes non-ASCII to \uXXXX) 3. int() builtin on value_int_t (identity, needed for Reka Edge template) * fix: escape invalid utf8 bytes when ensure_ascii=true The json_ensure_ascii_preserving_format function does not correctly handle an edge case where if UTF-8 parsing fails, it adds the non-ascii character back to the output as a raw byte. This commit fixes that by adding the unicode standard replacement character \\ufffd to the output instead. This is the standard behavior for various programming languages like Python, Rust, Go, etc. * chore: address PR comments 1. Add todo comment for supporting string repetition for array/tuples 2. Add support for float identity operation 3. Move invalid ascii test case to test_fuzzing * chore: accept suggestion for common/jinja/value.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : simplify autoparser tagged parser rules (#21216) * common : simplify autoparser tagged parser rules * cont : remove upper limit on optional args * cont : revert changes to parsing at the end * cont : undo arbitrary ordering of optional args * cont : fix uninitialized required parameters * revert to simplify merge * re-apply patches * restore flexible optional arg ordering tests common : fix ambiguous grammar rule in gemma4 (#21661) * common : fix ambiguous grammar rule in gemma4 * cont : fix missing comma... common : enable reasoning budget sampler for gemma4 (#21697) * fix: enable reasoning budget sampler for gemma4 Add thinking_start_tag and thinking_end_tag to common_chat_params_init_gemma4(). Without these, the reasoning budget sampler never activates for gemma4. Make the newline after "thought" optional in the PEG parser to handle budget=0 (sampler forces end tag before the newline). Add test case for empty thinking block. Fixes #21487 * use p.space() instead of p.optional(p.literal("\n")) in gemma4 thought parser common : better align to the updated official gemma4 template (#21704) fix: Fix broken structured output when using $refs in json_schema (#21699) chat: dedicated DeepSeek v3.2 parser + "official" template (#21785) Hide render_message_to_json warning common/gemma4 : handle parsing edge cases (#21760) common: skip reasoning budget sampler when no budget is requested (#21870) * common: skip reasoning budget sampler when no budget is requested After I added thinking_start_tag / thinking_end_tag for gemma4 in #21697, the reasoning budget sampler gets unconditionally created even when no budget is configured (the default -1). The same applies to kimi_k2, lfm2, lfm2_5, and ministral_3 which also set these tags. The budget gets converted to INT_MAX, so the sampler never actually forces any tokens but still runs per-token checks (start tag matching in IDLE state, token-to-piece conversion + UTF-8 checks in COUNTING state). More importantly, the mere existence of the sampler (non-null rbudget) disables backend sampling. Backend sampling lets the GPU select tokens directly, avoiding a full logits transfer from GPU to CPU every token. This could explain the 30% speed regression reported in #21784 (98 t/s to 70 t/s on Vulkan). So I added a reasoning_budget_tokens >= 0 check to the sampler creation condition. When the budget is unlimited, the sampler is not created, backend sampling stays enabled, and no per-token overhead is added. When a budget is explicitly set (0, 128, 1024, etc.), the sampler is created and works as before. * common: preserve rbudget when grammar is lazy Following up on the review feedback on #21870: keep the reasoning budget sampler when grammar_lazy is true, so the thinking-block grammar suppression from #20970 still works when tools are in use. This way, we only skip the sampler when both no budget is set AND grammar is not lazy. autoparser: support case of JSON_NATIVE with per-call markers (test case: Reka-Edge) (#21892) * fix grammar * fix add sampled token --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: firecoperana <firecoperana>
647 lines
21 KiB
C++
647 lines
21 KiB
C++
#pragma once
|
|
|
|
#include "lexer.h"
|
|
#include "value.h"
|
|
|
|
#include <cassert>
|
|
#include <ctime>
|
|
#include <memory>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#define JJ_DEBUG(msg, ...) do { if (g_jinja_debug) printf("%s:%-3d : " msg "\n", FILENAME, __LINE__, __VA_ARGS__); } while (0)
|
|
|
|
extern bool g_jinja_debug;
|
|
|
|
namespace jinja {
|
|
|
|
struct statement;
|
|
using statement_ptr = std::unique_ptr<statement>;
|
|
using statements = std::vector<statement_ptr>;
|
|
|
|
// Helpers for dynamic casting and type checking
|
|
template<typename T>
|
|
struct extract_pointee_unique {
|
|
using type = T;
|
|
};
|
|
template<typename U>
|
|
struct extract_pointee_unique<std::unique_ptr<U>> {
|
|
using type = U;
|
|
};
|
|
template<typename T>
|
|
bool is_stmt(const statement_ptr & ptr) {
|
|
return dynamic_cast<const T*>(ptr.get()) != nullptr;
|
|
}
|
|
template<typename T>
|
|
T * cast_stmt(statement_ptr & ptr) {
|
|
return dynamic_cast<T*>(ptr.get());
|
|
}
|
|
template<typename T>
|
|
const T * cast_stmt(const statement_ptr & ptr) {
|
|
return dynamic_cast<const T*>(ptr.get());
|
|
}
|
|
// End Helpers
|
|
|
|
|
|
// not thread-safe
|
|
void enable_debug(bool enable);
|
|
|
|
struct context {
|
|
std::shared_ptr<std::string> src; // for debugging; use shared_ptr to avoid copying on scope creation
|
|
std::time_t current_time; // for functions that need current time
|
|
|
|
bool is_get_stats = false; // whether to collect stats
|
|
|
|
// src is optional, used for error reporting
|
|
context(std::string src = "") : src(std::make_shared<std::string>(std::move(src))) {
|
|
env = mk_val<value_object>();
|
|
env->has_builtins = false; // context object has no builtins
|
|
env->insert("true", mk_val<value_bool>(true));
|
|
env->insert("True", mk_val<value_bool>(true));
|
|
env->insert("false", mk_val<value_bool>(false));
|
|
env->insert("False", mk_val<value_bool>(false));
|
|
env->insert("none", mk_val<value_none>());
|
|
env->insert("None", mk_val<value_none>());
|
|
current_time = std::time(nullptr);
|
|
}
|
|
~context() = default;
|
|
|
|
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);
|
|
}
|
|
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);
|
|
}
|
|
|
|
void set_val(const std::string & name, const value & val) {
|
|
env->insert(name, val);
|
|
}
|
|
|
|
void set_val(const value & name, const value & val) {
|
|
env->insert(name, val);
|
|
}
|
|
|
|
void print_vars() const {
|
|
printf("Context Variables:\n%s\n", value_to_json(env, 2).c_str());
|
|
}
|
|
|
|
private:
|
|
value_object env;
|
|
};
|
|
|
|
/**
|
|
* Base class for all nodes in the AST.
|
|
*/
|
|
struct statement {
|
|
size_t pos; // position in source, for debugging
|
|
virtual ~statement() = default;
|
|
virtual std::string type() const { return "Statement"; }
|
|
// execute_impl must be overridden by derived classes
|
|
virtual value execute_impl(context &) { throw std::runtime_error("cannot exec " + type()); }
|
|
// execute is the public method to execute a statement with error handling
|
|
value execute(context &);
|
|
};
|
|
|
|
// Type Checking Utilities
|
|
|
|
template<typename T>
|
|
static void chk_type(const statement_ptr & ptr) {
|
|
if (!ptr) return; // Allow null for optional fields
|
|
assert(dynamic_cast<T *>(ptr.get()) != nullptr);
|
|
}
|
|
|
|
template<typename T, typename U>
|
|
static void chk_type(const statement_ptr & ptr) {
|
|
if (!ptr) return;
|
|
assert(dynamic_cast<T *>(ptr.get()) != nullptr || dynamic_cast<U *>(ptr.get()) != nullptr);
|
|
}
|
|
|
|
// Base Types
|
|
|
|
/**
|
|
* Expressions will result in a value at runtime (unlike statements).
|
|
*/
|
|
struct expression : public statement {
|
|
std::string type() const override { return "Expression"; }
|
|
};
|
|
|
|
// Statements
|
|
|
|
struct program : public statement {
|
|
statements body;
|
|
|
|
program() = default;
|
|
explicit program(statements && body) : body(std::move(body)) {}
|
|
std::string type() const override { return "Program"; }
|
|
value execute_impl(context &) override {
|
|
throw std::runtime_error("Cannot execute program directly, use jinja::runtime instead");
|
|
}
|
|
};
|
|
|
|
struct if_statement : public statement {
|
|
statement_ptr test;
|
|
statements body;
|
|
statements alternate;
|
|
|
|
if_statement(statement_ptr && test, statements && body, statements && alternate)
|
|
: test(std::move(test)), body(std::move(body)), alternate(std::move(alternate)) {
|
|
chk_type<expression>(this->test);
|
|
}
|
|
|
|
std::string type() const override { return "If"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct identifier;
|
|
struct tuple_literal;
|
|
|
|
/**
|
|
* Loop over each item in a sequence
|
|
* https://jinja.palletsprojects.com/en/3.0.x/templates/#for
|
|
*/
|
|
struct for_statement : public statement {
|
|
statement_ptr loopvar; // Identifier | TupleLiteral
|
|
statement_ptr iterable;
|
|
statements body;
|
|
statements default_block; // if no iteration took place
|
|
|
|
for_statement(statement_ptr && loopvar, statement_ptr && iterable, statements && body, statements && default_block)
|
|
: loopvar(std::move(loopvar)), iterable(std::move(iterable)),
|
|
body(std::move(body)), default_block(std::move(default_block)) {
|
|
chk_type<identifier, tuple_literal>(this->loopvar);
|
|
chk_type<expression>(this->iterable);
|
|
}
|
|
|
|
std::string type() const override { return "For"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct break_statement : public statement {
|
|
std::string type() const override { return "Break"; }
|
|
|
|
struct signal : public std::exception {
|
|
const char* what() const noexcept override {
|
|
return "Break statement executed";
|
|
}
|
|
};
|
|
|
|
value execute_impl(context &) override {
|
|
throw break_statement::signal();
|
|
}
|
|
};
|
|
|
|
struct continue_statement : public statement {
|
|
std::string type() const override { return "Continue"; }
|
|
|
|
struct signal : public std::exception {
|
|
const char* what() const noexcept override {
|
|
return "Continue statement executed";
|
|
}
|
|
};
|
|
|
|
value execute_impl(context &) override {
|
|
throw continue_statement::signal();
|
|
}
|
|
};
|
|
|
|
// do nothing
|
|
struct noop_statement : public statement {
|
|
std::string type() const override { return "Noop"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_undefined>();
|
|
}
|
|
};
|
|
|
|
struct set_statement : public statement {
|
|
statement_ptr assignee;
|
|
statement_ptr val;
|
|
statements body;
|
|
|
|
set_statement(statement_ptr && assignee, statement_ptr && value, statements && body)
|
|
: assignee(std::move(assignee)), val(std::move(value)), body(std::move(body)) {
|
|
chk_type<expression>(this->assignee);
|
|
chk_type<expression>(this->val);
|
|
}
|
|
|
|
std::string type() const override { return "Set"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct macro_statement : public statement {
|
|
statement_ptr name;
|
|
statements args;
|
|
statements body;
|
|
|
|
macro_statement(statement_ptr && name, statements && args, statements && body)
|
|
: name(std::move(name)), args(std::move(args)), body(std::move(body)) {
|
|
chk_type<identifier>(this->name);
|
|
for (const auto& arg : this->args) chk_type<expression>(arg);
|
|
}
|
|
|
|
std::string type() const override { return "Macro"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct comment_statement : public statement {
|
|
std::string val;
|
|
explicit comment_statement(const std::string & v) : val(v) {}
|
|
std::string type() const override { return "Comment"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_undefined>();
|
|
}
|
|
};
|
|
|
|
// Expressions
|
|
|
|
// Represents an omitted expression in a computed member, e.g. `a[]`.
|
|
struct blank_expression : public expression {
|
|
std::string type() const override { return "BlankExpression"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_undefined>();
|
|
}
|
|
};
|
|
|
|
struct member_expression : public expression {
|
|
statement_ptr object;
|
|
statement_ptr property;
|
|
bool computed; // true if obj[expr] and false if obj.prop
|
|
|
|
member_expression(statement_ptr && object, statement_ptr && property, bool computed)
|
|
: object(std::move(object)), property(std::move(property)), computed(computed) {
|
|
chk_type<expression>(this->object);
|
|
chk_type<expression>(this->property);
|
|
}
|
|
std::string type() const override { return "MemberExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct call_expression : public expression {
|
|
statement_ptr callee;
|
|
statements args;
|
|
|
|
call_expression(statement_ptr && callee, statements && args)
|
|
: callee(std::move(callee)), args(std::move(args)) {
|
|
chk_type<expression>(this->callee);
|
|
for (const auto& arg : this->args) chk_type<expression>(arg);
|
|
}
|
|
std::string type() const override { return "CallExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
/**
|
|
* Represents a user-defined variable or symbol in the template.
|
|
*/
|
|
struct identifier : public expression {
|
|
std::string val;
|
|
explicit identifier(const std::string & val) : val(val) {}
|
|
std::string type() const override { return "Identifier"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
// Literals
|
|
|
|
struct integer_literal : public expression {
|
|
int64_t val;
|
|
explicit integer_literal(int64_t val) : val(val) {}
|
|
std::string type() const override { return "IntegerLiteral"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_int>(val);
|
|
}
|
|
};
|
|
|
|
struct float_literal : public expression {
|
|
double val;
|
|
explicit float_literal(double val) : val(val) {}
|
|
std::string type() const override { return "FloatLiteral"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_float>(val);
|
|
}
|
|
};
|
|
|
|
struct string_literal : public expression {
|
|
std::string val;
|
|
explicit string_literal(const std::string & val) : val(val) {}
|
|
std::string type() const override { return "StringLiteral"; }
|
|
value execute_impl(context &) override {
|
|
return mk_val<value_string>(val);
|
|
}
|
|
};
|
|
|
|
struct array_literal : public expression {
|
|
statements val;
|
|
explicit array_literal(statements && val) : val(std::move(val)) {
|
|
for (const auto& item : this->val) chk_type<expression>(item);
|
|
}
|
|
std::string type() const override { return "ArrayLiteral"; }
|
|
value execute_impl(context & ctx) override {
|
|
auto arr = mk_val<value_array>();
|
|
for (const auto & item_stmt : val) {
|
|
arr->push_back(item_stmt->execute(ctx));
|
|
}
|
|
return arr;
|
|
}
|
|
};
|
|
|
|
struct tuple_literal : public expression {
|
|
statements val;
|
|
explicit tuple_literal(statements && val) : val(std::move(val)) {
|
|
for (const auto& item : this->val) chk_type<expression>(item);
|
|
}
|
|
std::string type() const override { return "TupleLiteral"; }
|
|
value execute_impl(context & ctx) override {
|
|
auto arr = mk_val<value_array>();
|
|
for (const auto & item_stmt : val) {
|
|
arr->push_back(item_stmt->execute(ctx));
|
|
}
|
|
return mk_val<value_tuple>(std::move(arr->as_array()));
|
|
}
|
|
};
|
|
|
|
struct object_literal : public expression {
|
|
std::vector<std::pair<statement_ptr, statement_ptr>> val;
|
|
explicit object_literal(std::vector<std::pair<statement_ptr, statement_ptr>> && val)
|
|
: val(std::move(val)) {
|
|
for (const auto & pair : this->val) {
|
|
chk_type<expression>(pair.first);
|
|
chk_type<expression>(pair.second);
|
|
}
|
|
}
|
|
std::string type() const override { return "ObjectLiteral"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
// Complex Expressions
|
|
|
|
/**
|
|
* An operation with two sides, separated by an operator.
|
|
* Note: Either side can be a Complex Expression, with order
|
|
* of operations being determined by the operator.
|
|
*/
|
|
struct binary_expression : public expression {
|
|
token op;
|
|
statement_ptr left;
|
|
statement_ptr right;
|
|
|
|
binary_expression(token op, statement_ptr && left, statement_ptr && right)
|
|
: op(std::move(op)), left(std::move(left)), right(std::move(right)) {
|
|
chk_type<expression>(this->left);
|
|
chk_type<expression>(this->right);
|
|
}
|
|
std::string type() const override { return "BinaryExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
/**
|
|
* An operation with two sides, separated by the | operator.
|
|
* Operator precedence: https://github.com/pallets/jinja/issues/379#issuecomment-168076202
|
|
*/
|
|
struct filter_expression : public expression {
|
|
// either an expression or a value is allowed
|
|
statement_ptr operand;
|
|
value_string val; // will be set by filter_statement
|
|
|
|
statement_ptr filter;
|
|
|
|
filter_expression(statement_ptr && operand, statement_ptr && filter)
|
|
: operand(std::move(operand)), filter(std::move(filter)) {
|
|
chk_type<expression>(this->operand);
|
|
chk_type<identifier, call_expression>(this->filter);
|
|
}
|
|
|
|
filter_expression(value_string && val, statement_ptr && filter)
|
|
: val(std::move(val)), filter(std::move(filter)) {
|
|
chk_type<identifier, call_expression>(this->filter);
|
|
}
|
|
|
|
std::string type() const override { return "FilterExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct filter_statement : public statement {
|
|
statement_ptr filter;
|
|
statements body;
|
|
|
|
filter_statement(statement_ptr && filter, statements && body)
|
|
: filter(std::move(filter)), body(std::move(body)) {
|
|
chk_type<identifier, call_expression>(this->filter);
|
|
}
|
|
std::string type() const override { return "FilterStatement"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
/**
|
|
* An operation which filters a sequence of objects by applying a test to each object,
|
|
* and only selecting the objects with the test succeeding.
|
|
*
|
|
* It may also be used as a shortcut for a ternary operator.
|
|
*/
|
|
struct select_expression : public expression {
|
|
statement_ptr lhs;
|
|
statement_ptr test;
|
|
|
|
select_expression(statement_ptr && lhs, statement_ptr && test)
|
|
: lhs(std::move(lhs)), test(std::move(test)) {
|
|
chk_type<expression>(this->lhs);
|
|
chk_type<expression>(this->test);
|
|
}
|
|
std::string type() const override { return "SelectExpression"; }
|
|
value execute_impl(context & ctx) override {
|
|
auto predicate = test->execute_impl(ctx);
|
|
if (!predicate->as_bool()) {
|
|
return mk_val<value_undefined>();
|
|
}
|
|
return lhs->execute_impl(ctx);
|
|
}
|
|
};
|
|
|
|
/**
|
|
* An operation with two sides, separated by the "is" operator.
|
|
* NOTE: "value is something" translates to function call "test_is_something(value)"
|
|
*/
|
|
struct test_expression : public expression {
|
|
statement_ptr operand;
|
|
bool negate;
|
|
statement_ptr test;
|
|
|
|
test_expression(statement_ptr && operand, bool negate, statement_ptr && test)
|
|
: operand(std::move(operand)), negate(negate), test(std::move(test)) {
|
|
chk_type<expression>(this->operand);
|
|
chk_type<identifier, call_expression>(this->test);
|
|
}
|
|
std::string type() const override { return "TestExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
/**
|
|
* An operation with one side (operator on the left).
|
|
*/
|
|
struct unary_expression : public expression {
|
|
token op;
|
|
statement_ptr argument;
|
|
|
|
unary_expression(token op, statement_ptr && argument)
|
|
: op(std::move(op)), argument(std::move(argument)) {
|
|
chk_type<expression>(this->argument);
|
|
}
|
|
std::string type() const override { return "UnaryExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct slice_expression : public expression {
|
|
statement_ptr start_expr;
|
|
statement_ptr stop_expr;
|
|
statement_ptr step_expr;
|
|
|
|
slice_expression(statement_ptr && start_expr, statement_ptr && stop_expr, statement_ptr && step_expr)
|
|
: start_expr(std::move(start_expr)), stop_expr(std::move(stop_expr)), step_expr(std::move(step_expr)) {
|
|
chk_type<expression>(this->start_expr);
|
|
chk_type<expression>(this->stop_expr);
|
|
chk_type<expression>(this->step_expr);
|
|
}
|
|
std::string type() const override { return "SliceExpression"; }
|
|
value execute_impl(context &) override {
|
|
throw std::runtime_error("must be handled by MemberExpression");
|
|
}
|
|
};
|
|
|
|
struct keyword_argument_expression : public expression {
|
|
statement_ptr key;
|
|
statement_ptr val;
|
|
|
|
keyword_argument_expression(statement_ptr && key, statement_ptr && val)
|
|
: key(std::move(key)), val(std::move(val)) {
|
|
chk_type<identifier>(this->key);
|
|
chk_type<expression>(this->val);
|
|
}
|
|
std::string type() const override { return "KeywordArgumentExpression"; }
|
|
value execute_impl(context & ctx) override;
|
|
};
|
|
|
|
struct spread_expression : public expression {
|
|
statement_ptr argument;
|
|
explicit spread_expression(statement_ptr && argument) : argument(std::move(argument)) {
|
|
chk_type<expression>(this->argument);
|
|
}
|
|
std::string type() const override { return "SpreadExpression"; }
|
|
};
|
|
|
|
struct call_statement : public statement {
|
|
statement_ptr call;
|
|
statements caller_args;
|
|
statements body;
|
|
|
|
call_statement(statement_ptr && call, statements && caller_args, statements && body)
|
|
: call(std::move(call)), caller_args(std::move(caller_args)), body(std::move(body)) {
|
|
chk_type<call_expression>(this->call);
|
|
for (const auto & arg : this->caller_args) chk_type<expression>(arg);
|
|
}
|
|
std::string type() const override { return "CallStatement"; }
|
|
};
|
|
|
|
struct ternary_expression : public expression {
|
|
statement_ptr condition;
|
|
statement_ptr true_expr;
|
|
statement_ptr false_expr;
|
|
|
|
ternary_expression(statement_ptr && condition, statement_ptr && true_expr, statement_ptr && false_expr)
|
|
: condition(std::move(condition)), true_expr(std::move(true_expr)), false_expr(std::move(false_expr)) {
|
|
chk_type<expression>(this->condition);
|
|
chk_type<expression>(this->true_expr);
|
|
chk_type<expression>(this->false_expr);
|
|
}
|
|
std::string type() const override { return "Ternary"; }
|
|
value execute_impl(context & ctx) override {
|
|
value cond_val = condition->execute(ctx);
|
|
if (cond_val->as_bool()) {
|
|
return true_expr->execute(ctx);
|
|
} else {
|
|
return false_expr->execute(ctx);
|
|
}
|
|
}
|
|
};
|
|
|
|
struct raised_exception : public std::exception {
|
|
std::string message;
|
|
raised_exception(const std::string & msg) : message(msg) {}
|
|
const char* what() const noexcept override {
|
|
return message.c_str();
|
|
}
|
|
};
|
|
|
|
// Used to rethrow exceptions with modified messages
|
|
struct rethrown_exception : public std::exception {
|
|
std::string message;
|
|
rethrown_exception(const std::string & msg) : message(msg) {}
|
|
const char* what() const noexcept override {
|
|
return message.c_str();
|
|
}
|
|
};
|
|
|
|
//////////////////////
|
|
|
|
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);
|
|
} 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();
|
|
for (const auto & item : items) {
|
|
gather_string_parts_recursive(item, parts);
|
|
}
|
|
}
|
|
}
|
|
|
|
static std::string render_string_parts(const value_string & parts) {
|
|
std::ostringstream oss;
|
|
for (const auto & part : parts->val_str.parts) {
|
|
oss << part.val;
|
|
}
|
|
return oss.str();
|
|
}
|
|
|
|
struct runtime {
|
|
context & ctx;
|
|
explicit runtime(context & ctx) : ctx(ctx) {}
|
|
|
|
value_array execute(const program & prog) {
|
|
value_array results = mk_val<value_array>();
|
|
for (const auto & stmt : prog.body) {
|
|
value res = stmt->execute(ctx);
|
|
results->push_back(std::move(res));
|
|
}
|
|
return results;
|
|
}
|
|
|
|
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
|
|
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++;
|
|
}
|
|
}
|
|
return parts;
|
|
}
|
|
};
|
|
|
|
} // namespace jinja
|