1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 rc::Rc,7};89pub use arrays::*;10pub use compat::*;11pub use encoding::*;12pub use hash::*;13use jrsonnet_evaluator::{14 error::{ErrorKind::*, Result},15 function::{CallLocation, FuncVal, TlaArg},16 tb,17 trace::PathResolver,18 ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,19};20use jrsonnet_gcmodule::Trace;21use jrsonnet_parser::Source;22pub use manifest::*;23pub use math::*;24pub use misc::*;25pub use objects::*;26pub use operator::*;27pub use parse::*;28pub use sets::*;29pub use sort::*;30pub use strings::*;31pub use types::*;3233#[cfg(feature = "exp-regex")]34pub use crate::regex::*;3536mod arrays;37mod compat;38mod encoding;39mod expr;40mod hash;41mod manifest;42mod math;43mod misc;44mod objects;45mod operator;46mod parse;47#[cfg(feature = "exp-regex")]48mod regex;49mod sets;50mod sort;51mod strings;52mod types;5354#[allow(clippy::too_many_lines)]55pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {56 let mut builder = ObjValueBuilder::new();5758 let expr = expr::stdlib_expr();59 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)60 .expect("stdlib.jsonnet should have no errors")61 .as_obj()62 .expect("stdlib.jsonnet should evaluate to object");6364 builder.with_super(eval);6566 67 for (name, builtin) in [68 69 ("type", builtin_type::INST),70 ("isString", builtin_is_string::INST),71 ("isNumber", builtin_is_number::INST),72 ("isBoolean", builtin_is_boolean::INST),73 ("isObject", builtin_is_object::INST),74 ("isArray", builtin_is_array::INST),75 ("isFunction", builtin_is_function::INST),76 77 ("makeArray", builtin_make_array::INST),78 ("repeat", builtin_repeat::INST),79 ("slice", builtin_slice::INST),80 ("map", builtin_map::INST),81 ("mapWithIndex", builtin_map_with_index::INST),82 ("flatMap", builtin_flatmap::INST),83 ("filter", builtin_filter::INST),84 ("foldl", builtin_foldl::INST),85 ("foldr", builtin_foldr::INST),86 ("range", builtin_range::INST),87 ("join", builtin_join::INST),88 ("lines", builtin_lines::INST),89 ("deepJoin", builtin_deep_join::INST),90 ("reverse", builtin_reverse::INST),91 ("any", builtin_any::INST),92 ("all", builtin_all::INST),93 ("member", builtin_member::INST),94 ("contains", builtin_contains::INST),95 ("count", builtin_count::INST),96 ("avg", builtin_avg::INST),97 ("removeAt", builtin_remove_at::INST),98 ("remove", builtin_remove::INST),99 ("flattenArrays", builtin_flatten_arrays::INST),100 ("flattenDeepArray", builtin_flatten_deep_array::INST),101 ("prune", builtin_prune::INST),102 ("filterMap", builtin_filter_map::INST),103 104 ("abs", builtin_abs::INST),105 ("sign", builtin_sign::INST),106 ("max", builtin_max::INST),107 ("min", builtin_min::INST),108 ("clamp", builtin_clamp::INST),109 ("sum", builtin_sum::INST),110 ("modulo", builtin_modulo::INST),111 ("floor", builtin_floor::INST),112 ("ceil", builtin_ceil::INST),113 ("log", builtin_log::INST),114 ("pow", builtin_pow::INST),115 ("sqrt", builtin_sqrt::INST),116 ("sin", builtin_sin::INST),117 ("cos", builtin_cos::INST),118 ("tan", builtin_tan::INST),119 ("asin", builtin_asin::INST),120 ("acos", builtin_acos::INST),121 ("atan", builtin_atan::INST),122 ("atan2", builtin_atan2::INST),123 ("exp", builtin_exp::INST),124 ("mantissa", builtin_mantissa::INST),125 ("exponent", builtin_exponent::INST),126 ("round", builtin_round::INST),127 ("isEven", builtin_is_even::INST),128 ("isOdd", builtin_is_odd::INST),129 ("isInteger", builtin_is_integer::INST),130 ("isDecimal", builtin_is_decimal::INST),131 132 ("mod", builtin_mod::INST),133 ("primitiveEquals", builtin_primitive_equals::INST),134 ("equals", builtin_equals::INST),135 ("xor", builtin_xor::INST),136 ("xnor", builtin_xnor::INST),137 ("format", builtin_format::INST),138 139 ("sort", builtin_sort::INST),140 ("uniq", builtin_uniq::INST),141 ("set", builtin_set::INST),142 ("minArray", builtin_min_array::INST),143 ("maxArray", builtin_max_array::INST),144 145 ("md5", builtin_md5::INST),146 ("sha1", builtin_sha1::INST),147 ("sha256", builtin_sha256::INST),148 ("sha512", builtin_sha512::INST),149 ("sha3", builtin_sha3::INST),150 151 ("encodeUTF8", builtin_encode_utf8::INST),152 ("decodeUTF8", builtin_decode_utf8::INST),153 ("base64", builtin_base64::INST),154 ("base64Decode", builtin_base64_decode::INST),155 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),156 157 ("objectFieldsEx", builtin_object_fields_ex::INST),158 ("objectFields", builtin_object_fields::INST),159 ("objectFieldsAll", builtin_object_fields_all::INST),160 ("objectValues", builtin_object_values::INST),161 ("objectValuesAll", builtin_object_values_all::INST),162 ("objectKeysValues", builtin_object_keys_values::INST),163 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),164 ("objectHasEx", builtin_object_has_ex::INST),165 ("objectHas", builtin_object_has::INST),166 ("objectHasAll", builtin_object_has_all::INST),167 ("objectRemoveKey", builtin_object_remove_key::INST),168 169 ("escapeStringJson", builtin_escape_string_json::INST),170 ("escapeStringPython", builtin_escape_string_python::INST),171 ("escapeStringXML", builtin_escape_string_xml::INST),172 ("manifestJsonEx", builtin_manifest_json_ex::INST),173 ("manifestJson", builtin_manifest_json::INST),174 ("manifestJsonMinified", builtin_manifest_json_minified::INST),175 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),176 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),177 ("manifestTomlEx", builtin_manifest_toml_ex::INST),178 ("manifestToml", builtin_manifest_toml::INST),179 ("toString", builtin_to_string::INST),180 ("manifestPython", builtin_manifest_python::INST),181 ("manifestPythonVars", builtin_manifest_python_vars::INST),182 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),183 ("manifestIni", builtin_manifest_ini::INST),184 185 ("parseJson", builtin_parse_json::INST),186 ("parseYaml", builtin_parse_yaml::INST),187 188 ("codepoint", builtin_codepoint::INST),189 ("substr", builtin_substr::INST),190 ("char", builtin_char::INST),191 ("strReplace", builtin_str_replace::INST),192 ("escapeStringBash", builtin_escape_string_bash::INST),193 ("escapeStringDollars", builtin_escape_string_dollars::INST),194 ("isEmpty", builtin_is_empty::INST),195 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),196 ("splitLimit", builtin_splitlimit::INST),197 ("splitLimitR", builtin_splitlimitr::INST),198 ("split", builtin_split::INST),199 ("asciiUpper", builtin_ascii_upper::INST),200 ("asciiLower", builtin_ascii_lower::INST),201 ("findSubstr", builtin_find_substr::INST),202 ("parseInt", builtin_parse_int::INST),203 #[cfg(feature = "exp-bigint")]204 ("bigint", builtin_bigint::INST),205 ("parseOctal", builtin_parse_octal::INST),206 ("parseHex", builtin_parse_hex::INST),207 ("stringChars", builtin_string_chars::INST),208 ("lstripChars", builtin_lstrip_chars::INST),209 ("rstripChars", builtin_rstrip_chars::INST),210 ("stripChars", builtin_strip_chars::INST),211 212 ("length", builtin_length::INST),213 ("get", builtin_get::INST),214 ("startsWith", builtin_starts_with::INST),215 ("endsWith", builtin_ends_with::INST),216 217 ("setMember", builtin_set_member::INST),218 ("setInter", builtin_set_inter::INST),219 ("setDiff", builtin_set_diff::INST),220 ("setUnion", builtin_set_union::INST),221 222 #[cfg(feature = "exp-regex")]223 ("regexQuoteMeta", builtin_regex_quote_meta::INST),224 225 ("__compare", builtin___compare::INST),226 ("__compare_array", builtin___compare_array::INST),227 ("__array_less", builtin___array_less::INST),228 ("__array_greater", builtin___array_greater::INST),229 ("__array_less_or_equal", builtin___array_less_or_equal::INST),230 (231 "__array_greater_or_equal",232 builtin___array_greater_or_equal::INST,233 ),234 ]235 .iter()236 .copied()237 {238 builder.method(name, builtin);239 }240241 builder.method(242 "extVar",243 builtin_ext_var {244 settings: settings.clone(),245 },246 );247 builder.method(248 "native",249 builtin_native {250 settings: settings.clone(),251 },252 );253 builder.method("trace", builtin_trace { settings });254 builder.method("id", FuncVal::Id);255256 #[cfg(feature = "exp-regex")]257 {258 259 let regex_cache = RegexCache::default();260 builder.method(261 "regexFullMatch",262 builtin_regex_full_match {263 cache: regex_cache.clone(),264 },265 );266 builder.method(267 "regexPartialMatch",268 builtin_regex_partial_match {269 cache: regex_cache.clone(),270 },271 );272 builder.method(273 "regexReplace",274 builtin_regex_replace {275 cache: regex_cache.clone(),276 },277 );278 builder.method(279 "regexGlobalReplace",280 builtin_regex_global_replace { cache: regex_cache },281 );282 };283284 builder.build()285}286287pub trait TracePrinter {288 fn print_trace(&self, loc: CallLocation, value: IStr);289}290291pub struct StdTracePrinter {292 resolver: PathResolver,293}294impl StdTracePrinter {295 pub fn new(resolver: PathResolver) -> Self {296 Self { resolver }297 }298}299impl TracePrinter for StdTracePrinter {300 fn print_trace(&self, loc: CallLocation, value: IStr) {301 eprint!("TRACE:");302 if let Some(loc) = loc.0 {303 let locs = loc.0.map_source_locations(&[loc.1]);304 eprint!(305 " {}:{}",306 loc.0.source_path().path().map_or_else(307 || loc.0.source_path().to_string(),308 |p| self.resolver.resolve(p)309 ),310 locs[0].line311 );312 }313 eprintln!(" {value}");314 }315}316317pub struct Settings {318 319 pub ext_vars: HashMap<IStr, TlaArg>,320 321 pub ext_natives: HashMap<IStr, FuncVal>,322 323 pub trace_printer: Box<dyn TracePrinter>,324 325 pub path_resolver: PathResolver,326}327328fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {329 let source_name = format!("<extvar:{name}>");330 Source::new_virtual(source_name.into(), code.into())331}332333#[derive(Trace, Clone)]334pub struct ContextInitializer {335 336 #[cfg(not(feature = "legacy-this-file"))]337 context: jrsonnet_evaluator::Context,338 339 #[cfg(not(feature = "legacy-this-file"))]340 stdlib_thunk: Thunk<Val>,341 342 #[cfg(feature = "legacy-this-file")]343 stdlib_obj: ObjValue,344 settings: Rc<RefCell<Settings>>,345}346impl ContextInitializer {347 pub fn new(s: State, resolver: PathResolver) -> Self {348 let settings = Settings {349 ext_vars: HashMap::new(),350 ext_natives: HashMap::new(),351 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),352 path_resolver: resolver,353 };354 let settings = Rc::new(RefCell::new(settings));355 let stdlib_obj = stdlib_uncached(settings.clone());356 #[cfg(not(feature = "legacy-this-file"))]357 let stdlib_thunk = Thunk::evaluated(Val::Obj(stdlib_obj));358 #[cfg(feature = "legacy-this-file")]359 let _ = s;360 Self {361 #[cfg(not(feature = "legacy-this-file"))]362 context: {363 let mut context = ContextBuilder::with_capacity(s, 1);364 context.bind("std", stdlib_thunk.clone());365 context.build()366 },367 #[cfg(not(feature = "legacy-this-file"))]368 stdlib_thunk,369 #[cfg(feature = "legacy-this-file")]370 stdlib_obj,371 settings,372 }373 }374 pub fn settings(&self) -> Ref<Settings> {375 self.settings.borrow()376 }377 pub fn settings_mut(&self) -> RefMut<Settings> {378 self.settings.borrow_mut()379 }380 pub fn add_ext_var(&self, name: IStr, value: Val) {381 self.settings_mut()382 .ext_vars383 .insert(name, TlaArg::Val(value));384 }385 pub fn add_ext_str(&self, name: IStr, value: IStr) {386 self.settings_mut()387 .ext_vars388 .insert(name, TlaArg::String(value));389 }390 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {391 let code = code.into();392 let source = extvar_source(name, code.clone());393 let parsed = jrsonnet_parser::parse(394 &code,395 &jrsonnet_parser::ParserSettings {396 source: source.clone(),397 },398 )399 .map_err(|e| ImportSyntaxError {400 path: source,401 error: Box::new(e),402 })?;403 404 self.settings_mut()405 .ext_vars406 .insert(name.into(), TlaArg::Code(parsed));407 Ok(())408 }409 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {410 self.settings_mut()411 .ext_natives412 .insert(name.into(), cb.into());413 }414}415impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {416 fn reserve_vars(&self) -> usize {417 1418 }419 #[cfg(not(feature = "legacy-this-file"))]420 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {421 self.context.clone()422 }423 #[cfg(not(feature = "legacy-this-file"))]424 fn populate(&self, _for_file: Source, builder: &mut ContextBuilder) {425 builder.bind("std", self.stdlib_thunk.clone());426 }427 #[cfg(feature = "legacy-this-file")]428 fn populate(&self, source: Source, builder: &mut ContextBuilder) {429 let mut std = ObjValueBuilder::new();430 std.with_super(self.stdlib_obj.clone());431 std.field("thisFile").hide().value({432 let source_path = source.source_path();433 source_path.path().map_or_else(434 || source_path.to_string(),435 |p| self.settings().path_resolver.resolve(p),436 )437 });438 let stdlib_with_this_file = std.build();439440 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));441 }442 fn as_any(&self) -> &dyn std::any::Any {443 self444 }445}446447pub trait StateExt {448 449 fn with_stdlib(&self);450}451452impl StateExt for State {453 fn with_stdlib(&self) {454 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());455 self.settings_mut().context_initializer = tb!(initializer);456 }457}