PineForge unreleased
Deterministic PineScript v6 backtest runtime — C ABI reference
Loading...
Searching...
No Matches
run_failure.hpp
Go to the documentation of this file.
1#pragma once
2
3// Stable run-failure codes: every engine-originated run failure carries one.
4//
5// A run that fails leaves two things beside each other: the English text
6// strategy_get_last_error() has always returned, unchanged byte for byte, and
7// a code from a closed vocabulary (strategy_get_last_error_code()) with its
8// typed arguments as one canonical JSON object
9// (strategy_get_last_error_args()). The vocabulary, its classes, its argument
10// kinds and closed value lists, and the English each code is written with,
11// are published as run_failure_codes.json (schema
12// pineforge-run-failure-catalog/v1); include/pineforge/run_failure_codes.hpp
13// and src/run_failure_registry.inc are generated from it
14// (scripts/check_run_failure_codes.py --write-registry) and the source guard
15// holds them to it.
16//
17// The rules the channel keeps:
18// * a code is chosen where the failure is raised, never read from data: a
19// text a script writes (runtime.error) can only ever read
20// strategy_runtime_error, whatever it says;
21// * an argument is built only from a literal the transpiler emitted (a call's
22// spelling, its line, a literal symbol, an input title), a closed engine
23// vocabulary, or a value the run request supplied (a row of its OHLCV, its
24// timeframes) -- never from a value the script computes while it runs;
25// Q7's run_aborted additionally carries only engine-owned completion count
26// and started witnesses, never a script-computed index or value;
27// pine_map_capacity_exceeded likewise carries engine-owned map counts and
28// current bar context, plus the fixed TV identifier RE10070; its maxSize and
29// currSize argument names retain the provider's spelling;
30// pine_timezone_error carries the refused timezone argument in zone, which
31// may be script-computed; its function is a closed built-in vocabulary and
32// its code is fixed by pine_timezone_stop (TradingView RE10133); bar_index
33// comes from the engine's bar context and is -1 when no bar is installed;
34// * a vocabulary argument outside its closed list, an undeclared argument, a
35// wrong kind or a missing required argument turns the failure into
36// engine_invariant (the English is kept): a wrong call cannot mint a code
37// or an open string.
38//
39// Thrown types do not change: coded<Base> derives from Base, so every typed
40// catch and every what() is what it was. The classifier
41// (classify_run_failure) reads the carried code; an exception without one is
42// classified by its type as a safety net only -- std::bad_alloc is
43// out_of_memory, the std::logic_error family engine_invariant, anything else
44// engine_unclassified_error.
45//
46// ---------------------------------------------------------------------------
47// The codegen contract (PINEFORGE_HAS_RUN_FAILURE_CODES_V1). Generated code
48// may call exactly these, under `#ifdef PINEFORGE_HAS_RUN_FAILURE_CODES_V1`
49// (and keep `pine_runtime_error(std::string(english))` in the `#else` arm).
50// Every helper is [[noreturn]], throws coded<std::runtime_error>, hardwires its
51// code and never takes one; `english` is the text the stop has today, and is
52// what strategy_get_last_error() reads, byte for byte, except that the timezone
53// stop adds the shared bar prefix described below. Pointer arguments are
54// codegen literals (`const char*`, never NULL except where marked); `line` is
55// the call's line in the source the transpiler read.
56// pine_timezone_stop is guarded separately by PINEFORGE_HAS_TIMEZONE_STOP_V1,
57// with pine_runtime_error(std::string(english)) in its #else arm. Its zone
58// pointer may name the script's runtime timezone argument, rather than a
59// literal. Callers must pass english WITHOUT a prefix: the stop adds
60// run_error_bar_prefix() once ("Error on bar N: ", or
61// "Error before the first bar: " without a bar context) and carries the
62// integer run_error_bar_index() as bar_index.
63//
64// pine_runtime_error(const std::string& message) (log.hpp)
65// -> strategy_runtime_error {}
66// pine_no_data_stop(const char* function, const char* call,
67// std::int32_t line, const char* english)
68// -> no_data_request {function, call, line}
69// function: request.financial | request.earnings | request.dividends |
70// request.splits | request.footprint | request.economic |
71// request.quandl | request.seed | request.currency_rate
72// pine_other_symbol_stop(const char* function,
73// const char* symbol_literal_or_null,
74// const char* call, std::int32_t line,
75// const char* english)
76// -> other_symbol_request {function, symbol?, call, line}
77// function: request.security | request.security_lower_tf; symbol only
78// when the call spells it as a literal (NULL otherwise)
79// pine_array_stop(const char* reason, const char* method_or_null,
80// const char* english)
81// -> pine_array_error {reason, method?}
82// reason: index_out_of_bounds | slice_range_inverted |
83// empty_array_access | size_invalid
84// method: new | get | set | insert | remove | percentrank | fill |
85// slice | first | last | pop | shift
86// pine_collection_stop(const char* collection, const char* reason,
87// const char* english)
88// collection: array | matrix (any other collection: engine_invariant)
89// reason historical_modified -> pine_array_error {reason, collection}
90// reason na_reference -> pine_na_reference {object: collection}
91// pine_na_stop(const char* object, const char* english)
92// -> pine_na_reference {object}
93// object: array | matrix | map | line | box | label | linefill |
94// polyline | table | udt_object
95// pine_limit_stop(const char* limit, std::int64_t max, const char* english)
96// -> pine_runtime_limit {limit, max}
97// limit: map_pairs | max_bars_back | matrix_elements | udt_objects |
98// drawing_ids | live_drawings;
99// max is the limit's engine or transpiler constant (pass -1 for none)
100// pine_unsupported_stop(const char* reason, std::int32_t line,
101// const char* english)
102// -> request_unsupported {reason, line}
103// reason: lower_tf_lookahead_or_gaps | nested_heikinashi_request
104// (line -1: none)
105// pine_string_stop(const char* reason, const char* english)
106// -> pine_string_error {reason}
107// reason: substring_out_of_range | format_index_overflow |
108// invalid_regex_pattern | regex_resource_limit
109// pine_timezone_stop(const char* function, const char* zone, const char* english)
110// -> pine_timezone_error {bar_index, function, zone} (TradingView RE10133)
111// function: time | time_close | timestamp | hour | minute | second |
112// dayofmonth | dayofweek | month | year | weekofyear |
113// format_time (str.format_time)
114// zone: the refused timezone argument, which may be script-computed
115// bar_index: the current engine bar, or -1 before the first bar
116// pine_engine_invariant(const char* english)
117// -> engine_invariant {}
118//
119// note_run_failure(BacktestEngine&, const char* entrypoint,
120// const std::exception&)
121// the generated wrapper's catch: writes "<entrypoint>: <what()>" (the
122// text it writes today) with the exception's code;
123// note_run_failure_unknown(BacktestEngine&, const char* entrypoint)
124// its catch (...): "<entrypoint>: unknown C++ exception",
125// engine_unclassified_error;
126// note_run_failure(BacktestEngine&, std::string text, RunFailureCode,
127// const RunFailureArgs&)
128// a latched setter refusal: setting_rejected with its entrypoint and
129// reason;
130// note_run_failure(BacktestEngine&, std::string text,
131// const RunFailureValue&)
132// the same refusal with the value its RunFailureInfo holds.
133//
134// The latched setter failure also uses these names: RunFailureInfo as a
135// public base of its own exception type (beside
136// checked_settings::LatchedSettingsFailure) and as a copy-assignable member,
137// built with the (RunFailureCode, const RunFailureArgs&) constructor and read
138// with run_failure(); RunFailureValue; and the codes RunFailureCode::none,
139// ::setting_rejected and ::out_of_memory. An exception thrown where the script
140// is prepared that already carries a code keeps it; a latched failure without
141// one reads setting_rejected.
142// ---------------------------------------------------------------------------
143
145
146#include <cstddef>
147#include <cstdint>
148#include <cstring>
149#include <exception>
150#include <memory>
151#include <optional>
152#include <stdexcept>
153#include <string>
154#include <string_view>
155#include <type_traits>
156#include <utility>
157#include <vector>
158
159#define PINEFORGE_HAS_RUN_FAILURE_CODES_V1 1
160#define PINEFORGE_HAS_RUN_FAILURE_VALIDATION_V1 1
161#define PINEFORGE_HAS_TIMEZONE_STOP_V1 1
162
163namespace pineforge {
164
165inline namespace engine_script_run_v20 {
166class BacktestEngine;
167}
168class OwnedStorage; // include/pineforge/owned_storage.hpp
169
170/// The class a code belongs to (the catalog's `class`).
182
183/// An argument's kind (the catalog's `kind`).
184enum class RunFailureArgKind : std::uint8_t {
193 // The kinds below are appended, so every earlier kind keeps its value.
194 // string: text. nullable_string: text or a JSON null. scalar: text, an
195 // integer, a finite number, a boolean or a JSON null. None takes an array
196 // or an object.
200 // Q7: exactly a JSON true/false, with all earlier kind values preserved.
202};
203
204/// One typed argument as a raise site spells it. `name` is a literal; a text
205/// value is copied.
207 // boolean and null_value are appended, so the earlier values keep theirs. A
208 // boolean is held in `integer` (0 or 1) and serializes as true or false; a
209 // null_value holds nothing and serializes as null. Neither is ever a string.
210 enum class Type : std::uint8_t { text, integer, number, boolean, null_value };
211 const char* name = "";
213 std::string text;
214 std::int64_t integer = 0;
215 double number = 0.0;
216
217 // Out of line (src/run_failure.cpp): a literal value is handed over by
218 // address, so it stays one contiguous string wherever it is compiled.
219 RunFailureArg(const char* arg_name, const char* value);
220 RunFailureArg(const char* arg_name, std::string value)
221 : name(arg_name), text(std::move(value)) {}
222 // A JSON null, spelled with the literal nullptr. A `const char*` variable
223 // that happens to be null still reads as the empty text, as it always did.
224 RunFailureArg(const char* arg_name, std::nullptr_t)
225 : name(arg_name), type(Type::null_value) {}
226 // A JSON true or false. Only an argument of exactly type bool takes it: no
227 // pointer or integer converts to a boolean here.
228 template <typename Boolean,
229 typename std::enable_if<std::is_same<Boolean, bool>::value, int>::type = 0>
230 RunFailureArg(const char* arg_name, Boolean value)
231 : name(arg_name), type(Type::boolean), integer(value ? 1 : 0) {}
232 template <typename Integer,
233 typename std::enable_if<std::is_integral<Integer>::value
234 && !std::is_same<Integer, bool>::value, int>::type = 0>
235 RunFailureArg(const char* arg_name, Integer value)
236 : name(arg_name), type(Type::integer), integer(static_cast<std::int64_t>(value)) {}
237 template <typename Floating,
238 typename std::enable_if<std::is_floating_point<Floating>::value, int>::type = 0>
239 RunFailureArg(const char* arg_name, Floating value)
240 : name(arg_name), type(Type::number), number(static_cast<double>(value)) {}
241};
242
243using RunFailureArgs = std::vector<RunFailureArg>;
244
245/// A validated code and its canonical arguments: the JSON object with its keys
246/// sorted and no whitespace, or null for a code without arguments ("{}").
249 std::shared_ptr<const std::string> args;
250
251 // External ownership of `args` only; the containing owner counts this
252 // inline value. JSON minted by make_run_failure is one real allocation
253 // domain (string object and shared control requests, their ledger and
254 // records, the string's own buffer), recognized through std::get_deleter
255 // and counted once per walk. A truly empty `args` owns nothing. Any other
256 // control, a non-owning alias, or a pointee other than the minted string
257 // is reported incomplete and never traversed as owned. Preserves errno;
258 // follows the owner's serialized execution like OwnedAllocator.
259 void observe_owned_storage(OwnedStorage& out) const noexcept;
260};
261
262/// Validate `args` against `code`'s registry entry and canonicalize them. Any
263/// violation yields engine_invariant without arguments. Allocation failure
264/// yields out_of_memory.
266
268
271 std::optional<RunFailureValue> value;
272};
273
274/// Resolve an exact catalog name (excluding none) and validate/canonicalize
275/// through the same path as make_run_failure. Only accepted carries a value;
276/// unknown names take precedence over argument errors. Allocation or other
277/// implementation failure yields unavailable, never an accepted fallback code.
279 std::string_view name, const RunFailureArgs& args) noexcept;
280
281/// The code's catalog name ("" for none or an unknown value).
282const char* run_failure_code_name(RunFailureCode code) noexcept;
283/// The code's catalog class and retryable flag.
286
287/// Stops using TradingView's text prepend "Error on bar N: " when a bar
288/// context is installed, otherwise "Error before the first bar: ".
290
291/// The same context's current bar index, or -1 when no context is installed.
292std::int64_t run_error_bar_index() noexcept;
293
294/// The code an exception carries: a coded exception's own; else the safety
295/// net by type (std::bad_alloc -> out_of_memory, std::logic_error ->
296/// engine_invariant, other -> engine_unclassified_error).
297RunFailureValue classify_run_failure(const std::exception& error) noexcept;
298
299/// The code carried beside a thrown exception. A mixin: it adds no base of
300/// std::exception, so coded<Base> is still exactly a Base to every catch.
302public:
303 RunFailureInfo(RunFailureCode code, const RunFailureArgs& args) noexcept
304 : value_(make_run_failure(code, args)) {}
305 // An already validated value (a code another site recorded, carried on).
306 explicit RunFailureInfo(RunFailureValue value) noexcept : value_(std::move(value)) {}
307 RunFailureInfo(const RunFailureInfo&) noexcept = default;
308 RunFailureInfo& operator=(const RunFailureInfo&) noexcept = default;
310
311 RunFailureCode run_failure_code() const noexcept { return value_.code; }
312 const RunFailureValue& run_failure() const noexcept { return value_; }
313
314private:
315 RunFailureValue value_;
316};
317
318/// `Base` with a code: throw coded<std::invalid_argument>(code, {args}, text).
319template <class Base>
320class coded : public Base, public RunFailureInfo {
321public:
322 coded(RunFailureCode code, const RunFailureArgs& args, const std::string& what)
323 : Base(what), RunFailureInfo(code, args) {}
324 coded(RunFailureCode code, const RunFailureArgs& args, const char* what)
325 : Base(what), RunFailureInfo(code, args) {}
326 // Keep structured exception context (for example system_error::code())
327 // when the base cannot be reconstructed from its English text alone.
328 coded(RunFailureCode code, const RunFailureArgs& args, const Base& error)
329 : Base(error), RunFailureInfo(code, args) {}
330 coded(RunFailureValue value, const std::string& what)
331 : Base(what), RunFailureInfo(std::move(value)) {}
332 coded(RunFailureValue value, const char* what)
333 : Base(what), RunFailureInfo(std::move(value)) {}
334};
335
336// The record beside BacktestEngine::last_error(): writes the text and the
337// code together, so they never disagree. Defined with the execution consumer
338// that stores the record (src/run_failure.cpp).
339void note_run_failure(BacktestEngine& engine, std::string text, RunFailureCode code,
340 const RunFailureArgs& args = {});
341// The same for a literal text (preferred for one): taken by address.
342void note_run_failure(BacktestEngine& engine, const char* text, RunFailureCode code,
343 const RunFailureArgs& args = {});
344void note_run_failure(BacktestEngine& engine, std::string text, const RunFailureValue& value);
345void note_run_failure(BacktestEngine& engine, const char* entrypoint,
346 const std::exception& error);
347void note_run_failure_unknown(BacktestEngine& engine, const char* entrypoint);
348void clear_run_failure(BacktestEngine& engine) noexcept;
349
350/// The getters' answers (strategy_get_last_error_code / _args): the stored code
351/// while its text is the engine's last error; engine_unclassified_error for a
352/// non-empty error no coded site wrote; "" when there is no failure.
353const char* run_failure_code_of(const BacktestEngine& engine) noexcept;
354const char* run_failure_args_of(const BacktestEngine& engine) noexcept;
355/// The recorded value under the same rule (none when there is no failure).
357
358// ---------------------------------------------------------------------------
359// The generated-code helpers (the codegen contract above).
360
361[[noreturn]] inline void pine_no_data_stop(const char* function, const char* call,
362 std::int32_t line, const char* english) {
365 {{"function", function}, {"call", call}, {"line", line}}, english ? english : "");
366}
367
368[[noreturn]] inline void pine_other_symbol_stop(const char* function,
369 const char* symbol_literal_or_null,
370 const char* call, std::int32_t line,
371 const char* english) {
372 RunFailureArgs args{{"function", function}, {"call", call}, {"line", line}};
373 if (symbol_literal_or_null) args.emplace_back("symbol", symbol_literal_or_null);
375 english ? english : "");
376}
377
378[[noreturn]] inline void pine_array_stop(const char* reason, const char* method_or_null,
379 const char* english) {
380 RunFailureArgs args{{"reason", reason}};
381 if (method_or_null) args.emplace_back("method", method_or_null);
383 english ? english : "");
384}
385
386[[noreturn]] inline void pine_collection_stop(const char* collection, const char* reason,
387 const char* english) {
388 const char* text = english ? english : "";
389 // Only the contract's two collections: pine_na_reference alone would also
390 // take the other objects of its list.
391 const bool listed = collection && (std::strcmp(collection, "array") == 0
392 || std::strcmp(collection, "matrix") == 0);
393 if (listed && reason && std::strcmp(reason, "na_reference") == 0) {
395 {{"object", collection}}, text);
396 }
397 if (listed && reason && std::strcmp(reason, "historical_modified") == 0) {
400 {{"reason", "historical_modified"}, {"collection", collection}}, text);
401 }
403}
404
405[[noreturn]] inline void pine_na_stop(const char* object, const char* english) {
407 english ? english : "");
408}
409
410[[noreturn]] inline void pine_limit_stop(const char* limit, std::int64_t max,
411 const char* english) {
412 RunFailureArgs args{{"limit", limit}};
413 if (max >= 0) args.emplace_back("max", max);
415 english ? english : "");
416}
417
418[[noreturn]] inline void pine_unsupported_stop(const char* reason, std::int32_t line,
419 const char* english) {
420 RunFailureArgs args{{"reason", reason}};
421 if (line >= 0) args.emplace_back("line", line);
423 english ? english : "");
424}
425
426[[noreturn]] inline void pine_string_stop(const char* reason, const char* english) {
428 english ? english : "");
429}
430
431[[noreturn]] inline void pine_timezone_stop(const char* function, const char* zone,
432 const char* english) {
435 {{"bar_index", run_error_bar_index()}, {"function", function}, {"zone", zone}},
436 run_error_bar_prefix() + (english ? english : ""));
437}
438
439[[noreturn]] inline void pine_engine_invariant(const char* english) {
441 english ? english : "");
442}
443
444} // namespace pineforge
RunFailureCode run_failure_code() const noexcept
RunFailureInfo(const RunFailureInfo &) noexcept=default
RunFailureInfo(RunFailureValue value) noexcept
const RunFailureValue & run_failure() const noexcept
RunFailureInfo(RunFailureCode code, const RunFailureArgs &args) noexcept
RunFailureInfo & operator=(const RunFailureInfo &) noexcept=default
Base with a code: throw coded<std::invalid_argument>(code, {args}, text).
coded(RunFailureValue value, const char *what)
coded(RunFailureCode code, const RunFailureArgs &args, const char *what)
coded(RunFailureCode code, const RunFailureArgs &args, const std::string &what)
coded(RunFailureValue value, const std::string &what)
coded(RunFailureCode code, const RunFailureArgs &args, const Base &error)
RunFailureValidation validate_run_failure_name(std::string_view name, const RunFailureArgs &args) noexcept
Resolve an exact catalog name (excluding none) and validate/canonicalize through the same path as mak...
bool run_failure_code_retryable(RunFailureCode code) noexcept
const char * run_failure_args_of(const BacktestEngine &engine) noexcept
void pine_unsupported_stop(const char *reason, std::int32_t line, const char *english)
void pine_string_stop(const char *reason, const char *english)
void note_run_failure(BacktestEngine &engine, std::string text, RunFailureCode code, const RunFailureArgs &args={})
void clear_run_failure(BacktestEngine &engine) noexcept
void pine_timezone_stop(const char *function, const char *zone, const char *english)
RunFailureValue make_run_failure(RunFailureCode code, const RunFailureArgs &args) noexcept
Validate args against code's registry entry and canonicalize them.
void pine_limit_stop(const char *limit, std::int64_t max, const char *english)
RunFailureClass run_failure_code_class(RunFailureCode code) noexcept
The code's catalog class and retryable flag.
RunFailureValue run_failure_value_of(const BacktestEngine &engine) noexcept
The recorded value under the same rule (none when there is no failure).
RunFailureValue classify_run_failure(const std::exception &error) noexcept
The code an exception carries: a coded exception's own; else the safety net by type (std::bad_alloc -...
std::string run_error_bar_prefix()
Stops using TradingView's text prepend "Error on bar N: " when a bar context is installed,...
RunFailureClass
The class a code belongs to (the catalog's class).
const char * run_failure_code_of(const BacktestEngine &engine) noexcept
The getters' answers (strategy_get_last_error_code / _args): the stored code while its text is the en...
void pine_array_stop(const char *reason, const char *method_or_null, const char *english)
RunFailureArgKind
An argument's kind (the catalog's kind).
void pine_other_symbol_stop(const char *function, const char *symbol_literal_or_null, const char *call, std::int32_t line, const char *english)
std::int64_t run_error_bar_index() noexcept
The same context's current bar index, or -1 when no context is installed.
std::vector< RunFailureArg > RunFailureArgs
const char * run_failure_code_name(RunFailureCode code) noexcept
The code's catalog name ("" for none or an unknown value).
void pine_na_stop(const char *object, const char *english)
void pine_engine_invariant(const char *english)
void note_run_failure_unknown(BacktestEngine &engine, const char *entrypoint)
void pine_collection_stop(const char *collection, const char *reason, const char *english)
void pine_no_data_stop(const char *function, const char *call, std::int32_t line, const char *english)
RunFailureArg(const char *arg_name, const char *value)
RunFailureArg(const char *arg_name, std::string value)
RunFailureArg(const char *arg_name, Integer value)
RunFailureArg(const char *arg_name, std::nullptr_t)
RunFailureArg(const char *arg_name, Floating value)
RunFailureArg(const char *arg_name, Boolean value)
std::optional< RunFailureValue > value
RunFailureValidationStatus status
A validated code and its canonical arguments: the JSON object with its keys sorted and no whitespace,...
void observe_owned_storage(OwnedStorage &out) const noexcept
std::shared_ptr< const std::string > args