git.delta.rocks / jrsonnet / refs/commits / 57f709a58e12

difftreelog

source

crates/jrsonnet-stdlib/src/arrays.rs9.5 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, 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<i32>,52	end: Option<i32>,53	step: Option<BoundedUsize<1, { i32::MAX as usize }>>,54) -> Result<Val> {55	indexable.slice(index, end, step).map(Val::from)56}5758#[builtin]59pub fn builtin_map(func: FuncVal, arr: IndexableVal) -> ArrValue {60	let arr = arr.to_array();61	arr.map(func)62}6364#[builtin]65pub fn builtin_map_with_index(func: FuncVal, arr: IndexableVal) -> ArrValue {66	let arr = arr.to_array();67	arr.map_with_index(func)68}6970#[builtin]71pub fn builtin_flatmap(72	func: NativeFn<((Either![String, Val],), Val)>,73	arr: IndexableVal,74) -> Result<IndexableVal> {75	use std::fmt::Write;76	match arr {77		IndexableVal::Str(str) => {78			let mut out = String::new();79			for c in str.chars() {80				match func(Either2::A(c.to_string()))? {81					Val::Str(o) => write!(out, "{o}").unwrap(),82					Val::Null => continue,83					_ => bail!("in std.join all items should be strings"),84				};85			}86			Ok(IndexableVal::Str(out.into()))87		}88		IndexableVal::Arr(a) => {89			let mut out = Vec::new();90			for el in a.iter() {91				let el = el?;92				match func(Either2::B(el))? {93					Val::Arr(o) => {94						for oe in o.iter() {95							out.push(oe?);96						}97					}98					Val::Null => continue,99					_ => bail!("in std.join all items should be arrays"),100				};101			}102			Ok(IndexableVal::Arr(out.into()))103		}104	}105}106107#[builtin]108pub fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {109	arr.filter(|val| bool::from_untyped(func.evaluate_simple(&(val.clone(),), false)?))110}111112#[builtin]113pub fn builtin_filter_map(114	filter_func: FuncVal,115	map_func: FuncVal,116	arr: ArrValue,117) -> Result<ArrValue> {118	Ok(builtin_filter(filter_func, arr)?.map(map_func))119}120121#[builtin]122pub fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {123	let mut acc = init;124	for i in arr.iter() {125		acc = func.evaluate_simple(&(acc, i?), false)?;126	}127	Ok(acc)128}129130#[builtin]131pub fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Val) -> Result<Val> {132	let mut acc = init;133	for i in arr.iter().rev() {134		acc = func.evaluate_simple(&(i?, acc), false)?;135	}136	Ok(acc)137}138139#[builtin]140pub fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {141	if to < from {142		return Ok(ArrValue::empty());143	}144	Ok(ArrValue::range_inclusive(from, to))145}146147#[builtin]148pub fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {149	use std::fmt::Write;150	Ok(match sep {151		IndexableVal::Arr(joiner_items) => {152			let mut out = Vec::new();153154			let mut first = true;155			for item in arr.iter() {156				let item = item?.clone();157				if let Val::Arr(items) = item {158					if !first {159						out.reserve(joiner_items.len());160						// TODO: extend161						for item in joiner_items.iter() {162							out.push(item?);163						}164					}165					first = false;166					out.reserve(items.len());167					for item in items.iter() {168						out.push(item?);169					}170				} else if matches!(item, Val::Null) {171					continue;172				} else {173					bail!("in std.join all items should be arrays");174				}175			}176177			IndexableVal::Arr(out.into())178		}179		IndexableVal::Str(sep) => {180			let mut out = String::new();181182			let mut first = true;183			for item in arr.iter() {184				let item = item?.clone();185				if let Val::Str(item) = item {186					if !first {187						out += &sep;188					}189					first = false;190					write!(out, "{item}").unwrap();191				} else if matches!(item, Val::Null) {192					continue;193				} else {194					bail!("in std.join all items should be strings");195				}196			}197198			IndexableVal::Str(out.into())199		}200	})201}202203#[builtin]204pub fn builtin_lines(arr: ArrValue) -> Result<IndexableVal> {205	builtin_join(206		IndexableVal::Str("\n".into()),207		ArrValue::extended(arr, ArrValue::eager(vec![Val::string("")])),208	)209}210211#[builtin]212pub fn builtin_resolve_path(f: String, r: String) -> String {213	let Some(pos) = f.rfind('/') else {214		return r;215	};216	format!("{}{}", &f[..=pos], r)217}218219pub fn deep_join_inner(out: &mut String, arr: IndexableVal) -> Result<()> {220	use std::fmt::Write;221	match arr {222		IndexableVal::Str(s) => write!(out, "{s}").expect("no error"),223		IndexableVal::Arr(arr) => {224			for ele in arr.iter() {225				let indexable = IndexableVal::from_untyped(ele?)?;226				deep_join_inner(out, indexable)?;227			}228		}229	}230	Ok(())231}232233#[builtin]234pub fn builtin_deep_join(arr: IndexableVal) -> Result<String> {235	let mut out = String::new();236	deep_join_inner(&mut out, arr)?;237	Ok(out)238}239240#[builtin]241pub fn builtin_reverse(arr: ArrValue) -> ArrValue {242	arr.reversed()243}244245#[builtin]246pub fn builtin_any(arr: ArrValue) -> Result<bool> {247	for v in arr.iter() {248		let v = bool::from_untyped(v?)?;249		if v {250			return Ok(true);251		}252	}253	Ok(false)254}255256#[builtin]257pub fn builtin_all(arr: ArrValue) -> Result<bool> {258	for v in arr.iter() {259		let v = bool::from_untyped(v?)?;260		if !v {261			return Ok(false);262		}263	}264	Ok(true)265}266267#[builtin]268pub fn builtin_member(arr: IndexableVal, x: Val) -> Result<bool> {269	match arr {270		IndexableVal::Str(str) => {271			let x: IStr = IStr::from_untyped(x)?;272			Ok(!x.is_empty() && str.contains(&*x))273		}274		IndexableVal::Arr(a) => {275			for item in a.iter() {276				let item = item?;277				if equals(&item, &x)? {278					return Ok(true);279				}280			}281			Ok(false)282		}283	}284}285286#[builtin]287pub fn builtin_find(value: Val, arr: ArrValue) -> Result<Vec<usize>> {288	let mut out = Vec::new();289	for (i, ele) in arr.iter().enumerate() {290		let ele = ele?;291		if equals(&ele, &value)? {292			out.push(i);293		}294	}295	Ok(out)296}297298#[builtin]299pub fn builtin_contains(arr: IndexableVal, elem: Val) -> Result<bool> {300	builtin_member(arr, elem)301}302303#[builtin]304pub fn builtin_count(arr: ArrValue, x: Val) -> Result<usize> {305	let mut count = 0;306	for item in arr.iter() {307		if equals(&item?, &x)? {308			count += 1;309		}310	}311	Ok(count)312}313314#[builtin]315pub fn builtin_avg(arr: Vec<f64>, onEmpty: Option<Thunk<Val>>) -> Result<Val> {316	if arr.is_empty() {317		return eval_on_empty(onEmpty);318	}319	Ok(Val::try_num(arr.iter().sum::<f64>() / (arr.len() as f64))?)320}321322#[builtin]323pub fn builtin_remove_at(arr: ArrValue, at: i32) -> Result<ArrValue> {324	let newArrLeft = arr.clone().slice(None, Some(at), None);325	let newArrRight = arr.slice(Some(at + 1), None, None);326327	Ok(ArrValue::extended(newArrLeft, newArrRight))328}329330#[builtin]331pub fn builtin_remove(arr: ArrValue, elem: Val) -> Result<ArrValue> {332	for (index, item) in arr.iter().enumerate() {333		if equals(&item?, &elem)? {334			return builtin_remove_at(arr.clone(), index as i32);335		}336	}337	Ok(arr)338}339340#[builtin]341pub fn builtin_flatten_arrays(arrs: Vec<ArrValue>) -> ArrValue {342	pub fn flatten_inner(values: &[ArrValue]) -> ArrValue {343		if values.len() == 1 {344			return values[0].clone();345		} else if values.len() == 2 {346			return ArrValue::extended(values[0].clone(), values[1].clone());347		}348		let (a, b) = values.split_at(values.len() / 2);349		ArrValue::extended(flatten_inner(a), flatten_inner(b))350	}351	if arrs.is_empty() {352		return ArrValue::empty();353	} else if arrs.len() == 1 {354		return arrs.into_iter().next().expect("single");355	}356	flatten_inner(&arrs)357}358359#[builtin]360pub fn builtin_flatten_deep_array(value: Val) -> Result<Vec<Val>> {361	fn process(value: Val, out: &mut Vec<Val>) -> Result<()> {362		match value {363			Val::Arr(arr) => {364				for ele in arr.iter() {365					process(ele?, out)?;366				}367			}368			_ => out.push(value),369		}370		Ok(())371	}372	let mut out = Vec::new();373	process(value, &mut out)?;374	Ok(out)375}376377#[builtin]378pub fn builtin_prune(379	a: Val,380381	#[default(false)]382	#[cfg(feature = "exp-preserve-order")]383	preserve_order: bool,384) -> Result<Val> {385	fn is_content(val: &Val) -> bool {386		match val {387			Val::Null => false,388			Val::Arr(a) => !a.is_empty(),389			Val::Obj(o) => !o.is_empty(),390			_ => true,391		}392	}393	Ok(match a {394		Val::Arr(a) => {395			let mut out = Vec::new();396			for (i, ele) in a.iter().enumerate() {397				let ele = ele398					.and_then(|v| {399						builtin_prune(400							v,401							#[cfg(feature = "exp-preserve-order")]402							preserve_order,403						)404					})405					.with_description(|| format!("elem <{i}> pruning"))?;406				if is_content(&ele) {407					out.push(ele);408				}409			}410			Val::Arr(ArrValue::eager(out))411		}412		Val::Obj(o) => {413			let mut out = ObjValueBuilder::new();414			for (name, value) in o.iter(415				#[cfg(feature = "exp-preserve-order")]416				preserve_order,417			) {418				let value = value419					.and_then(|v| {420						builtin_prune(421							v,422							#[cfg(feature = "exp-preserve-order")]423							preserve_order,424						)425					})426					.with_description(|| format!("field <{name}> pruning"))?;427				if !is_content(&value) {428					continue;429				}430				out.field(name).value(value);431			}432			Val::Obj(out.build())433		}434		_ => a,435	})436}