git.delta.rocks / jrsonnet / refs/commits / eea91c38b18b

difftreelog

source

crates/jrsonnet-stdlib/src/arrays.rs10.4 KiBsourcehistory
1#![allow(non_snake_case)]23use jrsonnet_evaluator::{4	bail,5	function::{builtin, FuncVal},6	runtime_error,7	typed::{BoundedI32, BoundedUsize, Either2, NativeFn, Typed},8	val::{equals, ArrValue, IndexableVal},9	Either, IStr, ObjValue, ObjValueBuilder, Result, ResultExt, Thunk, Val,10};1112pub fn eval_on_empty(on_empty: Option<Thunk<Val>>) -> Result<Val> {13	if let Some(on_empty) = on_empty {14		on_empty.evaluate()15	} else {16		bail!("expected non-empty array")17	}18}1920#[builtin]21pub fn builtin_make_array(sz: BoundedI32<0, { i32::MAX }>, func: FuncVal) -> Result<ArrValue> {22	if *sz == 0 {23		return Ok(ArrValue::empty());24	}25	func.evaluate_trivial().map_or_else(26		|| Ok(ArrValue::range_exclusive(0, *sz).map(func)),27		|trivial| {28			let mut out = Vec::with_capacity(*sz as usize);29			for _ in 0..*sz {30				out.push(trivial.clone());31			}32			Ok(ArrValue::eager(out))33		},34	)35}3637#[builtin]38pub fn builtin_repeat(what: Either![IStr, ArrValue], count: usize) -> Result<Val> {39	Ok(match what {40		Either2::A(s) => Val::string(s.repeat(count)),41		Either2::B(arr) => Val::Arr(42			ArrValue::repeated(arr, count)43				.ok_or_else(|| runtime_error!("repeated length overflow"))?,44		),45	})46}4748#[builtin]49pub fn builtin_slice(50	indexable: IndexableVal,51	index: Option<Option<i32>>,52	end: Option<Option<i32>>,53	step: Option<Option<BoundedUsize<1, { i32::MAX as usize }>>>,54) -> Result<Val> {55	indexable56		.slice(index.flatten(), end.flatten(), step.flatten())57		.map(Val::from)58}5960#[builtin]61pub fn builtin_map(func: FuncVal, arr: IndexableVal) -> ArrValue {62	let arr = arr.to_array();63	arr.map(func)64}6566#[builtin]67pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {68	let arr = arr.to_array();69	arr.map_with_index(func)70}7172#[builtin]73pub fn builtin_map_with_key(func: FuncVal, obj: ObjValue) -> Result<ObjValue> {74	let mut out = ObjValueBuilder::new();75	for (k, v) in obj.iter(76		// Makes sense mapped object should be ordered the same way, should not break anything when the output is not ordered (the default).77		// The thrown error might be different, but jsonnet78		// does not specify the evaluation order.79		#[cfg(feature = "exp-preserve-order")]80		true,81	) {82		let v = v?;83		out.field(k.clone())84			.value(func.evaluate_simple(&(k, v), false)?);85	}86	Ok(out.build())87}8889#[builtin]90pub fn builtin_flatmap(91	func: NativeFn<((Either![String, Val],), Val)>,92	arr: IndexableVal,93) -> Result<IndexableVal> {94	use std::fmt::Write;95	match arr {96		IndexableVal::Str(str) => {97			let mut out = String::new();98			for c in str.chars() {99				match func(Either2::A(c.to_string()))? {100					Val::Str(o) => write!(out, "{o}").unwrap(),101					Val::Null => continue,102					_ => bail!("in std.join all items should be strings"),103				};104			}105			Ok(IndexableVal::Str(out.into()))106		}107		IndexableVal::Arr(a) => {108			let mut out = Vec::new();109			for el in a.iter() {110				let el = el?;111				match func(Either2::B(el))? {112					Val::Arr(o) => {113						for oe in o.iter() {114							out.push(oe?);115						}116					}117					Val::Null => continue,118					_ => bail!("in std.join all items should be arrays"),119				};120			}121			Ok(IndexableVal::Arr(out.into()))122		}123	}124}125126#[builtin]127pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {128	arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))129}130131#[builtin]132pub fn builtin_filter_map(133	filter_func: FuncVal,134	map_func: FuncVal,135	arr: ArrValue,136) -> Result<ArrValue> {137	Ok(builtin_filter(filter_func, arr)?.map(map_func))138}139140#[builtin]141pub fn builtin_foldl(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {142	let mut acc = init;143	match arr {144		Either2::A(arr) => {145			for i in arr.iter() {146				acc = func.evaluate_simple(&(acc, i?), false)?;147			}148		}149		Either2::B(arr) => {150			for i in arr.chars() {151				acc = func.evaluate_simple(&(acc, Val::string(i)), false)?;152			}153		}154	}155	Ok(acc)156}157158#[builtin]159pub fn builtin_foldr(func: FuncVal, arr: Either![ArrValue, IStr], init: Val) -> Result<Val> {160	let mut acc = init;161	match arr {162		Either2::A(arr) => {163			for i in arr.iter().rev() {164				acc = func.evaluate_simple(&(i?, acc), false)?;165			}166		}167		Either2::B(arr) => {168			for i in arr.chars().rev() {169				acc = func.evaluate_simple(&(Val::string(i), acc), false)?;170			}171		}172	}173	Ok(acc)174}175176#[builtin]177pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {178	if to < from {179		return Ok(ArrValue::empty());180	}181	Ok(ArrValue::range_inclusive(from, to))182}183184#[builtin]185pub fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {186	use std::fmt::Write;187	Ok(match sep {188		IndexableVal::Arr(joiner_items) => {189			let mut out = Vec::new();190191			let mut first = true;192			for item in arr.iter() {193				let item = item?.clone();194				if let Val::Arr(items) = item {195					if !first {196						out.reserve(joiner_items.len());197						// TODO: extend198						for item in joiner_items.iter() {199							out.push(item?);200						}201					}202					first = false;203					out.reserve(items.len());204					for item in items.iter() {205						out.push(item?);206					}207				} else if matches!(item, Val::Null) {208					continue;209				} else {210					bail!("in std.join all items should be arrays");211				}212			}213214			IndexableVal::Arr(out.into())215		}216		IndexableVal::Str(sep) => {217			let mut out = String::new();218219			let mut first = true;220			for item in arr.iter() {221				let item = item?.clone();222				if let Val::Str(item) = item {223					if !first {224						out += &sep;225					}226					first = false;227					write!(out, "{item}").unwrap();228				} else if matches!(item, Val::Null) {229					continue;230				} else {231					bail!("in std.join all items should be strings");232				}233			}234235			IndexableVal::Str(out.into())236		}237	})238}239240#[builtin]241pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {242	builtin_join(243		IndexableVal::Str("\n".into()),244		ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),245	)246}247248#[builtin]249pub fn builtin_resolve_path(f: String, r: String) -> String {250	let Some(pos) = f.rfind('/') else {251		return r;252	};253	format!("{}{}", &f[..=pos], r)254}255256pub fn deep_join_inner(out: &mut String, arr: IndexableVal) -> Result<()> {257	use std::fmt::Write;258	match arr {259		IndexableVal::Str(s) => write!(out, "{s}").expect("no error"),260		IndexableVal::Arr(arr) => {261			for ele in arr.iter() {262				let indexable = IndexableVal::from_untyped(ele?)?;263				deep_join_inner(out, indexable)?;264			}265		}266	}267	Ok(())268}269270#[builtin]271pub fn builtin_deep_join(arr: IndexableVal) -> Result<String> {272	let mut out = String::new();273	deep_join_inner(&mut out, arr)?;274	Ok(out)275}276277#[builtin]278pub fn builtin_reverse(arr: ArrValue) -> ArrValue {279	arr.reversed()280}281282#[builtin]283pub fn builtin_any(arr: ArrValue) -> Result<bool> {284	for v in arr.iter() {285		let v = bool::from_untyped(v?)?;286		if v {287			return Ok(true);288		}289	}290	Ok(false)291}292293#[builtin]294pub fn builtin_all(arr: ArrValue) -> Result<bool> {295	for v in arr.iter() {296		let v = bool::from_untyped(v?)?;297		if !v {298			return Ok(false);299		}300	}301	Ok(true)302}303304#[builtin]305pub fn builtin_member(arr: IndexableVal, x: Val) -> Result<bool> {306	match arr {307		IndexableVal::Str(str) => {308			let x: IStr = IStr::from_untyped(x)?;309			Ok(!x.is_empty() && str.contains(&*x))310		}311		IndexableVal::Arr(a) => {312			for item in a.iter() {313				let item = item?;314				if equals(&item, &x)? {315					return Ok(true);316				}317			}318			Ok(false)319		}320	}321}322323#[builtin]324pub fn builtin_find(value: Val, arr: ArrValue) -> Result<Vec<usize>> {325	let mut out = Vec::new();326	for (i, ele) in arr.iter().enumerate() {327		let ele = ele?;328		if equals(&ele, &value)? {329			out.push(i);330		}331	}332	Ok(out)333}334335#[builtin]336pub fn builtin_contains(arr: IndexableVal, elem: Val) -> Result<bool> {337	builtin_member(arr, elem)338}339340#[builtin]341pub fn builtin_count(arr: ArrValue, x: Val) -> Result<usize> {342	let mut count = 0;343	for item in arr.iter() {344		if equals(&item?, &x)? {345			count += 1;346		}347	}348	Ok(count)349}350351#[builtin]352pub fn builtin_avg(arr: Vec<f64>, onEmpty: Option<Thunk<Val>>) -> Result<Val> {353	if arr.is_empty() {354		return eval_on_empty(onEmpty);355	}356	Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)357}358359#[builtin]360pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {361	let newArrLeft = arr.clone().slice(None, Some(at), None);362	let newArrRight = arr.slice(Some(at + 1), None, None);363364	Ok(ArrValue::extended(newArrLeft, newArrRight))365}366367#[builtin]368pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {369	for (index, item) in arr.iter().enumerate() {370		if equals(&item?, &elem)? {371			return builtin_remove_at(arr.clone(), index as i32);372		}373	}374	Ok(arr)375}376377#[builtin]378pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {379	pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {380		if values.len() == 1 {381			return values[0].clone();382		} else if values.len() == 2 {383			return ArrValue::extended(values[0].clone(), values[1].clone());384		}385		let (a, b) = values.split_at(values.len() / 2);386		ArrValue::extended(flatten_inner(a), flatten_inner(b))387	}388	if arrs.is_empty() {389		return ArrValue::empty();390	} else if arrs.len() == 1 {391		return arrs.into_iter().next().expect("single");392	}393	flatten_inner(&arrs)394}395396#[builtin]397pub fn builtin_flatten_deep_array(value: Val) -> Result<Vec<Val>> {398	fn process(value: Val, out: &mut Vec<Val>) -> Result<()> {399		match value {400			Val::Arr(arr) => {401				for ele in arr.iter() {402					process(ele?, out)?;403				}404			}405			_ => out.push(value),406		}407		Ok(())408	}409	let mut out = Vec::new();410	process(value, &mut out)?;411	Ok(out)412}413414#[builtin]415pub fn builtin_prune(416	a: Val,417418	#[default(false)]419	#[cfg(feature = "exp-preserve-order")]420	preserve_order: bool,421) -> Result<Val> {422	fn is_content(val: &Val) -> bool {423		match val {424			Val::Null => false,425			Val::Arr(a) => !a.is_empty(),426			Val::Obj(o) => !o.is_empty(),427			_ => true,428		}429	}430	Ok(match a {431		Val::Arr(a) => {432			let mut out = Vec::new();433			for (i, ele) in a.iter().enumerate() {434				let ele = ele435					.and_then(|v| {436						builtin_prune(437							v,438							#[cfg(feature = "exp-preserve-order")]439							preserve_order,440						)441					})442					.with_description(|| format!("elem <{i}> pruning"))?;443				if is_content(&ele) {444					out.push(ele);445				}446			}447			Val::Arr(ArrValue::eager(out))448		}449		Val::Obj(o) => {450			let mut out = ObjValueBuilder::new();451			for (name, value) in o.iter(452				#[cfg(feature = "exp-preserve-order")]453				preserve_order,454			) {455				let value = value456					.and_then(|v| {457						builtin_prune(458							v,459							#[cfg(feature = "exp-preserve-order")]460							preserve_order,461						)462					})463					.with_description(|| format!("field <{name}> pruning"))?;464				if !is_content(&value) {465					continue;466				}467				out.field(name).value(value);468			}469			Val::Obj(out.build())470		}471		_ => a,472	})473}