1use std::{2 cell::{Ref, RefCell, RefMut},3 collections::HashMap,4 rc::Rc,5};67use jrsonnet_evaluator::{8 error::{Error::*, Result},9 function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10 gc::{GcHashMap, TraceBox},11 tb, throw_runtime,12 trace::PathResolver,13 typed::{Any, Either, Either2, Either4, VecVal, M1},14 val::{equals, ArrValue},15 Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;4243pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {44 let mut builder = ObjValueBuilder::new();4546 let expr = expr::stdlib_expr();47 let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)48 .expect("stdlib.jsonnet should have no errors")49 .as_obj()50 .expect("stdlib.jsonnet should evaluate to object");5152 builder.with_super(eval);5354 for (name, builtin) in [55 ("length", builtin_length::INST),56 57 ("type", builtin_type::INST),58 ("isString", builtin_is_string::INST),59 ("isNumber", builtin_is_number::INST),60 ("isBoolean", builtin_is_boolean::INST),61 ("isObject", builtin_is_object::INST),62 ("isArray", builtin_is_array::INST),63 ("isFunction", builtin_is_function::INST),64 65 ("makeArray", builtin_make_array::INST),66 ("slice", builtin_slice::INST),67 ("map", builtin_map::INST),68 ("flatMap", builtin_flatmap::INST),69 ("filter", builtin_filter::INST),70 ("foldl", builtin_foldl::INST),71 ("foldr", builtin_foldr::INST),72 ("range", builtin_range::INST),73 ("join", builtin_join::INST),74 ("reverse", builtin_reverse::INST),75 ("any", builtin_any::INST),76 ("all", builtin_all::INST),77 ("member", builtin_member::INST),78 ("count", builtin_count::INST),79 80 ("modulo", builtin_modulo::INST),81 ("floor", builtin_floor::INST),82 ("ceil", builtin_ceil::INST),83 ("log", builtin_log::INST),84 ("pow", builtin_pow::INST),85 ("sqrt", builtin_sqrt::INST),86 ("sin", builtin_sin::INST),87 ("cos", builtin_cos::INST),88 ("tan", builtin_tan::INST),89 ("asin", builtin_asin::INST),90 ("acos", builtin_acos::INST),91 ("atan", builtin_atan::INST),92 ("exp", builtin_exp::INST),93 ("mantissa", builtin_mantissa::INST),94 ("exponent", builtin_exponent::INST),95 96 ("mod", builtin_mod::INST),97 ("primitiveEquals", builtin_primitive_equals::INST),98 ("equals", builtin_equals::INST),99 ("format", builtin_format::INST),100 101 ("sort", builtin_sort::INST),102 103 ("md5", builtin_md5::INST),104 105 ("encodeUTF8", builtin_encode_utf8::INST),106 ("decodeUTF8", builtin_decode_utf8::INST),107 ("base64", builtin_base64::INST),108 ("base64Decode", builtin_base64_decode::INST),109 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),110 111 ("objectFieldsEx", builtin_object_fields_ex::INST),112 ("objectHasEx", builtin_object_has_ex::INST),113 114 ("escapeStringJson", builtin_escape_string_json::INST),115 ("manifestJsonEx", builtin_manifest_json_ex::INST),116 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),117 118 ("parseJson", builtin_parse_json::INST),119 ("parseYaml", builtin_parse_yaml::INST),120 121 ("codepoint", builtin_codepoint::INST),122 ("substr", builtin_substr::INST),123 ("char", builtin_char::INST),124 ("strReplace", builtin_str_replace::INST),125 ("splitLimit", builtin_splitlimit::INST),126 ("asciiUpper", builtin_ascii_upper::INST),127 ("asciiLower", builtin_ascii_lower::INST),128 ("findSubstr", builtin_find_substr::INST),129 ("startsWith", builtin_starts_with::INST),130 ("endsWith", builtin_ends_with::INST),131 ]132 .iter()133 .cloned()134 {135 builder136 .member(name.into())137 .hide()138 .value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))139 .expect("no conflict");140 }141142 builder143 .member("extVar".into())144 .hide()145 .value(146 s.clone(),147 Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {148 settings: settings.clone()149 })))),150 )151 .expect("no conflict");152 builder153 .member("native".into())154 .hide()155 .value(156 s.clone(),157 Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {158 settings: settings.clone()159 })))),160 )161 .expect("no conflict");162 builder163 .member("trace".into())164 .hide()165 .value(166 s.clone(),167 Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),168 )169 .expect("no conflict");170171 builder172 .member("id".into())173 .hide()174 .value(s, Val::Func(FuncVal::Id))175 .expect("no conflict");176177 builder.build()178}179180pub trait TracePrinter {181 fn print_trace(&self, s: State, loc: CallLocation, value: IStr);182}183184pub struct StdTracePrinter {185 resolver: PathResolver,186}187impl StdTracePrinter {188 pub fn new(resolver: PathResolver) -> Self {189 Self { resolver }190 }191}192impl TracePrinter for StdTracePrinter {193 fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {194 eprint!("TRACE:");195 if let Some(loc) = loc.0 {196 let locs = loc.0.map_source_locations(&[loc.1]);197 eprint!(198 " {}:{}",199 match loc.0.source_path().path() {200 Some(p) => self.resolver.resolve(p),201 None => loc.0.source_path().to_string(),202 },203 locs[0].line204 );205 }206 eprintln!(" {}", value);207 }208}209210pub struct Settings {211 212 pub ext_vars: HashMap<IStr, TlaArg>,213 214 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,215 216 pub globals: GcHashMap<IStr, Thunk<Val>>,217 218 pub trace_printer: Box<dyn TracePrinter>,219 220 pub path_resolver: PathResolver,221}222223pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {224 let source_name = format!("<extvar:{}>", name);225 Source::new_virtual(source_name.into(), code.into())226}227228pub struct ContextInitializer {229 230 #[cfg(not(feature = "legacy-this-file"))]231 context: Context,232 233 #[cfg(feature = "legacy-this-file")]234 stdlib_obj: ObjValue,235 settings: Rc<RefCell<Settings>>,236}237impl ContextInitializer {238 pub fn new(s: State, resolver: PathResolver) -> Self {239 let settings = Settings {240 ext_vars: Default::default(),241 ext_natives: Default::default(),242 globals: Default::default(),243 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),244 path_resolver: resolver,245 };246 let settings = Rc::new(RefCell::new(settings));247 Self {248 #[cfg(not(feature = "legacy-this-file"))]249 context: {250 let mut context = ContextBuilder::with_capacity(1);251 context.bind(252 "std".into(),253 Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),254 );255 context.build()256 },257 #[cfg(feature = "legacy-this-file")]258 stdlib_obj: stdlib_uncached(s, settings.clone()),259 settings,260 }261 }262 pub fn settings(&self) -> Ref<Settings> {263 self.settings.borrow()264 }265 pub fn settings_mut(&self) -> RefMut<Settings> {266 self.settings.borrow_mut()267 }268 pub fn add_ext_var(&self, name: IStr, value: Val) {269 self.settings_mut()270 .ext_vars271 .insert(name, TlaArg::Val(value));272 }273 pub fn add_ext_str(&self, name: IStr, value: IStr) {274 self.settings_mut()275 .ext_vars276 .insert(name, TlaArg::String(value));277 }278 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {279 let code = code.into();280 let source = extvar_source(name, code.clone());281 let parsed = jrsonnet_parser::parse(282 &code,283 &jrsonnet_parser::ParserSettings {284 file_name: source.clone(),285 },286 )287 .map_err(|e| ImportSyntaxError {288 path: source,289 error: Box::new(e),290 })?;291 292 self.settings_mut()293 .ext_vars294 .insert(name.into(), TlaArg::Code(parsed));295 Ok(())296 }297 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {298 self.settings_mut().ext_natives.insert(name, cb);299 }300}301impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {302 #[cfg(not(feature = "legacy-this-file"))]303 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {304 let out = self.context.clone();305 let globals = &self.settings().globals;306 if globals.is_empty() {307 return out;308 }309310 let mut out = ContextBuilder::extend(out);311 for (k, v) in globals.iter() {312 out.bind(k.clone(), v.clone());313 }314 out.build()315 }316 #[cfg(feature = "legacy-this-file")]317 fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {318 let mut builder = ObjValueBuilder::new();319 builder.with_super(self.stdlib_obj.clone());320 builder321 .member("thisFile".into())322 .hide()323 .value(324 s,325 Val::Str(match source.source_path().path() {326 Some(p) => self.settings().path_resolver.resolve(p).into(),327 None => source.source_path().to_string().into(),328 }),329 )330 .expect("this object builder is empty");331 let stdlib_with_this_file = builder.build();332333 let mut context = ContextBuilder::with_capacity(1);334 context.bind(335 "std".into(),336 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),337 );338 for (k, v) in self.settings().globals.iter() {339 context.bind(k.clone(), v.clone());340 }341 context.build()342 }343 fn as_any(&self) -> &dyn std::any::Any {344 self345 }346}347348#[builtin]349fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {350 use Either4::*;351 Ok(match x {352 A(x) => x.chars().count(),353 B(x) => x.len(),354 C(x) => x.len(),355 D(f) => f.params_len(),356 })357}358359#[builtin]360const fn builtin_codepoint(str: char) -> Result<u32> {361 Ok(str as u32)362}363364#[builtin]365fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {366 Ok(str.chars().skip(from).take(len).collect())367}368369#[builtin(fields(370 settings: Rc<RefCell<Settings>>,371))]372fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {373 let ctx = s.create_default_context(extvar_source(&x, ""));374 Ok(Any(this375 .settings376 .borrow()377 .ext_vars378 .get(&x)379 .cloned()380 .ok_or_else(|| UndefinedExternalVariable(x))?381 .evaluate_arg(s.clone(), ctx, true)?382 .evaluate(s)?))383}384385#[builtin(fields(386 settings: Rc<RefCell<Settings>>,387))]388fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {389 Ok(Any(this390 .settings391 .borrow()392 .ext_natives393 .get(&name)394 .cloned()395 .map_or(Val::Null, |v| {396 Val::Func(FuncVal::Builtin(v.clone()))397 })))398}399400#[builtin]401fn builtin_char(n: u32) -> Result<char> {402 Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)403}404405#[builtin(fields(406 settings: Rc<RefCell<Settings>>,407))]408fn builtin_trace(409 this: &builtin_trace,410 s: State,411 loc: CallLocation,412 str: IStr,413 rest: Thunk<Val>,414) -> Result<Any> {415 this.settings416 .borrow()417 .trace_printer418 .print_trace(s.clone(), loc, str);419 Ok(Any(rest.evaluate(s)?))420}421422#[builtin]423fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {424 Ok(str.replace(&from as &str, &to as &str))425}426427#[builtin]428fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {429 use Either2::*;430 Ok(VecVal(Cc::new(match maxsplits {431 A(n) => str432 .splitn(n + 1, &c as &str)433 .map(|s| Val::Str(s.into()))434 .collect(),435 B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),436 })))437}438439#[builtin]440fn builtin_ascii_upper(str: IStr) -> Result<String> {441 Ok(str.to_ascii_uppercase())442}443444#[builtin]445fn builtin_ascii_lower(str: IStr) -> Result<String> {446 Ok(str.to_ascii_lowercase())447}448449#[builtin]450fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {451 if pat.is_empty() || str.is_empty() || pat.len() > str.len() {452 return Ok(ArrValue::empty());453 }454455 let str = str.as_str();456 let pat = pat.as_bytes();457 let strb = str.as_bytes();458459 let max_pos = str.len() - pat.len();460461 let mut out: Vec<Val> = Vec::new();462 for (ch_idx, (i, _)) in str463 .char_indices()464 .take_while(|(i, _)| i <= &max_pos)465 .enumerate()466 {467 if &strb[i..i + pat.len()] == pat {468 out.push(Val::Num(ch_idx as f64))469 }470 }471 Ok(out.into())472}473474#[allow(clippy::comparison_chain)]475#[builtin]476fn builtin_starts_with(477 s: State,478 a: Either![IStr, ArrValue],479 b: Either![IStr, ArrValue],480) -> Result<bool> {481 Ok(match (a, b) {482 (Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),483 (Either2::B(a), Either2::B(b)) => {484 if b.len() > a.len() {485 return Ok(false);486 } else if b.len() == a.len() {487 return equals(s, &Val::Arr(a), &Val::Arr(b));488 } else {489 for (a, b) in a490 .slice(None, Some(b.len()), None)491 .iter(s.clone())492 .zip(b.iter(s.clone()))493 {494 let a = a?;495 let b = b?;496 if !equals(s.clone(), &a, &b)? {497 return Ok(false);498 }499 }500 true501 }502 }503 _ => throw_runtime!("both arguments should be of the same type"),504 })505}506507#[allow(clippy::comparison_chain)]508#[builtin]509fn builtin_ends_with(510 s: State,511 a: Either![IStr, ArrValue],512 b: Either![IStr, ArrValue],513) -> Result<bool> {514 Ok(match (a, b) {515 (Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),516 (Either2::B(a), Either2::B(b)) => {517 if b.len() > a.len() {518 return Ok(false);519 } else if b.len() == a.len() {520 return equals(s, &Val::Arr(a), &Val::Arr(b));521 } else {522 let a_len = a.len();523 for (a, b) in a524 .slice(Some(a_len - b.len()), None, None)525 .iter(s.clone())526 .zip(b.iter(s.clone()))527 {528 let a = a?;529 let b = b?;530 if !equals(s.clone(), &a, &b)? {531 return Ok(false);532 }533 }534 true535 }536 }537 _ => throw_runtime!("both arguments should be of the same type"),538 })539}540541pub trait StateExt {542 543 fn with_stdlib(&self);544 fn add_global(&self, name: IStr, value: Thunk<Val>);545}546547impl StateExt for State {548 fn with_stdlib(&self) {549 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());550 self.settings_mut().context_initializer = Box::new(initializer)551 }552 fn add_global(&self, name: IStr, value: Thunk<Val>) {553 self.settings()554 .context_initializer555 .as_any()556 .downcast_ref::<ContextInitializer>()557 .expect("not standard context initializer")558 .settings_mut()559 .globals560 .insert(name, value);561 }562}