1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 f64,7 rc::Rc,8};910pub use arrays::*;11pub use compat::*;12pub use encoding::*;13pub use hash::*;14use jrsonnet_evaluator::{15 IStr, InitialContextBuilder, NumValue, ObjValue, ObjValueBuilder, Source, Thunk, Val,16 error::Result,17 function::{CallLocation, FuncVal, builtin_id},18 tla::TlaArg,19 trace::PathResolver,20 typed::SerializeTypedObj as _,21};22use jrsonnet_gcmodule::{Acyclic, Cc, Trace};23use jrsonnet_macros::{IntoUntyped, Typed};24pub use manifest::*;25pub use math::*;26pub use misc::*;27pub use objects::*;28pub use operator::*;29pub use parse::*;30pub use sets::*;31pub use sort::*;32pub use strings::*;33pub use types::*;3435#[cfg(feature = "exp-regex")]36pub use crate::regex::*;3738mod arrays;39mod compat;40mod encoding;41mod hash;42mod keyf;43mod manifest;44mod math;45mod misc;46mod objects;47mod operator;48mod parse;49#[cfg(feature = "exp-regex")]50mod regex;51mod sets;52mod sort;53mod strings;54mod types;5556#[derive(Typed, IntoUntyped, Default)]57#[allow(non_snake_case)]58struct Builtins {59 #[typed(method)]60 id: builtin_id,61 62 #[typed(method, rename = "type")]63 r#type: builtin_type,64 #[typed(method)]65 isString: builtin_is_string,66 #[typed(method)]67 isNumber: builtin_is_number,68 #[typed(method)]69 isBoolean: builtin_is_boolean,70 #[typed(method)]71 isObject: builtin_is_object,72 #[typed(method)]73 isArray: builtin_is_array,74 #[typed(method)]75 isFunction: builtin_is_function,76 #[typed(method)]77 isNull: builtin_is_null,78 79 #[typed(method)]80 makeArray: builtin_make_array,81 #[typed(method)]82 repeat: builtin_repeat,83 #[typed(method)]84 slice: builtin_slice,85 #[typed(method)]86 map: builtin_map,87 #[typed(method)]88 mapWithIndex: builtin_map_with_index,89 #[typed(method)]90 mapWithKey: builtin_map_with_key,91 #[typed(method)]92 flatMap: builtin_flatmap,93 #[typed(method)]94 filter: builtin_filter,95 #[typed(method)]96 foldl: builtin_foldl,97 #[typed(method)]98 foldr: builtin_foldr,99 #[typed(method)]100 range: builtin_range,101 #[typed(method)]102 join: builtin_join,103 #[typed(method)]104 lines: builtin_lines,105 #[typed(method)]106 resolvePath: builtin_resolve_path,107 #[typed(method)]108 deepJoin: builtin_deep_join,109 #[typed(method)]110 reverse: builtin_reverse,111 #[typed(method)]112 any: builtin_any,113 #[typed(method)]114 all: builtin_all,115 #[typed(method)]116 member: builtin_member,117 #[typed(method)]118 find: builtin_find,119 #[typed(method)]120 contains: builtin_contains,121 #[typed(method)]122 count: builtin_count,123 #[typed(method)]124 avg: builtin_avg,125 #[typed(method)]126 removeAt: builtin_remove_at,127 #[typed(method)]128 remove: builtin_remove,129 #[typed(method)]130 flattenArrays: builtin_flatten_arrays,131 #[typed(method)]132 flattenDeepArray: builtin_flatten_deep_array,133 #[typed(method)]134 prune: builtin_prune,135 #[typed(method)]136 filterMap: builtin_filter_map,137 138 #[typed(method)]139 abs: builtin_abs,140 #[typed(method)]141 sign: builtin_sign,142 #[typed(method)]143 max: builtin_max,144 #[typed(method)]145 min: builtin_min,146 #[typed(method)]147 clamp: builtin_clamp,148 #[typed(method)]149 sum: builtin_sum,150 #[typed(method)]151 modulo: builtin_modulo,152 #[typed(method)]153 floor: builtin_floor,154 #[typed(method)]155 ceil: builtin_ceil,156 #[typed(method)]157 log: builtin_log,158 #[typed(method)]159 log2: builtin_log2,160 #[typed(method)]161 log10: builtin_log10,162 #[typed(method)]163 pow: builtin_pow,164 #[typed(method)]165 sqrt: builtin_sqrt,166 #[typed(method)]167 sin: builtin_sin,168 #[typed(method)]169 cos: builtin_cos,170 #[typed(method)]171 tan: builtin_tan,172 #[typed(method)]173 asin: builtin_asin,174 #[typed(method)]175 acos: builtin_acos,176 #[typed(method)]177 atan: builtin_atan,178 #[typed(method)]179 atan2: builtin_atan2,180 #[typed(method)]181 exp: builtin_exp,182 #[typed(method)]183 mantissa: builtin_mantissa,184 #[typed(method)]185 exponent: builtin_exponent,186 #[typed(method)]187 round: builtin_round,188 #[typed(method)]189 isEven: builtin_is_even,190 #[typed(method)]191 isOdd: builtin_is_odd,192 #[typed(method)]193 isInteger: builtin_is_integer,194 #[typed(method)]195 isDecimal: builtin_is_decimal,196 #[typed(method)]197 deg2rad: builtin_deg2rad,198 #[typed(method)]199 rad2deg: builtin_rad2deg,200 #[typed(method)]201 hypot: builtin_hypot,202 203 #[typed(rename = "mod", method)]204 r#mod: builtin_mod,205 #[typed(method)]206 primitiveEquals: builtin_primitive_equals,207 #[typed(method)]208 equals: builtin_equals,209 #[typed(method)]210 xor: builtin_xor,211 #[typed(method)]212 xnor: builtin_xnor,213 #[typed(method)]214 format: builtin_format,215 216 #[typed(method)]217 sort: builtin_sort,218 #[typed(method)]219 uniq: builtin_uniq,220 #[typed(method)]221 set: builtin_set,222 #[typed(method)]223 minArray: builtin_min_array,224 #[typed(method)]225 maxArray: builtin_max_array,226 227 #[typed(method)]228 md5: builtin_md5,229 #[typed(method)]230 sha1: builtin_sha1,231 #[typed(method)]232 sha256: builtin_sha256,233 #[typed(method)]234 sha512: builtin_sha512,235 #[typed(method)]236 sha3: builtin_sha3,237 238 #[typed(method)]239 encodeUTF8: builtin_encode_utf8,240 #[typed(method)]241 decodeUTF8: builtin_decode_utf8,242 #[typed(method)]243 base64: builtin_base64,244 #[typed(method)]245 base64Decode: builtin_base64_decode,246 #[typed(method)]247 base64DecodeBytes: builtin_base64_decode_bytes,248 249 #[typed(method)]250 objectFieldsEx: builtin_object_fields_ex,251 #[typed(method)]252 objectFields: builtin_object_fields,253 #[typed(method)]254 objectFieldsAll: builtin_object_fields_all,255 #[typed(method)]256 objectValues: builtin_object_values,257 #[typed(method)]258 objectValuesAll: builtin_object_values_all,259 #[typed(method)]260 objectKeysValues: builtin_object_keys_values,261 #[typed(method)]262 objectKeysValuesAll: builtin_object_keys_values_all,263 #[typed(method)]264 objectHasEx: builtin_object_has_ex,265 #[typed(method)]266 objectHas: builtin_object_has,267 #[typed(method)]268 objectHasAll: builtin_object_has_all,269 #[typed(method)]270 objectRemoveKey: builtin_object_remove_key,271 272 #[typed(method)]273 escapeStringJson: builtin_escape_string_json,274 #[typed(method)]275 escapeStringPython: builtin_escape_string_python,276 #[typed(method)]277 escapeStringXML: builtin_escape_string_xml,278 #[typed(method)]279 manifestJsonEx: builtin_manifest_json_ex,280 #[typed(method)]281 manifestJson: builtin_manifest_json,282 #[typed(method)]283 manifestJsonMinified: builtin_manifest_json_minified,284 #[typed(method)]285 manifestYamlDoc: builtin_manifest_yaml_doc,286 #[typed(method)]287 manifestYamlStream: builtin_manifest_yaml_stream,288 #[typed(method)]289 manifestTomlEx: builtin_manifest_toml_ex,290 #[typed(method)]291 manifestToml: builtin_manifest_toml,292 #[typed(method)]293 toString: builtin_to_string,294 #[typed(method)]295 manifestPython: builtin_manifest_python,296 #[typed(method)]297 manifestPythonVars: builtin_manifest_python_vars,298 #[typed(method)]299 manifestXmlJsonml: builtin_manifest_xml_jsonml,300 #[typed(method)]301 manifestIni: builtin_manifest_ini,302 303 #[typed(method)]304 parseJson: builtin_parse_json,305 #[typed(method)]306 parseYaml: builtin_parse_yaml,307 308 #[typed(method)]309 codepoint: builtin_codepoint,310 #[typed(method)]311 substr: builtin_substr,312 #[typed(method)]313 char: builtin_char,314 #[typed(method)]315 strReplace: builtin_str_replace,316 #[typed(method)]317 escapeStringBash: builtin_escape_string_bash,318 #[typed(method)]319 escapeStringDollars: builtin_escape_string_dollars,320 #[typed(method)]321 isEmpty: builtin_is_empty,322 #[typed(method)]323 equalsIgnoreCase: builtin_equals_ignore_case,324 #[typed(method)]325 splitLimit: builtin_splitlimit,326 #[typed(method)]327 splitLimitR: builtin_splitlimitr,328 #[typed(method)]329 split: builtin_split,330 #[typed(method)]331 asciiUpper: builtin_ascii_upper,332 #[typed(method)]333 asciiLower: builtin_ascii_lower,334 #[typed(method)]335 findSubstr: builtin_find_substr,336 #[typed(method)]337 parseInt: builtin_parse_int,338 #[cfg(feature = "exp-bigint")]339 #[typed(method)]340 bigint: builtin_bigint,341 #[typed(method)]342 parseOctal: builtin_parse_octal,343 #[typed(method)]344 parseHex: builtin_parse_hex,345 #[typed(method)]346 stringChars: builtin_string_chars,347 #[typed(method)]348 lstripChars: builtin_lstrip_chars,349 #[typed(method)]350 rstripChars: builtin_rstrip_chars,351 #[typed(method)]352 stripChars: builtin_strip_chars,353 #[typed(method)]354 trim: builtin_trim,355 356 #[typed(method)]357 length: builtin_length,358 #[typed(method)]359 get: builtin_get,360 #[typed(method)]361 startsWith: builtin_starts_with,362 #[typed(method)]363 endsWith: builtin_ends_with,364 #[typed(method)]365 assertEqual: builtin_assert_equal,366 #[typed(method)]367 mergePatch: builtin_merge_patch,368 369 #[typed(method)]370 setMember: builtin_set_member,371 #[typed(method)]372 setInter: builtin_set_inter,373 #[typed(method)]374 setDiff: builtin_set_diff,375 #[typed(method)]376 setUnion: builtin_set_union,377 378 #[cfg(feature = "exp-regex")]379 #[typed(method)]380 regexQuoteMeta: builtin_regex_quote_meta,381 382 #[typed(method)]383 __compare: builtin___compare,384 #[typed(method)]385 __compare_array: builtin___compare_array,386 #[typed(method)]387 __array_less: builtin___array_less,388 #[typed(method)]389 __array_greater: builtin___array_greater,390 #[typed(method)]391 __array_less_or_equal: builtin___array_less_or_equal,392 #[typed(method)]393 __array_greater_or_equal: builtin___array_greater_or_equal,394}395396#[allow(clippy::too_many_lines)]397pub fn stdlib_uncached(settings: Cc<RefCell<Settings>>) -> ObjValue {398 let mut builder = ObjValueBuilder::new();399400 let builtins = Builtins::default();401 builtins.serialize(&mut builder).expect("no conflicts");402403 builder.method(404 "extVar",405 builtin_ext_var {406 settings: settings.clone(),407 },408 );409 builder.method(410 "native",411 builtin_native {412 settings: settings.clone(),413 },414 );415 builder.method("trace", builtin_trace { settings });416417 builder.field("pi").hide().value(Val::Num(418 NumValue::new(f64::consts::PI).expect("pi is finite"),419 ));420421 #[cfg(feature = "exp-regex")]422 {423 424 let regex_cache = RegexCache::default();425 builder.method(426 "regexFullMatch",427 builtin_regex_full_match {428 cache: regex_cache.clone(),429 },430 );431 builder.method(432 "regexPartialMatch",433 builtin_regex_partial_match {434 cache: regex_cache.clone(),435 },436 );437 builder.method(438 "regexReplace",439 builtin_regex_replace {440 cache: regex_cache.clone(),441 },442 );443 builder.method(444 "regexGlobalReplace",445 builtin_regex_global_replace { cache: regex_cache },446 );447 };448449 builder.build()450}451452pub trait TracePrinter: Acyclic {453 fn print_trace(&self, loc: CallLocation, value: IStr);454}455456#[derive(Acyclic)]457pub struct StdTracePrinter {458 resolver: PathResolver,459}460impl StdTracePrinter {461 pub fn new(resolver: PathResolver) -> Self {462 Self { resolver }463 }464}465impl TracePrinter for StdTracePrinter {466 fn print_trace(&self, loc: CallLocation, value: IStr) {467 eprint!("TRACE:");468 if let Some(loc) = loc.0 {469 let locs = loc.0.map_source_locations(&[loc.1]);470 eprint!(471 " {}:{}",472 loc.0.source_path().path().map_or_else(473 || loc.0.source_path().to_string(),474 |p| self.resolver.resolve(p)475 ),476 locs[0].line477 );478 }479 eprintln!(" {value}");480 }481}482483#[derive(Clone, Trace)]484pub struct Settings {485 486 pub ext_vars: HashMap<IStr, TlaArg>,487 488 pub ext_natives: HashMap<IStr, FuncVal>,489 490 pub trace_printer: Rc<dyn TracePrinter>,491 492 pub path_resolver: PathResolver,493}494495#[derive(Trace, Clone)]496pub struct ContextInitializer {497 498 stdlib_obj: ObjValue,499 settings: Cc<RefCell<Settings>>,500}501impl ContextInitializer {502 pub fn new(resolver: PathResolver) -> Self {503 let settings = Settings {504 ext_vars: HashMap::new(),505 ext_natives: HashMap::new(),506 trace_printer: Rc::new(StdTracePrinter::new(resolver.clone())),507 path_resolver: resolver,508 };509 let settings = Cc::new(RefCell::new(settings));510 let stdlib_obj = stdlib_uncached(settings.clone());511 Self {512 stdlib_obj,513 settings,514 }515 }516 pub fn settings(&self) -> Ref<'_, Settings> {517 self.settings.borrow()518 }519 pub fn settings_mut(&self) -> RefMut<'_, Settings> {520 self.settings.borrow_mut()521 }522 pub fn add_ext_var(&self, name: IStr, value: Val) {523 self.settings_mut()524 .ext_vars525 .insert(name, TlaArg::Val(value));526 }527 pub fn add_ext_str(&self, name: IStr, value: IStr) {528 self.settings_mut()529 .ext_vars530 .insert(name, TlaArg::String(value));531 }532 pub fn add_ext_code(&self, name: &str, code: impl AsRef<str>) -> Result<()> {533 534 self.settings_mut()535 .ext_vars536 .insert(name.into(), TlaArg::InlineCode(code.as_ref().to_owned()));537 Ok(())538 }539 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {540 self.settings_mut()541 .ext_natives542 .insert(name.into(), cb.into());543 }544}545impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {546 fn populate(&self, source: Source, builder: &mut InitialContextBuilder) {547 let mut std = ObjValueBuilder::new();548 std.with_super(self.stdlib_obj.clone());549 std.field("thisFile").hide().value({550 let source_path = source.source_path();551 source_path.path().map_or_else(552 || source_path.to_string(),553 |p| self.settings().path_resolver.resolve(p),554 )555 });556 let stdlib_with_this_file = std.build();557558 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));559 }560 fn as_any(&self) -> &dyn std::any::Any {561 self562 }563}