difftreelog
feat sync jsonnet stdlib changes
in: master
8 files changed
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -413,18 +413,19 @@
val.value_type()
)
};
- if !arr.is_empty() {
- for (i, v) in arr.iter().enumerate() {
- let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
- out.push_str("---\n");
- in_description_frame(
- || format!("elem <{i}> manifestification"),
- || self.inner.manifest_buf(v, out),
- )?;
+ for (i, v) in arr.iter().enumerate() {
+ if i != 0 {
out.push('\n');
}
+ let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
+ out.push_str("---\n");
+ in_description_frame(
+ || format!("elem <{i}> manifestification"),
+ || self.inner.manifest_buf(v, out),
+ )?;
}
if self.c_document_end {
+ out.push('\n');
out.push_str("...");
}
if self.end_newline {
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -237,7 +237,11 @@
Expr::ArrComp(expr, specs)
}
pub rule number_expr(s: &ParserSettings) -> Expr
- = n:number() { expr::Expr::Num(n) }
+ = n:number() {? if n.is_finite() {
+ Ok(expr::Expr::Num(n))
+ } else {
+ Err("!!!numbers are finite")
+ }}
pub rule var_expr(s: &ParserSettings) -> Expr
= n:id() { expr::Expr::Var(n) }
pub rule id_loc(s: &ParserSettings) -> LocExpr
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth1#![allow(clippy::similar_names)]23use std::{4 cell::{Ref, RefCell, RefMut},5 collections::HashMap,6 f64,7 rc::Rc,8};910pub use arrays::*;11pub use compat::*;12pub use encoding::*;13pub use hash::*;14use jrsonnet_evaluator::{15 error::{ErrorKind::*, Result},16 function::{CallLocation, FuncVal, TlaArg},17 trace::PathResolver,18 val::NumValue,19 ContextBuilder, IStr, ObjValue, ObjValueBuilder, Thunk, Val,20};21use jrsonnet_gcmodule::{Acyclic, Cc, Trace};22use jrsonnet_parser::Source;23pub use manifest::*;24pub use math::*;25pub use misc::*;26pub use objects::*;27pub use operator::*;28pub use parse::*;29pub use sets::*;30pub use sort::*;31pub use strings::*;32pub use types::*;3334#[cfg(feature = "exp-regex")]35pub use crate::regex::*;3637mod arrays;38mod compat;39mod encoding;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: Cc<RefCell<Settings>>) -> ObjValue {56 let mut builder = ObjValueBuilder::new();5758 // FIXME: Use PHF59 for (name, builtin) in [60 // Types61 ("type", builtin_type::INST),62 ("isString", builtin_is_string::INST),63 ("isNumber", builtin_is_number::INST),64 ("isBoolean", builtin_is_boolean::INST),65 ("isObject", builtin_is_object::INST),66 ("isArray", builtin_is_array::INST),67 ("isFunction", builtin_is_function::INST),68 ("isNull", builtin_is_null::INST),69 // Arrays70 ("makeArray", builtin_make_array::INST),71 ("repeat", builtin_repeat::INST),72 ("slice", builtin_slice::INST),73 ("map", builtin_map::INST),74 ("mapWithIndex", builtin_map_with_index::INST),75 ("mapWithKey", builtin_map_with_key::INST),76 ("flatMap", builtin_flatmap::INST),77 ("filter", builtin_filter::INST),78 ("foldl", builtin_foldl::INST),79 ("foldr", builtin_foldr::INST),80 ("range", builtin_range::INST),81 ("join", builtin_join::INST),82 ("lines", builtin_lines::INST),83 ("resolvePath", builtin_resolve_path::INST),84 ("deepJoin", builtin_deep_join::INST),85 ("reverse", builtin_reverse::INST),86 ("any", builtin_any::INST),87 ("all", builtin_all::INST),88 ("member", builtin_member::INST),89 ("find", builtin_find::INST),90 ("contains", builtin_contains::INST),91 ("count", builtin_count::INST),92 ("avg", builtin_avg::INST),93 ("removeAt", builtin_remove_at::INST),94 ("remove", builtin_remove::INST),95 ("flattenArrays", builtin_flatten_arrays::INST),96 ("flattenDeepArray", builtin_flatten_deep_array::INST),97 ("prune", builtin_prune::INST),98 ("filterMap", builtin_filter_map::INST),99 // Math100 ("abs", builtin_abs::INST),101 ("sign", builtin_sign::INST),102 ("max", builtin_max::INST),103 ("min", builtin_min::INST),104 ("clamp", builtin_clamp::INST),105 ("sum", builtin_sum::INST),106 ("modulo", builtin_modulo::INST),107 ("floor", builtin_floor::INST),108 ("ceil", builtin_ceil::INST),109 ("log", builtin_log::INST),110 ("log2", builtin_log2::INST),111 ("log10", builtin_log10::INST),112 ("pow", builtin_pow::INST),113 ("sqrt", builtin_sqrt::INST),114 ("sin", builtin_sin::INST),115 ("cos", builtin_cos::INST),116 ("tan", builtin_tan::INST),117 ("asin", builtin_asin::INST),118 ("acos", builtin_acos::INST),119 ("atan", builtin_atan::INST),120 ("atan2", builtin_atan2::INST),121 ("exp", builtin_exp::INST),122 ("mantissa", builtin_mantissa::INST),123 ("exponent", builtin_exponent::INST),124 ("round", builtin_round::INST),125 ("isEven", builtin_is_even::INST),126 ("isOdd", builtin_is_odd::INST),127 ("isInteger", builtin_is_integer::INST),128 ("isDecimal", builtin_is_decimal::INST),129 ("deg2rad", builtin_deg2rad::INST),130 ("rad2deg", builtin_rad2deg::INST),131 ("hypot", builtin_hypot::INST),132 // Operator133 ("mod", builtin_mod::INST),134 ("primitiveEquals", builtin_primitive_equals::INST),135 ("equals", builtin_equals::INST),136 ("xor", builtin_xor::INST),137 ("xnor", builtin_xnor::INST),138 ("format", builtin_format::INST),139 // Sort140 ("sort", builtin_sort::INST),141 ("uniq", builtin_uniq::INST),142 ("set", builtin_set::INST),143 ("minArray", builtin_min_array::INST),144 ("maxArray", builtin_max_array::INST),145 // Hash146 ("md5", builtin_md5::INST),147 ("sha1", builtin_sha1::INST),148 ("sha256", builtin_sha256::INST),149 ("sha512", builtin_sha512::INST),150 ("sha3", builtin_sha3::INST),151 // Encoding152 ("encodeUTF8", builtin_encode_utf8::INST),153 ("decodeUTF8", builtin_decode_utf8::INST),154 ("base64", builtin_base64::INST),155 ("base64Decode", builtin_base64_decode::INST),156 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),157 // Objects158 ("objectFieldsEx", builtin_object_fields_ex::INST),159 ("objectFields", builtin_object_fields::INST),160 ("objectFieldsAll", builtin_object_fields_all::INST),161 ("objectValues", builtin_object_values::INST),162 ("objectValuesAll", builtin_object_values_all::INST),163 ("objectKeysValues", builtin_object_keys_values::INST),164 ("objectKeysValuesAll", builtin_object_keys_values_all::INST),165 ("objectHasEx", builtin_object_has_ex::INST),166 ("objectHas", builtin_object_has::INST),167 ("objectHasAll", builtin_object_has_all::INST),168 ("objectRemoveKey", builtin_object_remove_key::INST),169 // Manifest170 ("escapeStringJson", builtin_escape_string_json::INST),171 ("escapeStringPython", builtin_escape_string_python::INST),172 ("escapeStringXML", builtin_escape_string_xml::INST),173 ("manifestJsonEx", builtin_manifest_json_ex::INST),174 ("manifestJson", builtin_manifest_json::INST),175 ("manifestJsonMinified", builtin_manifest_json_minified::INST),176 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),177 ("manifestYamlStream", builtin_manifest_yaml_stream::INST),178 ("manifestTomlEx", builtin_manifest_toml_ex::INST),179 ("manifestToml", builtin_manifest_toml::INST),180 ("toString", builtin_to_string::INST),181 ("manifestPython", builtin_manifest_python::INST),182 ("manifestPythonVars", builtin_manifest_python_vars::INST),183 ("manifestXmlJsonml", builtin_manifest_xml_jsonml::INST),184 ("manifestIni", builtin_manifest_ini::INST),185 // Parse186 ("parseJson", builtin_parse_json::INST),187 ("parseYaml", builtin_parse_yaml::INST),188 // Strings189 ("codepoint", builtin_codepoint::INST),190 ("substr", builtin_substr::INST),191 ("char", builtin_char::INST),192 ("strReplace", builtin_str_replace::INST),193 ("escapeStringBash", builtin_escape_string_bash::INST),194 ("escapeStringDollars", builtin_escape_string_dollars::INST),195 ("isEmpty", builtin_is_empty::INST),196 ("equalsIgnoreCase", builtin_equals_ignore_case::INST),197 ("splitLimit", builtin_splitlimit::INST),198 ("splitLimitR", builtin_splitlimitr::INST),199 ("split", builtin_split::INST),200 ("asciiUpper", builtin_ascii_upper::INST),201 ("asciiLower", builtin_ascii_lower::INST),202 ("findSubstr", builtin_find_substr::INST),203 ("parseInt", builtin_parse_int::INST),204 #[cfg(feature = "exp-bigint")]205 ("bigint", builtin_bigint::INST),206 ("parseOctal", builtin_parse_octal::INST),207 ("parseHex", builtin_parse_hex::INST),208 ("stringChars", builtin_string_chars::INST),209 ("lstripChars", builtin_lstrip_chars::INST),210 ("rstripChars", builtin_rstrip_chars::INST),211 ("stripChars", builtin_strip_chars::INST),212 ("trim", builtin_trim::INST),213 // Misc214 ("length", builtin_length::INST),215 ("get", builtin_get::INST),216 ("startsWith", builtin_starts_with::INST),217 ("endsWith", builtin_ends_with::INST),218 ("assertEqual", builtin_assert_equal::INST),219 ("mergePatch", builtin_merge_patch::INST),220 // Sets221 ("setMember", builtin_set_member::INST),222 ("setInter", builtin_set_inter::INST),223 ("setDiff", builtin_set_diff::INST),224 ("setUnion", builtin_set_union::INST),225 // Regex226 #[cfg(feature = "exp-regex")]227 ("regexQuoteMeta", builtin_regex_quote_meta::INST),228 // Compat229 ("__compare", builtin___compare::INST),230 ("__compare_array", builtin___compare_array::INST),231 ("__array_less", builtin___array_less::INST),232 ("__array_greater", builtin___array_greater::INST),233 ("__array_less_or_equal", builtin___array_less_or_equal::INST),234 (235 "__array_greater_or_equal",236 builtin___array_greater_or_equal::INST,237 ),238 ]239 .iter()240 .copied()241 {242 builder.method(name, builtin);243 }244245 builder.method(246 "extVar",247 builtin_ext_var {248 settings: settings.clone(),249 },250 );251 builder.method(252 "native",253 builtin_native {254 settings: settings.clone(),255 },256 );257 builder.method("trace", builtin_trace { settings });258 builder.method("id", FuncVal::Id);259260 builder.field("pi").hide().value(Val::Num(261 NumValue::new(f64::consts::PI).expect("pi is finite"),262 ));263264 #[cfg(feature = "exp-regex")]265 {266 // Regex267 let regex_cache = RegexCache::default();268 builder.method(269 "regexFullMatch",270 builtin_regex_full_match {271 cache: regex_cache.clone(),272 },273 );274 builder.method(275 "regexPartialMatch",276 builtin_regex_partial_match {277 cache: regex_cache.clone(),278 },279 );280 builder.method(281 "regexReplace",282 builtin_regex_replace {283 cache: regex_cache.clone(),284 },285 );286 builder.method(287 "regexGlobalReplace",288 builtin_regex_global_replace { cache: regex_cache },289 );290 };291292 builder.build()293}294295pub trait TracePrinter: Acyclic {296 fn print_trace(&self, loc: CallLocation, value: IStr);297}298299#[derive(Acyclic)]300pub struct StdTracePrinter {301 resolver: PathResolver,302}303impl StdTracePrinter {304 pub fn new(resolver: PathResolver) -> Self {305 Self { resolver }306 }307}308impl TracePrinter for StdTracePrinter {309 fn print_trace(&self, loc: CallLocation, value: IStr) {310 eprint!("TRACE:");311 if let Some(loc) = loc.0 {312 let locs = loc.0.map_source_locations(&[loc.1]);313 eprint!(314 " {}:{}",315 loc.0.source_path().path().map_or_else(316 || loc.0.source_path().to_string(),317 |p| self.resolver.resolve(p)318 ),319 locs[0].line320 );321 }322 eprintln!(" {value}");323 }324}325326#[derive(Clone, Trace)]327pub struct Settings {328 /// Used for `std.extVar`329 pub ext_vars: HashMap<IStr, TlaArg>,330 /// Used for `std.native`331 pub ext_natives: HashMap<IStr, FuncVal>,332 /// Used for `std.trace`333 pub trace_printer: Rc<dyn TracePrinter>,334 /// Used for `std.thisFile`335 pub path_resolver: PathResolver,336}337338fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {339 let source_name = format!("<extvar:{name}>");340 Source::new_virtual(source_name.into(), code.into())341}342343#[derive(Trace, Clone)]344pub struct ContextInitializer {345 /// std without applied thisFile overlay346 stdlib_obj: ObjValue,347 settings: Cc<RefCell<Settings>>,348}349impl ContextInitializer {350 pub fn new(resolver: PathResolver) -> Self {351 let settings = Settings {352 ext_vars: HashMap::new(),353 ext_natives: HashMap::new(),354 trace_printer: Rc::new(StdTracePrinter::new(resolver.clone())),355 path_resolver: resolver,356 };357 let settings = Cc::new(RefCell::new(settings));358 let stdlib_obj = stdlib_uncached(settings.clone());359 Self {360 stdlib_obj,361 settings,362 }363 }364 pub fn settings(&self) -> Ref<'_, Settings> {365 self.settings.borrow()366 }367 pub fn settings_mut(&self) -> RefMut<'_, Settings> {368 self.settings.borrow_mut()369 }370 pub fn add_ext_var(&self, name: IStr, value: Val) {371 self.settings_mut()372 .ext_vars373 .insert(name, TlaArg::Val(value));374 }375 pub fn add_ext_str(&self, name: IStr, value: IStr) {376 self.settings_mut()377 .ext_vars378 .insert(name, TlaArg::String(value));379 }380 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {381 let code = code.into();382 let source = extvar_source(name, code.clone());383 let parsed = jrsonnet_parser::parse(384 &code,385 &jrsonnet_parser::ParserSettings {386 source: source.clone(),387 },388 )389 .map_err(|e| ImportSyntaxError {390 path: source,391 error: Box::new(e),392 })?;393 // self.data_mut().volatile_files.insert(source_name, code);394 self.settings_mut()395 .ext_vars396 .insert(name.into(), TlaArg::Code(parsed));397 Ok(())398 }399 pub fn add_native(&self, name: impl Into<IStr>, cb: impl Into<FuncVal>) {400 self.settings_mut()401 .ext_natives402 .insert(name.into(), cb.into());403 }404}405impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {406 fn reserve_vars(&self) -> usize {407 1408 }409 fn populate(&self, source: Source, builder: &mut ContextBuilder) {410 let mut std = ObjValueBuilder::new();411 std.with_super(self.stdlib_obj.clone());412 std.field("thisFile").hide().value({413 let source_path = source.source_path();414 source_path.path().map_or_else(415 || source_path.to_string(),416 |p| self.settings().path_resolver.resolve(p),417 )418 });419 let stdlib_with_this_file = std.build();420421 builder.bind("std", Thunk::evaluated(Val::Obj(stdlib_with_this_file)));422 }423 fn as_any(&self) -> &dyn std::any::Any {424 self425 }426}crates/jrsonnet-stdlib/src/math.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/math.rs
+++ b/crates/jrsonnet-stdlib/src/math.rs
@@ -1,3 +1,5 @@
+use std::f64;
+
use jrsonnet_evaluator::{function::builtin, typed::PositiveF64};
#[builtin]
@@ -56,6 +58,16 @@
}
#[builtin]
+pub fn builtin_log2(x: f64) -> f64 {
+ x.log2()
+}
+
+#[builtin]
+pub fn builtin_log10(x: f64) -> f64 {
+ x.log10()
+}
+
+#[builtin]
pub fn builtin_pow(x: f64, n: f64) -> f64 {
x.powf(n)
}
@@ -153,3 +165,18 @@
pub fn builtin_is_decimal(x: f64) -> bool {
builtin_round(x) != x
}
+
+#[builtin]
+pub fn builtin_deg2rad(x: f64) -> f64 {
+ x * f64::consts::PI / 180.0
+}
+
+#[builtin]
+pub fn builtin_rad2deg(x: f64) -> f64 {
+ x * 180.0 / f64::consts::PI
+}
+
+#[builtin]
+pub fn builtin_hypot(x: f64, y: f64) -> f64 {
+ x.hypot(y)
+}
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -156,8 +156,16 @@
#[cfg(feature = "exp-preserve-order")]
true,
);
- let a = a.manifest(&format).description("<a> manifestification")?;
- let b = b.manifest(&format).description("<b> manifestification")?;
+ let a = if let Some(a) = a.as_str() {
+ format!("<A>\n{a}\n</A>")
+ } else {
+ a.manifest(&format).description("<a> manifestification")?
+ };
+ let b = if let Some(b) = b.as_str() {
+ format!("<B>\n{b}\n</B>")
+ } else {
+ b.manifest(&format).description("<b> manifestification")?
+ };
bail!("assertion failed: A != B\nA: {a}\nB: {b}")
}
@@ -166,9 +174,7 @@
let Some(patch) = patch.as_obj() else {
return Ok(patch);
};
- let Some(target) = target.as_obj() else {
- return Ok(Val::Obj(patch));
- };
+ let target = target.as_obj().unwrap_or_else(|| ObjValue::new_empty());
let target_fields = target
.fields(
// FIXME: Makes no sense to preserve order for BTreeSet, it would be better to use IndexSet here?
@@ -203,10 +209,7 @@
if matches!(field_patch, Val::Null) {
continue;
}
- let Some(field_target) = target.get(field.clone())? else {
- out.field(field.clone()).value(field_patch);
- continue;
- };
+ let field_target = target.get(field.clone())?.unwrap_or(Val::Null);
out.field(field.clone())
.value(builtin_merge_patch(field_target, field_patch)?);
}
crates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,7 +1,8 @@
use jrsonnet_evaluator::{
function::builtin,
+ rustc_hash::FxHashSet,
val::{ArrValue, Val},
- IStr, ObjValue, ObjValueBuilder,
+ IStr, MaybeUnbound, ObjValue, ObjValueBuilder, Thunk,
};
#[builtin]
@@ -166,14 +167,31 @@
preserve_order: bool,
) -> ObjValue {
let mut new_obj = ObjValueBuilder::with_capacity(obj.len() - 1);
- for (k, v) in obj.iter(
+ let all_fields = obj.fields_ex(
+ true,
#[cfg(feature = "exp-preserve-order")]
preserve_order,
- ) {
- if k == key {
+ );
+ let visible_fields = obj
+ .fields_ex(
+ false,
+ #[cfg(feature = "exp-preserve-order")]
+ preserve_order,
+ )
+ .into_iter()
+ .collect::<FxHashSet<_>>();
+
+ for field in &all_fields {
+ if *field == key {
continue;
}
- new_obj.field(k).value(v.unwrap());
+ let mut b = new_obj.field(field.clone());
+ if !visible_fields.contains(&field) {
+ b = b.hide();
+ }
+ let _ = b.binding(MaybeUnbound::Bound(Thunk::result(
+ obj.get(field.clone()).transpose().expect("field exists"),
+ )));
}
new_obj.build()
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -254,6 +254,19 @@
Ok(str.as_str().trim_matches(pattern).into())
}
+#[builtin]
+pub fn builtin_trim(str: IStr) -> String {
+ let filter =
+ |v: char| {
+ v == ' '
+ || v == '\t' || v == '\n'
+ || v == '\u{000c}'
+ || v == '\r' || v == '\u{0085}'
+ || v == '\u{00a0}'
+ };
+ str.as_str().trim_matches(filter).to_string()
+}
+
fn new_trim_pattern(chars: IndexableVal) -> Result<impl Fn(char) -> bool> {
let chars: BTreeSet<char> = match chars {
IndexableVal::Str(chars) => chars.chars().collect(),
crates/jrsonnet-stdlib/src/types.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/types.rs
+++ b/crates/jrsonnet-stdlib/src/types.rs
@@ -29,3 +29,7 @@
pub fn builtin_is_function(v: Val) -> bool {
matches!(v, Val::Func(_))
}
+#[builtin]
+pub fn builtin_is_null(v: Val) -> bool {
+ matches!(v, Val::Null)
+}