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

difftreelog

perf move std.object[Keys]Values[All] to native

Yaroslav Bolyukin2023-08-10parent: #be6e85a.patch.diff
in: master

6 files changed

modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -9,8 +9,9 @@
 	error::ErrorKind::InfiniteRecursionDetected,
 	evaluate,
 	function::FuncVal,
+	typed::Typed,
 	val::{StrValue, ThunkValue},
-	Context, Error, Result, Thunk, Val,
+	Context, Error, ObjValue, Result, Thunk, Val,
 };
 
 pub trait ArrayLike: Any + Trace + Debug {
@@ -576,3 +577,103 @@
 		self.data.is_cheap()
 	}
 }
+
+#[derive(Trace, Debug)]
+pub struct PickObjectValues {
+	obj: ObjValue,
+	keys: Vec<IStr>,
+}
+
+impl PickObjectValues {
+	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {
+		Self { obj, keys }
+	}
+}
+
+impl ArrayLike for PickObjectValues {
+	fn len(&self) -> usize {
+		self.keys.len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		let Some(key) = self.keys.get(index) else {
+			return Ok(None);
+		};
+		Ok(Some(self.obj.get_or_bail(key.clone())?))
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		let Some(key) = self.keys.get(index) else {
+			return None;
+		};
+		Some(self.obj.get_lazy_or_bail(key.clone()))
+	}
+
+	fn get_cheap(&self, _index: usize) -> Option<Val> {
+		None
+	}
+
+	fn is_cheap(&self) -> bool {
+		false
+	}
+}
+
+#[derive(Trace, Debug)]
+pub struct PickObjectKeyValues {
+	obj: ObjValue,
+	keys: Vec<IStr>,
+}
+
+impl PickObjectKeyValues {
+	pub fn new(obj: ObjValue, keys: Vec<IStr>) -> Self {
+		Self { obj, keys }
+	}
+}
+
+#[derive(Typed)]
+pub struct KeyValue {
+	key: IStr,
+	value: Thunk<Val>,
+}
+
+impl ArrayLike for PickObjectKeyValues {
+	fn len(&self) -> usize {
+		self.keys.len()
+	}
+
+	fn get(&self, index: usize) -> Result<Option<Val>> {
+		let Some(key) = self.keys.get(index) else {
+			return Ok(None);
+		};
+		Ok(Some(
+			KeyValue::into_untyped(KeyValue {
+				key: key.clone(),
+				value: Thunk::evaluated(self.obj.get_or_bail(key.clone())?),
+			})
+			.expect("convertible"),
+		))
+	}
+
+	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
+		let Some(key) = self.keys.get(index) else {
+			return None;
+		};
+		// Nothing can fail in the key part, yet value is still
+		// lazy-evaluated
+		Some(Thunk::evaluated(
+			KeyValue::into_untyped(KeyValue {
+				key: key.clone(),
+				value: self.obj.get_lazy_or_bail(key.clone()),
+			})
+			.expect("convertible"),
+		))
+	}
+
+	fn get_cheap(&self, _index: usize) -> Option<Val> {
+		None
+	}
+
+	fn is_cheap(&self) -> bool {
+		false
+	}
+}
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -12,12 +12,13 @@
 use rustc_hash::FxHashMap;
 
 use crate::{
-	error::{Error, ErrorKind::*},
+	arr::{PickObjectKeyValues, PickObjectValues},
+	error::{suggest_object_fields, Error, ErrorKind::*},
 	function::CallLocation,
 	gc::{GcHashMap, GcHashSet, TraceBox},
 	operator::evaluate_add_op,
 	tb, throw,
-	val::ThunkValue,
+	val::{ArrValue, ThunkValue},
 	MaybeUnbound, Result, State, Thunk, Unbound, Val,
 };
 
@@ -398,6 +399,14 @@
 		self.0.get_for(key, this)
 	}
 
