difftreelog
refactor(evaluator)! remove standard library
in: master
Implementation will be moved to jrsonnet-stdlib crate BREAKING CHANGE: `State::with_stdlib` was removed
9 files changed
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -7,9 +7,7 @@
edition = "2021"
[features]
-default = ["serialized-stdlib", "explaining-traces", "friendly-errors"]
-# Serializes standard library AST instead of parsing them every run
-serialized-stdlib = ["bincode", "jrsonnet-parser/serde"]
+default = ["explaining-traces", "friendly-errors"]
# Rustc-like trace visualization
explaining-traces = ["annotate-snippets"]
# Allows library authors to throw custom errors
@@ -23,11 +21,12 @@
exp-serde-preserve-order = ["serde_json/preserve_order"]
# Implements field destructuring
exp-destruct = ["jrsonnet-parser/exp-destruct"]
+# Provide Typed for conversions to/from serde_json::Value type
+serde_json = ["dep:serde_json"]
[dependencies]
jrsonnet-interner = { path = "../jrsonnet-interner", version = "0.4.2" }
jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
-jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }
jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
jrsonnet-gcmodule = { version = "0.3.4" }
@@ -36,15 +35,13 @@
hashbrown = "0.12.1"
static_assertions = "1.1"
-md5 = "0.7.0"
-base64 = "0.13.0"
rustc-hash = "1.1"
thiserror = "1.0"
serde = "1.0"
-serde_json = "1.0"
-serde_yaml_with_quirks = "0.8.24"
+# Optional integration
+serde_json = { version = "1.0.82", optional = true }
anyhow = { version = "1.0", optional = true }
# Friendly errors
@@ -53,9 +50,3 @@
bincode = { version = "1.3", optional = true }
# Explaining traces
annotate-snippets = { version = "0.9.1", features = ["color"], optional = true }
-
-[build-dependencies]
-jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
-jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
-serde = "1.0"
-bincode = "1.3"
crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-use std::{borrow::Cow, env, fs::File, io::Write, path::Path};
-
-use bincode::serialize;
-use jrsonnet_parser::{parse, ParserSettings, Source};
-use jrsonnet_stdlib::STDLIB_STR;
-
-fn main() {
- let parsed = parse(
- STDLIB_STR,
- &ParserSettings {
- file_name: Source::new_virtual(Cow::Borrowed("<std>")),
- },
- )
- .expect("parse");
-
- {
- let out_dir = env::var("OUT_DIR").unwrap();
- let dest_path = Path::new(&out_dir).join("stdlib.bincode");
- let mut f = File::create(&dest_path).unwrap();
- f.write_all(&serialize(&parsed).unwrap()).unwrap();
- }
-}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -6,10 +6,7 @@
use jrsonnet_types::ValType;
use thiserror::Error;
-use crate::{
- stdlib::{format::FormatError, sort::SortError},
- typed::TypeLocError,
-};
+use crate::{stdlib::format::FormatError, typed::TypeLocError};
fn format_found(list: &[IStr], what: &str) -> String {
if list.is_empty() {
@@ -169,13 +166,6 @@
Format(#[from] FormatError),
#[error("type error: {0}")]
TypeError(TypeLocError),
- #[error("sort error: {0}")]
- Sort(#[from] SortError),
-
- /// Thrown as error, as this is legacy feature, and error here
- /// is acceptable for defeating object field cache
- #[error("should not reach outside: std.thisFile")]
- MagicThisFileUsed,
#[cfg(feature = "anyhow-error")]
#[error(transparent)]
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -13,10 +13,9 @@
error::Error::*,
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
- stdlib::{std_slice, BUILTINS},
tb, throw,
typed::Typed,
- val::{ArrValue, CachedUnbound, Thunk, ThunkValue},
+ val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},
Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,
Unbound, Val,
};
@@ -417,13 +416,13 @@
Literal(LiteralType::This) => {
Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
}
- Literal(LiteralType::Super) => Val::Obj(
- ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(
+ Literal(LiteralType::Super) => {
+ Val::Obj(ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(
ctx.this()
.clone()
.expect("if super exists - then this should to"),
- ),
- ),
+ ))
+ }
Literal(LiteralType::Dollar) => {
Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)
}
@@ -473,9 +472,6 @@
heap.into_iter().map(|(_, v)| v).collect()
))
}
- Err(e) if matches!(e.error(), MagicThisFileUsed) => {
- Ok(Val::Str(loc.0.full_path().into()))
- }
Err(e) => Err(e),
},
)?,
@@ -573,13 +569,6 @@
Function(params, body) => {
evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())
}
- Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(
- BUILTINS
- .with(|b| b.get(name).copied())
- .ok_or_else(|| IntrinsicNotFound(name.clone()))?,
- )),
- IntrinsicThisFile => return Err(MagicThisFileUsed.into()),
- IntrinsicId => Val::Func(FuncVal::identity()),
AssertExpr(assert, returned) => {
evaluate_assert(s.clone(), ctx.clone(), assert)?;
evaluate(s, ctx, returned)?
@@ -635,9 +624,9 @@
let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;
let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;
- let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;
+ let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;
- std_slice(indexable.into_indexable()?, start, end, step)?
+ IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?
}
i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
let tmp = loc.clone().0;
crates/jrsonnet-evaluator/src/function/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/native.rs
+++ b/crates/jrsonnet-evaluator/src/function/native.rs
@@ -1,5 +1,5 @@
use super::{arglike::ArgLike, CallLocation, FuncVal};
-use crate::{error::Result, typed::Typed, State};
+use crate::{error::Result, typed::Typed, Context, State};
pub trait NativeDesc {
type Value;
@@ -19,7 +19,8 @@
Box::new(move |s: State, $($gen),*| {
let val = val.evaluate(
s.clone(),
- s.create_default_context(),
+ // This isn't intended to be used with ArgsDesc
+ Context::default(),
CallLocation::native(),
&($($gen,)*),
true
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -37,12 +37,13 @@
mod integrations;
mod map;
mod obj;
-mod stdlib;
+pub mod stdlib;
pub mod trace;
pub mod typed;
pub mod val;
use std::{
+ any::Any,
borrow::Cow,
cell::{Ref, RefCell, RefMut},
collections::HashMap,
@@ -55,13 +56,12 @@
pub use dynamic::*;
use error::{Error::*, LocError, Result, StackTraceElement};
pub use evaluate::*;
-use function::{builtin::Builtin, CallLocation, TlaArg};
+use function::{CallLocation, TlaArg};
use gc::{GcHashMap, TraceBox};
use hashbrown::hash_map::RawEntryMut;
pub use import::*;
use jrsonnet_gcmodule::{Cc, Trace};
-use jrsonnet_interner::IBytes;
-pub use jrsonnet_interner::IStr;
+pub use jrsonnet_interner::{IBytes, IStr};
pub use jrsonnet_parser as parser;
use jrsonnet_parser::*;
pub use obj::*;
@@ -98,19 +98,40 @@
}
}
+/// During import, this trait will be called to create initial context for file
+/// It may initialize global variables, stdlib for example
+pub trait ContextInitializer {
+ fn initialize(&self, state: State, for_file: Source) -> Context;
+
+ /// # Safety
+ ///
+ /// For use only in bindings, should not be used elsewhere.
+ /// Implementations which are not intended to be used in bindings
+ /// should panic on call to this method.
+ unsafe fn as_any(&self) -> &dyn Any;
+}
+
+/// Context initializer, which adds noth
+pub struct DummyContextInitializer;
+impl ContextInitializer for DummyContextInitializer {
+ fn initialize(&self, _state: State, _for_file: Source) -> Context {
+ Context::default()
+ }
+ unsafe fn as_any(&self) -> &dyn Any {
+ panic!("`as_any(&self)` is not supported by dummy initializer")
+ }
+}
+
pub struct EvaluationSettings {
/// Limits recursion by limiting the number of stack frames
pub max_stack: usize,
/// Limits amount of stack trace items preserved
pub max_trace: usize,
- /// Used for s`td.extVar`
- pub ext_vars: HashMap<IStr, TlaArg>,
- /// Used for ext.native
- pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,
/// TLA vars
pub tla_vars: HashMap<IStr, TlaArg>,
- /// Global variables are inserted in default context
- pub globals: HashMap<IStr, Val>,
+ /// Context initializer, which will be used for imports and everything
+ /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`
+ pub context_initializer: Box<dyn ContextInitializer>,
/// Used to resolve file locations/contents
pub import_resolver: Box<dyn ImportResolver>,
/// Used in manifestification functions
@@ -123,9 +144,7 @@
Self {
max_stack: 200,
max_trace: 20,
- globals: HashMap::default(),
- ext_vars: HashMap::default(),
- ext_natives: HashMap::default(),
+ context_initializer: Box::new(DummyContextInitializer),
tla_vars: HashMap::default(),
import_resolver: Box::new(DummyImportResolver),
manifest_format: ManifestFormat::Json {
@@ -152,7 +171,8 @@
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
files: GcHashMap<PathBuf, FileData>,
- /// Contains tla arguments and others, which aren't needed to be obtained by name
+ /// Contains tla arguments and others, which aren't needed to be obtained by name, however may be used for receiving source
+ /// TODO: look into nix approach, storing source code in `Source` object
volatile_files: GcHashMap<String, String>,
}
struct FileData {
@@ -333,7 +353,7 @@
},
)
.map_err(|e| ImportSyntaxError {
- path: file_name,
+ path: file_name.clone(),
source_code: code.clone(),
error: Box::new(e),
})?,
@@ -346,7 +366,11 @@
file.evaluating = true;
// Dropping file here, as it borrows data, which may be used in evaluation
drop(data);
- let res = evaluate(self.clone(), self.create_default_context(), &parsed);
+ let res = evaluate(
+ self.clone(),
+ self.create_default_context(file_name),
+ &parsed,
+ );
let mut data = self.data_mut();
let mut file = data.files.raw_entry_mut().from_key(&path);
@@ -391,26 +415,11 @@
column,
)
}
- /// Adds standard library global variable (std) to this evaluator
- pub fn with_stdlib(&self) -> &Self {
- let val = evaluate(
- self.clone(),
- self.create_default_context(),
- &stdlib::get_parsed_stdlib(),
- )
- .expect("std should not fail");
- self.settings_mut().globals.insert("std".into(), val);
- self
- }
/// Creates context with all passed global variables
- pub fn create_default_context(&self) -> Context {
- let globals = &self.settings().globals;
- let mut new_bindings = GcHashMap::with_capacity(globals.len());
- for (name, value) in globals.iter() {
- new_bindings.insert(name.clone(), Thunk::evaluated(value.clone()));
- }
- Context::new().extend(new_bindings, None, None, None)
+ pub fn create_default_context(&self, source: Source) -> Context {
+ let context_initializer = &self.settings().context_initializer;
+ context_initializer.initialize(self.clone(), source)
}
/// Executes code creating a new stack frame
@@ -545,7 +554,7 @@
|| {
func.evaluate(
self.clone(),
- self.create_default_context(),
+ self.create_default_context(Source::new_virtual(Cow::Borrowed("<tla>"))),
CallLocation::native(),
&self.settings().tla_vars,
true,
@@ -585,48 +594,17 @@
},
)
.map_err(|e| ImportSyntaxError {
- path: source,
+ path: source.clone(),
source_code: code.clone().into(),
error: Box::new(e),
})?;
self.data_mut().volatile_files.insert(name, code);
- evaluate(self.clone(), self.create_default_context(), &parsed)
+ evaluate(self.clone(), self.create_default_context(source), &parsed)
}
}
/// Settings utilities
impl State {
- pub fn add_ext_var(&self, name: IStr, value: Val) {
- self.settings_mut()
- .ext_vars
- .insert(name, TlaArg::Val(value));
- }
- pub fn add_ext_str(&self, name: IStr, value: IStr) {
- self.settings_mut()
- .ext_vars
- .insert(name, TlaArg::String(value));
- }
- pub fn add_ext_code(&self, name: &str, code: String) -> Result<()> {
- let source_name = format!("<extvar:{}>", name);
- let source = Source::new_virtual(Cow::Owned(source_name.clone()));
- let parsed = jrsonnet_parser::parse(
- &code,
- &ParserSettings {
- file_name: source.clone(),
- },
- )
- .map_err(|e| ImportSyntaxError {
- path: source,
- source_code: code.clone().into(),
- error: Box::new(e),
- })?;
- self.data_mut().volatile_files.insert(source_name, code);
- self.settings_mut()
- .ext_vars
- .insert(name.into(), TlaArg::Code(parsed));
- Ok(())
- }
-
pub fn add_tla(&self, name: IStr, value: Val) {
self.settings_mut()
.tla_vars
@@ -672,9 +650,8 @@
pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {
self.settings_mut().import_resolver = resolver;
}
-
- pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {
- self.settings_mut().ext_natives.insert(name, cb);
+ pub fn context_initializer(&self) -> Ref<dyn ContextInitializer> {
+ Ref::map(self.settings(), |s| &*s.context_initializer)
}
pub fn manifest_format(&self) -> ManifestFormat {
crates/jrsonnet-evaluator/src/stdlib/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/expr.rs
+++ /dev/null
@@ -1,28 +0,0 @@
-use std::borrow::Cow;
-
-use jrsonnet_parser::{LocExpr, ParserSettings, Source};
-
-thread_local! {
- /// To avoid parsing again when issued from the same thread
- #[allow(unreachable_code)]
- static PARSED_STDLIB: LocExpr = {
- #[cfg(feature = "serialized-stdlib")]
- {
- // Should not panic, stdlib.bincode is generated in build.rs
- return bincode::deserialize(include_bytes!(concat!(env!("OUT_DIR"), "/stdlib.bincode")))
- .unwrap();
- }
-
- jrsonnet_parser::parse(
- jrsonnet_stdlib::STDLIB_STR,
- &ParserSettings {
- file_name: Source::new_virtual(Cow::Borrowed("<std>")),
- },
- )
- .unwrap()
- }
-}
-
-pub fn get_parsed_stdlib() -> LocExpr {
- PARSED_STDLIB.with(Clone::clone)
-}
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth1// All builtins should return results1// All builtins should return results2#![allow(clippy::unnecessary_wraps)]2#![allow(clippy::unnecessary_wraps)]34use std::collections::HashMap;536use format::{format_arr, format_obj};4use format::{format_arr, format_obj};7use jrsonnet_gcmodule::Cc;8use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_interner::IStr;9use serde::Deserialize;10use serde_yaml_with_quirks::DeserializingQuirks;11612use crate::{7use crate::{error::Result, function::CallLocation, State, Val};13 error::{Error::*, Result},14 function::{builtin::StaticBuiltin, ArgLike, CallLocation, FuncVal},15 operator::evaluate_mod_op,16 stdlib::manifest::{manifest_yaml_ex, ManifestYamlOptions},17 throw,18 typed::{Any, BoundedUsize, Either2, Either4, PositiveF64, Typed, VecVal, M1},19 val::{equals, primitive_equals, ArrValue, IndexableVal, Slice},20 Either, ObjValue, State, Val,21};2223pub mod expr;24pub use expr::*;2526use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};27828pub mod format;9pub mod format;29pub mod manifest;10pub mod manifest;30pub mod sort;311132pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {12pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {33 s.push(13 s.push(43 )23 )44}24}4546pub fn std_slice(47 indexable: IndexableVal,48 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,49 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,50 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,51) -> Result<Val> {52 match &indexable {53 IndexableVal::Str(s) => {54 let index = index.as_deref().copied().unwrap_or(0);55 let end = end.as_deref().copied().unwrap_or(usize::MAX);56 let step = step.as_deref().copied().unwrap_or(1);5758 if index >= end {59 return Ok(Val::Str("".into()));60 }6162 Ok(Val::Str(63 (s.chars()64 .skip(index)65 .take(end - index)66 .step_by(step)67 .collect::<String>())68 .into(),69 ))70 }71 IndexableVal::Arr(arr) => {72 let index = index.as_deref().copied().unwrap_or(0);73 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());74 let step = step.as_deref().copied().unwrap_or(1);7576 if index >= end {77 return Ok(Val::Arr(ArrValue::new_eager()));78 }7980 Ok(Val::Arr(ArrValue::Slice(Box::new(Slice {81 inner: arr.clone(),82 from: index as u32,83 to: end as u32,84 step: step as u32,85 }))))86 }87 }88}8990type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;9192thread_local! {93 pub static BUILTINS: BuiltinsType = {94 [95 ("length".into(), builtin_length::INST),96 ("type".into(), builtin_type::INST),97 ("makeArray".into(), builtin_make_array::INST),98 ("codepoint".into(), builtin_codepoint::INST),99 ("objectFieldsEx".into(), builtin_object_fields_ex::INST),100 ("objectHasEx".into(), builtin_object_has_ex::INST),101 ("slice".into(), builtin_slice::INST),102 ("substr".into(), builtin_substr::INST),103 ("primitiveEquals".into(), builtin_primitive_equals::INST),104 ("equals".into(), builtin_equals::INST),105 ("modulo".into(), builtin_modulo::INST),106 ("mod".into(), builtin_mod::INST),107 ("floor".into(), builtin_floor::INST),108 ("ceil".into(), builtin_ceil::INST),109 ("log".into(), builtin_log::INST),110 ("pow".into(), builtin_pow::INST),111 ("sqrt".into(), builtin_sqrt::INST),112 ("sin".into(), builtin_sin::INST),113 ("cos".into(), builtin_cos::INST),114 ("tan".into(), builtin_tan::INST),115 ("asin".into(), builtin_asin::INST),116 ("acos".into(), builtin_acos::INST),117 ("atan".into(), builtin_atan::INST),118 ("exp".into(), builtin_exp::INST),119 ("mantissa".into(), builtin_mantissa::INST),120 ("exponent".into(), builtin_exponent::INST),121 ("extVar".into(), builtin_ext_var::INST),122 ("native".into(), builtin_native::INST),123 ("filter".into(), builtin_filter::INST),124 ("map".into(), builtin_map::INST),125 ("flatMap".into(), builtin_flatmap::INST),126 ("foldl".into(), builtin_foldl::INST),127 ("foldr".into(), builtin_foldr::INST),128 ("sort".into(), builtin_sort::INST),129 ("format".into(), builtin_format::INST),130 ("range".into(), builtin_range::INST),131 ("char".into(), builtin_char::INST),132 ("encodeUTF8".into(), builtin_encode_utf8::INST),133 ("decodeUTF8".into(), builtin_decode_utf8::INST),134 ("md5".into(), builtin_md5::INST),135 ("base64".into(), builtin_base64::INST),136 ("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),137 ("base64Decode".into(), builtin_base64_decode::INST),138 ("trace".into(), builtin_trace::INST),139 ("join".into(), builtin_join::INST),140 ("escapeStringJson".into(), builtin_escape_string_json::INST),141 ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),142 ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),143 ("reverse".into(), builtin_reverse::INST),144 ("strReplace".into(), builtin_str_replace::INST),145 ("splitLimit".into(), builtin_splitlimit::INST),146 ("parseJson".into(), builtin_parse_json::INST),147 ("parseYaml".into(), builtin_parse_yaml::INST),148 ("asciiUpper".into(), builtin_ascii_upper::INST),149 ("asciiLower".into(), builtin_ascii_lower::INST),150 ("member".into(), builtin_member::INST),151 ("count".into(), builtin_count::INST),152 ("any".into(), builtin_any::INST),153 ("all".into(), builtin_all::INST),154 ].iter().cloned().collect()155 };156}157158#[jrsonnet_macros::builtin]159fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {160 use Either4::*;161 Ok(match x {162 A(x) => x.chars().count(),163 B(x) => x.len(),164 C(x) => x.len(),165 D(f) => f.params_len(),166 })167}168169#[jrsonnet_macros::builtin]170fn builtin_type(x: Any) -> Result<IStr> {171 Ok(x.0.value_type().name().into())172}173174#[jrsonnet_macros::builtin]175fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {176 let mut out = Vec::with_capacity(sz);177 for i in 0..sz {178 out.push(func.evaluate_simple(s.clone(), &(i as f64,))?);179 }180 Ok(VecVal(Cc::new(out)))181}182183#[jrsonnet_macros::builtin]184const fn builtin_codepoint(str: char) -> Result<u32> {185 Ok(str as u32)186}187188#[jrsonnet_macros::builtin]189fn builtin_object_fields_ex(190 obj: ObjValue,191 inc_hidden: bool,192 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,193) -> Result<VecVal> {194 #[cfg(feature = "exp-preserve-order")]195 let preserve_order = preserve_order.unwrap_or(false);196 let out = obj.fields_ex(197 inc_hidden,198 #[cfg(feature = "exp-preserve-order")]199 preserve_order,200 );201 Ok(VecVal(Cc::new(202 out.into_iter().map(Val::Str).collect::<Vec<_>>(),203 )))204}205206#[jrsonnet_macros::builtin]207fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {208 Ok(obj.has_field_ex(f, inc_hidden))209}210211#[jrsonnet_macros::builtin]212fn builtin_parse_json(st: State, s: IStr) -> Result<Any> {213 use serde_json::Value;214 let value: Value = serde_json::from_str(&s)215 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;216 Ok(Any(Value::into_untyped(value, st)?))217}218219#[jrsonnet_macros::builtin]220fn builtin_parse_yaml(st: State, s: IStr) -> Result<Any> {221 use serde_json::Value;222 let value = serde_yaml_with_quirks::Deserializer::from_str_with_quirks(223 &s,224 DeserializingQuirks { old_octals: true },225 );226 let mut out = vec![];227 for item in value {228 let value = Value::deserialize(item)229 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230 let val = Value::into_untyped(value, st.clone())?;231 out.push(val);232 }233 Ok(Any(if out.is_empty() {234 Val::Null235 } else if out.len() == 1 {236 out.into_iter().next().unwrap()237 } else {238 Val::Arr(out.into())239 }))240}241242#[jrsonnet_macros::builtin]243fn builtin_slice(244 indexable: IndexableVal,245 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,246 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,247 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,248) -> Result<Any> {249 std_slice(indexable, index, end, step).map(Any)250}251252#[jrsonnet_macros::builtin]253fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {254 Ok(str.chars().skip(from as usize).take(len as usize).collect())255}256257#[jrsonnet_macros::builtin]258fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {259 primitive_equals(&a.0, &b.0)260}261262#[jrsonnet_macros::builtin]263fn builtin_equals(s: State, a: Any, b: Any) -> Result<bool> {264 equals(s, &a.0, &b.0)265}266267#[jrsonnet_macros::builtin]268fn builtin_modulo(a: f64, b: f64) -> Result<f64> {269 Ok(a % b)270}271272#[jrsonnet_macros::builtin]273fn builtin_mod(s: State, a: Either![f64, IStr], b: Any) -> Result<Any> {274 use Either2::*;275 Ok(Any(evaluate_mod_op(276 s,277 &match a {278 A(v) => Val::Num(v),279 B(s) => Val::Str(s),280 },281 &b.0,282 )?))283}284285#[jrsonnet_macros::builtin]286fn builtin_floor(x: f64) -> Result<f64> {287 Ok(x.floor())288}289290#[jrsonnet_macros::builtin]291fn builtin_ceil(x: f64) -> Result<f64> {292 Ok(x.ceil())293}294295#[jrsonnet_macros::builtin]296fn builtin_log(n: f64) -> Result<f64> {297 Ok(n.ln())298}299300#[jrsonnet_macros::builtin]301fn builtin_pow(x: f64, n: f64) -> Result<f64> {302 Ok(x.powf(n))303}304305#[jrsonnet_macros::builtin]306fn builtin_sqrt(x: PositiveF64) -> Result<f64> {307 Ok(x.0.sqrt())308}309310#[jrsonnet_macros::builtin]311fn builtin_sin(x: f64) -> Result<f64> {312 Ok(x.sin())313}314315#[jrsonnet_macros::builtin]316fn builtin_cos(x: f64) -> Result<f64> {317 Ok(x.cos())318}319320#[jrsonnet_macros::builtin]321fn builtin_tan(x: f64) -> Result<f64> {322 Ok(x.tan())323}324325#[jrsonnet_macros::builtin]326fn builtin_asin(x: f64) -> Result<f64> {327 Ok(x.asin())328}329330#[jrsonnet_macros::builtin]331fn builtin_acos(x: f64) -> Result<f64> {332 Ok(x.acos())333}334335#[jrsonnet_macros::builtin]336fn builtin_atan(x: f64) -> Result<f64> {337 Ok(x.atan())338}339340#[jrsonnet_macros::builtin]341fn builtin_exp(x: f64) -> Result<f64> {342 Ok(x.exp())343}344345fn frexp(s: f64) -> (f64, i16) {346 if 0.0 == s {347 (s, 0)348 } else {349 let lg = s.abs().log2();350 let x = (lg - lg.floor() - 1.0).exp2();351 let exp = lg.floor() + 1.0;352 (s.signum() * x, exp as i16)353 }354}355356#[jrsonnet_macros::builtin]357fn builtin_mantissa(x: f64) -> Result<f64> {358 Ok(frexp(x).0)359}360361#[jrsonnet_macros::builtin]362fn builtin_exponent(x: f64) -> Result<i16> {363 Ok(frexp(x).1)364}365366#[jrsonnet_macros::builtin]367fn builtin_ext_var(s: State, x: IStr) -> Result<Any> {368 let ctx = s.create_default_context();369 Ok(Any(s370 .clone()371 .settings()372 .ext_vars373 .get(&x)374 .cloned()375 .ok_or(UndefinedExternalVariable(x))?376 .evaluate_arg(s.clone(), ctx, true)?377 .evaluate(s)?))378}379380#[jrsonnet_macros::builtin]381fn builtin_native(s: State, name: IStr) -> Result<Any> {382 Ok(Any(s383 .settings()384 .ext_natives385 .get(&name)386 .cloned()387 .map_or(Val::Null, |v| {388 Val::Func(FuncVal::Builtin(v.clone()))389 })))390}391392#[jrsonnet_macros::builtin]393fn builtin_filter(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {394 arr.filter(s.clone(), |val| {395 bool::from_untyped(396 func.evaluate_simple(s.clone(), &(Any(val.clone()),))?,397 s.clone(),398 )399 })400}401402#[jrsonnet_macros::builtin]403fn builtin_map(s: State, func: FuncVal, arr: ArrValue) -> Result<ArrValue> {404 arr.map(s.clone(), |val| {405 func.evaluate_simple(s.clone(), &(Any(val),))406 })407}408409#[jrsonnet_macros::builtin]410fn builtin_flatmap(s: State, func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {411 match arr {412 IndexableVal::Str(str) => {413 let mut out = String::new();414 for c in str.chars() {415 match func.evaluate_simple(s.clone(), &(c.to_string(),))? {416 Val::Str(o) => out.push_str(&o),417 Val::Null => continue,418 _ => throw!(RuntimeError(419 "in std.join all items should be strings".into()420 )),421 };422 }423 Ok(IndexableVal::Str(out.into()))424 }425 IndexableVal::Arr(a) => {426 let mut out = Vec::new();427 for el in a.iter(s.clone()) {428 let el = el?;429 match func.evaluate_simple(s.clone(), &(Any(el),))? {430 Val::Arr(o) => {431 for oe in o.iter(s.clone()) {432 out.push(oe?);433 }434 }435 Val::Null => continue,436 _ => throw!(RuntimeError(437 "in std.join all items should be arrays".into()438 )),439 };440 }441 Ok(IndexableVal::Arr(out.into()))442 }443 }444}445446#[jrsonnet_macros::builtin]447fn builtin_foldl(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {448 let mut acc = init.0;449 for i in arr.iter(s.clone()) {450 acc = func.evaluate_simple(s.clone(), &(Any(acc), Any(i?)))?;451 }452 Ok(Any(acc))453}454455#[jrsonnet_macros::builtin]456fn builtin_foldr(s: State, func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {457 let mut acc = init.0;458 for i in arr.iter(s.clone()).rev() {459 acc = func.evaluate_simple(s.clone(), &(Any(i?), Any(acc)))?;460 }461 Ok(Any(acc))462}463464#[jrsonnet_macros::builtin]465#[allow(non_snake_case)]466fn builtin_sort(s: State, arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {467 if arr.len() <= 1 {468 return Ok(arr);469 }470 Ok(ArrValue::Eager(sort::sort(471 s.clone(),472 arr.evaluated(s)?,473 keyF.unwrap_or_else(FuncVal::identity),474 )?))475}476477#[jrsonnet_macros::builtin]478fn builtin_format(s: State, str: IStr, vals: Any) -> Result<String> {479 std_format(s, str, vals.0)480}481482#[jrsonnet_macros::builtin]483fn builtin_range(from: i32, to: i32) -> Result<ArrValue> {484 if to < from {485 return Ok(ArrValue::new_eager());486 }487 Ok(ArrValue::new_range(from, to))488}489490#[jrsonnet_macros::builtin]491fn builtin_char(n: u32) -> Result<char> {492 Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)493}494495#[jrsonnet_macros::builtin]496fn builtin_encode_utf8(str: IStr) -> Result<IBytes> {497 Ok(str.cast_bytes())498}499500#[jrsonnet_macros::builtin]501fn builtin_decode_utf8(arr: IBytes) -> Result<IStr> {502 Ok(arr503 .cast_str()504 .ok_or_else(|| RuntimeError("bad utf8".into()))?)505}506507#[jrsonnet_macros::builtin]508fn builtin_md5(str: IStr) -> Result<String> {509 Ok(format!("{:x}", md5::compute(&str.as_bytes())))510}511512#[jrsonnet_macros::builtin]513fn builtin_trace(s: State, loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {514 eprint!("TRACE:");515 if let Some(loc) = loc.0 {516 let locs = s.map_source_locations(loc.0.clone(), &[loc.1]);517 eprint!(" {}:{}", loc.0.short_display(), locs[0].line);518 }519 eprintln!(" {}", str);520 Ok(rest) as Result<Any>521}522523#[jrsonnet_macros::builtin]524fn builtin_base64(input: Either![IBytes, IStr]) -> Result<String> {525 use Either2::*;526 Ok(match input {527 A(a) => base64::encode(a.as_slice()),528 B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),529 })530}531532#[jrsonnet_macros::builtin]533fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {534 Ok(base64::decode(&input.as_bytes())535 .map_err(|_| RuntimeError("bad base64".into()))?536 .as_slice()537 .into())538}539540#[jrsonnet_macros::builtin]541fn builtin_base64_decode(input: IStr) -> Result<String> {542 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;543 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)544}545546#[jrsonnet_macros::builtin]547fn builtin_join(s: State, sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {548 Ok(match sep {549 IndexableVal::Arr(joiner_items) => {550 let mut out = Vec::new();551552 let mut first = true;553 for item in arr.iter(s.clone()) {554 let item = item?.clone();555 if let Val::Arr(items) = item {556 if !first {557 out.reserve(joiner_items.len());558 // TODO: extend559 for item in joiner_items.iter(s.clone()) {560 out.push(item?);561 }562 }563 first = false;564 out.reserve(items.len());565 for item in items.iter(s.clone()) {566 out.push(item?);567 }568 } else if matches!(item, Val::Null) {569 continue;570 } else {571 throw!(RuntimeError(572 "in std.join all items should be arrays".into()573 ));574 }575 }576577 IndexableVal::Arr(out.into())578 }579 IndexableVal::Str(sep) => {580 let mut out = String::new();581582 let mut first = true;583 for item in arr.iter(s) {584 let item = item?.clone();585 if let Val::Str(item) = item {586 if !first {587 out += &sep;588 }589 first = false;590 out += &item;591 } else if matches!(item, Val::Null) {592 continue;593 } else {594 throw!(RuntimeError(595 "in std.join all items should be strings".into()596 ));597 }598 }599600 IndexableVal::Str(out.into())601 }602 })603}604605#[jrsonnet_macros::builtin]606fn builtin_escape_string_json(str_: IStr) -> Result<String> {607 Ok(escape_string_json(&str_))608}609610#[jrsonnet_macros::builtin]611fn builtin_manifest_json_ex(612 s: State,613 value: Any,614 indent: IStr,615 newline: Option<IStr>,616 key_val_sep: Option<IStr>,617 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,618) -> Result<String> {619 let newline = newline.as_deref().unwrap_or("\n");620 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");621 manifest_json_ex(622 s,623 &value.0,624 &ManifestJsonOptions {625 padding: &indent,626 mtype: ManifestType::Std,627 newline,628 key_val_sep,629 #[cfg(feature = "exp-preserve-order")]630 preserve_order: preserve_order.unwrap_or(false),631 },632 )633}634635#[jrsonnet_macros::builtin]636fn builtin_manifest_yaml_doc(637 s: State,638 value: Any,639 indent_array_in_object: Option<bool>,640 quote_keys: Option<bool>,641 #[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,642) -> Result<String> {643 manifest_yaml_ex(644 s,645 &value.0,646 &ManifestYamlOptions {647 padding: " ",648 arr_element_padding: if indent_array_in_object.unwrap_or(false) {649 " "650 } else {651 ""652 },653 quote_keys: quote_keys.unwrap_or(true),654 #[cfg(feature = "exp-preserve-order")]655 preserve_order: preserve_order.unwrap_or(false),656 },657 )658}659660#[jrsonnet_macros::builtin]661fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {662 Ok(value.reversed())663}664665#[jrsonnet_macros::builtin]666fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {667 Ok(str.replace(&from as &str, &to as &str))668}669670#[jrsonnet_macros::builtin]671fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {672 use Either2::*;673 Ok(VecVal(Cc::new(match maxsplits {674 A(n) => str675 .splitn(n + 1, &c as &str)676 .map(|s| Val::Str(s.into()))677 .collect(),678 B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),679 })))680}681682#[jrsonnet_macros::builtin]683fn builtin_ascii_upper(str: IStr) -> Result<String> {684 Ok(str.to_ascii_uppercase())685}686687#[jrsonnet_macros::builtin]688fn builtin_ascii_lower(str: IStr) -> Result<String> {689 Ok(str.to_ascii_lowercase())690}691692#[jrsonnet_macros::builtin]693fn builtin_member(s: State, arr: IndexableVal, x: Any) -> Result<bool> {694 match arr {695 IndexableVal::Str(str) => {696 let x: IStr = IStr::from_untyped(x.0, s)?;697 Ok(!x.is_empty() && str.contains(&*x))698 }699 IndexableVal::Arr(a) => {700 for item in a.iter(s.clone()) {701 let item = item?;702 if equals(s.clone(), &item, &x.0)? {703 return Ok(true);704 }705 }706 Ok(false)707 }708 }709}710711#[jrsonnet_macros::builtin]712fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {713 let mut count = 0;714 for item in &arr {715 if equals(s.clone(), &item.0, &v.0)? {716 count += 1;717 }718 }719 Ok(count)720}721722#[jrsonnet_macros::builtin]723fn builtin_any(s: State, arr: ArrValue) -> Result<bool> {724 for v in arr.iter(s.clone()) {725 let v = bool::from_untyped(v?, s.clone())?;726 if v {727 return Ok(true);728 }729 }730 Ok(false)731}732733#[jrsonnet_macros::builtin]734fn builtin_all(s: State, arr: ArrValue) -> Result<bool> {735 for v in arr.iter(s.clone()) {736 let v = bool::from_untyped(v?, s.clone())?;737 if !v {738 return Ok(false);739 }740 }741 Ok(true)742}74325crates/jrsonnet-evaluator/src/stdlib/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/sort.rs
+++ /dev/null
@@ -1,110 +0,0 @@
-use jrsonnet_gcmodule::{Cc, Trace};
-
-use crate::{
- error::{Error, LocError, Result},
- function::FuncVal,
- throw,
- typed::Any,
- State, Val,
-};
-
-#[derive(Debug, Clone, thiserror::Error, Trace)]
-pub enum SortError {
- #[error("sort key should be string or number")]
- SortKeyShouldBeStringOrNumber,
- #[error("sort elements should have equal types")]
- SortElementsShouldHaveEqualType,
-}
-
-impl From<SortError> for LocError {
- fn from(s: SortError) -> Self {
- Self::new(Error::Sort(s))
- }
-}
-
-#[derive(Copy, Clone)]
-enum SortKeyType {
- Number,
- String,
- Unknown,
-}
-
-#[derive(PartialEq)]
-struct NonNaNf64(f64);
-impl PartialOrd for NonNaNf64 {
- fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
- self.0.partial_cmp(&other.0)
- }
-}
-impl Eq for NonNaNf64 {}
-impl Ord for NonNaNf64 {
- fn cmp(&self, other: &Self) -> std::cmp::Ordering {
- self.partial_cmp(other).expect("non nan")
- }
-}
-
-fn get_sort_type<T>(
- values: &mut Vec<T>,
- key_getter: impl Fn(&mut T) -> &mut Val,
-) -> Result<SortKeyType> {
- let mut sort_type = SortKeyType::Unknown;
- for i in values.iter_mut() {
- let i = key_getter(i);
- match (i, sort_type) {
- (Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
- (Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
- (Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
- (Val::Str(_) | Val::Num(_), _) => {
- throw!(SortError::SortElementsShouldHaveEqualType)
- }
- _ => throw!(SortError::SortKeyShouldBeStringOrNumber),
- }
- }
- Ok(sort_type)
-}
-
-/// * `key_getter` - None, if identity sort required
-pub fn sort(s: State, values: Cc<Vec<Val>>, key_getter: FuncVal) -> Result<Cc<Vec<Val>>> {
- if values.len() <= 1 {
- return Ok(values);
- }
- if key_getter.is_identity() {
- // Fast path, identity key getter
- let mut values = (*values).clone();
- let sort_type = get_sort_type(&mut values, |k| k)?;
- match sort_type {
- SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
- Val::Num(n) => NonNaNf64(*n),
- _ => unreachable!(),
- }),
- SortKeyType::String => values.sort_unstable_by_key(|v| match v {
- Val::Str(s) => s.clone(),
- _ => unreachable!(),
- }),
- SortKeyType::Unknown => unreachable!(),
- };
- Ok(Cc::new(values))
- } else {
- // Slow path, user provided key getter
- let mut vk = Vec::with_capacity(values.len());
- for value in values.iter() {
- vk.push((
- value.clone(),
- key_getter.evaluate_simple(s.clone(), &(Any(value.clone()),))?,
- ));
- }
- let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;
- match sort_type {
- SortKeyType::Number => vk.sort_by_key(|v| match v.1 {
- Val::Num(n) => NonNaNf64(n),
- _ => unreachable!(),
- }),
- SortKeyType::String => vk.sort_by_key(|v| match &v.1 {
- Val::Str(s) => s.clone(),
- _ => unreachable!(),
- }),
- SortKeyType::Unknown => unreachable!(),
- };
- Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
- }
-}