+	pub fn get_or_bail(&self, key: IStr) -> Result<Val> {
+		let Some(value) = self.get(key.clone())? else {
+			let suggestions = suggest_object_fields(self, key.clone());
+			throw!(NoSuchField(key, suggestions))
+		};
+		Ok(value)
+	}
+
 	fn get_raw(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
 		self.0.get_for_uncached(key, this)
 	}
@@ -452,6 +461,25 @@
 			key,
 		}))
 	}
+	pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {
+		#[derive(Trace)]
+		struct ThunkGet {
+			obj: ObjValue,
+			key: IStr,
+		}
+		impl ThunkValue for ThunkGet {
+			type Output = Val;
+
+			fn get(self: Box<Self>) -> Result<Self::Output> {
+				Ok(self.obj.get_or_bail(self.key)?)
+			}
+		}
+
+		Thunk::new(ThunkGet {
+			obj: self.clone(),
+			key,
+		})
+	}
 	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
 		Cc::ptr_eq(&a.0, &b.0)
 	}
@@ -529,6 +557,51 @@
 			preserve_order,
 		)
 	}
+	pub fn values_ex(
+		&self,
+		include_hidden: bool,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> ArrValue {
+		ArrValue::new(PickObjectValues::new(
+			self.clone(),
+			self.fields_ex(
+				include_hidden,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			),
+		))
+	}
+	pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {
+		self.values_ex(
+			false,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		)
+	}
+	pub fn key_values_ex(
+		&self,
+		include_hidden: bool,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> ArrValue {
+		ArrValue::new(PickObjectKeyValues::new(
+			self.clone(),
+			self.fields_ex(
+				include_hidden,
+				#[cfg(feature = "exp-preserve-order")]
+				preserve_order,
+			),
+		))
+	}
+	pub fn key_values(
+		&self,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> ArrValue {
+		self.key_values_ex(
+			false,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		)
+	}
 }
 
 impl OopObject {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,7 +1,6 @@
 use std::{
 	cell::RefCell,
 	fmt::{self, Debug, Display},
-	hash::Hasher,
 	mem::replace,
 	rc::Rc,
 };
@@ -9,7 +8,6 @@
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
 use jrsonnet_types::ValType;
-use rustc_hash::FxHasher;
 
 pub use crate::arr::{ArrValue, ArrayLike};
 use crate::{
@@ -50,6 +48,12 @@
 	pub fn errored(e: Error) -> Self {
 		Self(Cc::new(RefCell::new(ThunkInner::Errored(e))))
 	}
+	pub fn result(res: Result<T, Error>) -> Self {
+		match res {
+			Ok(o) => Self::evaluated(o),
+			Err(e) => Self::errored(e),
+		}
+	}
 }
 
 impl<T> Thunk<T>
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -138,6 +138,10 @@
 		("base64DecodeBytes", builtin_base64_decode_bytes::INST),
 		// Objects
 		("objectFieldsEx", builtin_object_fields_ex::INST),
+		("objectValues", builtin_object_values::INST),
+		("objectValuesAll", builtin_object_values_all::INST),
+		("objectKeysValues", builtin_object_keys_values::INST),
+		("objectKeysValuesAll", builtin_object_keys_values_all::INST),
 		("objectHasEx", builtin_object_has_ex::INST),
 		("objectRemoveKey", builtin_object_remove_key::INST),
 		// Manifest
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,6 +1,6 @@
 use jrsonnet_evaluator::{
 	function::builtin,
-	val::{StrValue, Val},
+	val::{ArrValue, StrValue, Val},
 	IStr, ObjValue, ObjValueBuilder,
 };
 
@@ -23,6 +23,82 @@
 		.collect::<Vec<_>>()
 }
 
+pub fn builtin_object_values_ex(
+	o: ObjValue,
+	include_hidden: bool,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	#[cfg(feature = "exp-preserve-order")]
+	let preserve_order = preserve_order.unwrap_or(false);
+	o.values_ex(
+		include_hidden,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+#[builtin]
+pub fn builtin_object_values(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	builtin_object_values_ex(
+		o,
+		false,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+#[builtin]
+pub fn builtin_object_values_all(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	builtin_object_values_ex(
+		o,
+		true,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+
+pub fn builtin_object_keys_values_ex(
+	o: ObjValue,
+	include_hidden: bool,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	#[cfg(feature = "exp-preserve-order")]
+	let preserve_order = preserve_order.unwrap_or(false);
+	o.key_values_ex(
+		include_hidden,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+#[builtin]
+pub fn builtin_object_keys_values(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	builtin_object_keys_values_ex(
+		o,
+		false,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+#[builtin]
+pub fn builtin_object_keys_values_all(
+	o: ObjValue,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> ArrValue {
+	builtin_object_keys_values_ex(
+		o,
+		true,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order,
+	)
+}
+
 #[builtin]
 pub fn builtin_object_has_ex(obj: ObjValue, fname: IStr, hidden: bool) -> bool {
 	obj.has_field_ex(fname, hidden)
modifiedcrates/jrsonnet-stdlib/src/std.jsonnetdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/std.jsonnet
1{2  local std = self,3  local id = std.id,45  thisFile:: error 'std.thisFile is deprecated, to enable its support in jrsonnet - recompile it with "legacy-this-file" support.\nThis will slow down stdlib caching a bit, though',67  toString(a):: '' + a,89  lstripChars(str, chars)::10    if std.length(str) > 0 && std.member(chars, str[0]) then11      std.lstripChars(str[1:], chars)12    else13      str,1415  rstripChars(str, chars)::16    local len = std.length(str);17    if len > 0 && std.member(chars, str[len - 1]) then18      std.rstripChars(str[:len - 1], chars)19    else20      str,2122  stripChars(str, chars)::23    std.lstripChars(std.rstripChars(str, chars), chars),2425  stringChars(str)::26    std.makeArray(std.length(str), function(i) str[i]),2728  splitLimitR(str, c, maxsplits)::29    if maxsplits == -1 then30      std.splitLimit(str, c, -1)31    else32      local revStr(str) = std.join('', std.reverse(std.stringChars(str)));33      std.map(function(e) revStr(e), std.reverse(std.splitLimit(revStr(str), revStr(c), maxsplits))),3435  split(str, c):: std.splitLimit(str, c, -1),3637  mapWithIndex(func, arr)::38    if !std.isFunction(func) then39      error ('std.mapWithIndex first param must be function, got ' + std.type(func))40    else if !std.isArray(arr) && !std.isString(arr) then41      error ('std.mapWithIndex second param must be array, got ' + std.type(arr))42    else43      std.makeArray(std.length(arr), function(i) func(i, arr[i])),4445  mapWithKey(func, obj)::46    if !std.isFunction(func) then47      error ('std.mapWithKey first param must be function, got ' + std.type(func))48    else if !std.isObject(obj) then49      error ('std.mapWithKey second param must be object, got ' + std.type(obj))50    else51      { [k]: func(k, obj[k]) for k in std.objectFields(obj) },5253  lines(arr)::54    std.join('\n', arr + ['']),5556  deepJoin(arr)::57    if std.isString(arr) then58      arr59    else if std.isArray(arr) then60      std.join('', [std.deepJoin(x) for x in arr])61    else62      error 'Expected string or array, got %s' % std.type(arr),6364  filterMap(filter_func, map_func, arr)::65    if !std.isFunction(filter_func) then66      error ('std.filterMap first param must be function, got ' + std.type(filter_func))67    else if !std.isFunction(map_func) then68      error ('std.filterMap second param must be function, got ' + std.type(map_func))69    else if !std.isArray(arr) then70      error ('std.filterMap third param must be array, got ' + std.type(arr))71    else72      std.map(map_func, std.filter(filter_func, arr)),7374  assertEqual(a, b)::75    if a == b then76      true77    else78      error 'Assertion failed. ' + a + ' != ' + b,7980  clamp(x, minVal, maxVal)::81    if x < minVal then minVal82    else if x > maxVal then maxVal83    else x,8485  flattenArrays(arrs)::86    std.foldl(function(a, b) a + b, arrs, []),8788  manifestIni(ini)::89    local body_lines(body) =90      std.join([], [91        local value_or_values = body[k];92        if std.isArray(value_or_values) then93          ['%s = %s' % [k, value] for value in value_or_values]94        else95          ['%s = %s' % [k, value_or_values]]9697        for k in std.objectFields(body)98      ]);99100    local section_lines(sname, sbody) = ['[%s]' % [sname]] + body_lines(sbody),101          main_body = if std.objectHas(ini, 'main') then body_lines(ini.main) else [],102          all_sections = [103      section_lines(k, ini.sections[k])104      for k in std.objectFields(ini.sections)105    ];106    std.join('\n', main_body + std.flattenArrays(all_sections) + ['']),107108  manifestToml(value):: std.manifestTomlEx(value, '  '),109110  escapeStringPython(str)::111    std.escapeStringJson(str),112113  escapeStringBash(str_)::114    local str = std.toString(str_);115    local trans(ch) =116      if ch == "'" then117        "'\"'\"'"118      else119        ch;120    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),121122  escapeStringDollars(str_)::123    local str = std.toString(str_);124    local trans(ch) =125      if ch == '$' then126        '$$'127      else128        ch;129    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),130131  local xml_escapes = {132    '<': '&lt;',133    '>': '&gt;',134    '&': '&amp;',135    '"': '&quot;',136    "'": '&apos;',137  },138139  escapeStringXML(str_)::140    local str = std.toString(str_);141    std.join('', [std.get(xml_escapes, ch, ch) for ch in std.stringChars(str)]),142143  manifestJson(value):: std.manifestJsonEx(value, '    ') tailstrict,144145  manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),146147  manifestYamlStream(value, indent_array_in_object=false, c_document_end=true, quote_keys=true)::148    if !std.isArray(value) then149      error 'manifestYamlStream only takes arrays, got ' + std.type(value)150    else151      '---\n' + std.join(152        '\n---\n', [std.manifestYamlDoc(e, indent_array_in_object, quote_keys) for e in value]153      ) + if c_document_end then '\n...\n' else '\n',154155  manifestPython(v)::156    if std.isObject(v) then157      local fields = [158        '%s: %s' % [std.escapeStringPython(k), std.manifestPython(v[k])]159        for k in std.objectFields(v)160      ];161      '{%s}' % [std.join(', ', fields)]162    else if std.isArray(v) then163      '[%s]' % [std.join(', ', [std.manifestPython(v2) for v2 in v])]164    else if std.isString(v) then165      '%s' % [std.escapeStringPython(v)]166    else if std.isFunction(v) then167      error 'cannot manifest function'168    else if std.isNumber(v) then169      std.toString(v)170    else if v == true then171      'True'172    else if v == false then173      'False'174    else if v == null then175      'None',176177  manifestPythonVars(conf)::178    local vars = ['%s = %s' % [k, std.manifestPython(conf[k])] for k in std.objectFields(conf)];179    std.join('\n', vars + ['']),180181  manifestXmlJsonml(value)::182    if !std.isArray(value) then183      error 'Expected a JSONML value (an array), got %s' % std.type(value)184    else185      local aux(v) =186        if std.isString(v) then187          v188        else189          local tag = v[0];190          local has_attrs = std.length(v) > 1 && std.isObject(v[1]);191          local attrs = if has_attrs then v[1] else {};192          local children = if has_attrs then v[2:] else v[1:];193          local attrs_str =194            std.join('', [' %s="%s"' % [k, attrs[k]] for k in std.objectFields(attrs)]);195          std.deepJoin(['<', tag, attrs_str, '>', [aux(x) for x in children], '</', tag, '>']);196197      aux(value),198199  setUnion(a, b, keyF=id)::200    // NOTE: order matters, values in `a` win201    local aux(a, b, i, j, acc) =202      if i >= std.length(a) then203        acc + b[j:]204      else if j >= std.length(b) then205        acc + a[i:]206      else207        local ak = keyF(a[i]);208        local bk = keyF(b[j]);209        if ak == bk then210          aux(a, b, i + 1, j + 1, acc + [a[i]]) tailstrict211        else if ak < bk then212          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict213        else214          aux(a, b, i, j + 1, acc + [b[j]]) tailstrict;215    aux(a, b, 0, 0, []),216217  setDiff(a, b, keyF=id)::218    local aux(a, b, i, j, acc) =219      if i >= std.length(a) then220        acc221      else if j >= std.length(b) then222        acc + a[i:]223      else224        if keyF(a[i]) == keyF(b[j]) then225          aux(a, b, i + 1, j + 1, acc) tailstrict226        else if keyF(a[i]) < keyF(b[j]) then227          aux(a, b, i + 1, j, acc + [a[i]]) tailstrict228        else229          aux(a, b, i, j + 1, acc) tailstrict;230    aux(a, b, 0, 0, []) tailstrict,231232  mergePatch(target, patch)::233    if std.isObject(patch) then234      local target_object =235        if std.isObject(target) then target else {};236237      local target_fields =238        if std.isObject(target_object) then std.objectFields(target_object) else [];239240      local null_fields = [k for k in std.objectFields(patch) if patch[k] == null];241      local both_fields = std.setUnion(target_fields, std.objectFields(patch));242243      {244        [k]:245          if !std.objectHas(patch, k) then246            target_object[k]247          else if !std.objectHas(target_object, k) then248            std.mergePatch(null, patch[k]) tailstrict249          else250            std.mergePatch(target_object[k], patch[k]) tailstrict251        for k in std.setDiff(both_fields, null_fields)252      }253    else254      patch,255256  get(o, f, default=null, inc_hidden=true)::257    if std.objectHasEx(o, f, inc_hidden) then o[f] else default,258259  objectFields(o)::260    std.objectFieldsEx(o, false),261262  objectFieldsAll(o)::263    std.objectFieldsEx(o, true),264265  objectHas(o, f)::266    std.objectHasEx(o, f, false),267268  objectHasAll(o, f)::269    std.objectHasEx(o, f, true),270271  objectValues(o)::272    [o[k] for k in std.objectFields(o)],273274  objectValuesAll(o)::275    [o[k] for k in std.objectFieldsAll(o)],276277  objectKeysValues(o)::278    [{ key: k, value: o[k] } for k in std.objectFields(o)],279	280  objectKeysValuesAll(o)::281		[{ key: k, value: o[k] } for k in std.objectFieldsAll(o)],282283  resolvePath(f, r)::284    local arr = std.split(f, '/');285    std.join('/', std.makeArray(std.length(arr) - 1, function(i) arr[i]) + [r]),286287  prune(a)::288    local isContent(b) =289      if b == null then290        false291      else if std.isArray(b) then292        std.length(b) > 0293      else if std.isObject(b) then294        std.length(b) > 0295      else296        true;297    if std.isArray(a) then298      [std.prune(x) for x in a if isContent($.prune(x))]299    else if std.isObject(a) then {300      [x]: $.prune(a[x])301      for x in std.objectFields(a)302      if isContent(std.prune(a[x]))303    } else304      a,305306  find(value, arr)::307    if !std.isArray(arr) then308      error 'find second parameter should be an array, got ' + std.type(arr)309    else310      std.filter(function(i) arr[i] == value, std.range(0, std.length(arr) - 1)),311312  // Compat313  __compare_array(arr1, arr2)::314    assert std.isArray(arr1) && std.isArray(arr2);315    std.__compare(arr1, arr2),316  __array_less(arr1, arr2):: std.__compare_array(arr1, arr2) == -1,317  __array_greater(arr1, arr2):: std.__compare_array(arr1, arr2) == 1,318  __array_less_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) <= 0,319  __array_greater_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) >= 0,320}