difftreelog
Merge remote-tracking branch 'origin/feature/importbin' into gcmodule
in: master
11 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -2,7 +2,7 @@
use jrsonnet_evaluator::{
error::{Error::*, Result},
- throw, EvaluationState, IStr, ImportResolver,
+ throw, EvaluationState, ImportResolver,
};
use std::{
any::Any,
@@ -29,8 +29,7 @@
pub struct CallbackImportResolver {
cb: JsonnetImportCallback,
ctx: *mut c_void,
-
- out: RefCell<HashMap<PathBuf, IStr>>,
+ out: RefCell<HashMap<PathBuf, Vec<u8>>>,
}
impl ImportResolver for CallbackImportResolver {
fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
@@ -75,9 +74,10 @@
Ok(found_here_buf.into())
}
- fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
+ fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>> {
Ok(self.out.borrow().get(resolved).unwrap().clone())
}
+
unsafe fn as_any(&self) -> &dyn Any {
self
}
@@ -124,12 +124,12 @@
throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
}
}
- fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+ fn load_file_contents(&self, id: &Path) -> Result<Vec<u8>> {
let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
- let mut out = String::new();
- file.read_to_string(&mut out)
- .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
- Ok(out.into())
+ let mut out = Vec::new();
+ file.read_to_end(&mut out)
+ .map_err(|e| ImportIo(e.to_string()))?;
+ Ok(out)
}
unsafe fn as_any(&self) -> &dyn Any {
self
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth1use crate::function::{CallLocation, StaticBuiltin};2use crate::typed::{Any, PositiveF64, VecVal, M1};3use crate::{4 builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},5 equals,6 error::{Error::*, Result},7 operator::evaluate_mod_op,8 primitive_equals, push_frame, throw,9 typed::{Either2, Either4},10 with_state, ArrValue, FuncVal, IndexableVal, Val,11};12use crate::{Either, ObjValue};13use format::{format_arr, format_obj};14use jrsonnet_interner::IStr;15use serde::Deserialize;16use serde_yaml::DeserializingQuirks;17use std::collections::HashMap;18use std::convert::{TryFrom, TryInto};1920pub mod stdlib;21pub use stdlib::*;2223use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2425pub mod format;26pub mod manifest;27pub mod sort;2829pub fn std_format(str: IStr, vals: Val) -> Result<String> {30 push_frame(31 CallLocation::native(),32 || format!("std.format of {}", str),33 || {34 Ok(match vals {35 Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,36 Val::Obj(obj) => format_obj(&str, &obj)?,37 o => format_arr(&str, &[o])?,38 })39 },40 )41}4243pub fn std_slice(44 indexable: IndexableVal,45 index: Option<usize>,46 end: Option<usize>,47 step: Option<usize>,48) -> Result<Val> {49 let index = index.unwrap_or(0);50 let end = end.unwrap_or_else(|| match &indexable {51 IndexableVal::Str(_) => usize::MAX,52 IndexableVal::Arr(v) => v.len(),53 });54 let step = step.unwrap_or(1);55 match &indexable {56 IndexableVal::Str(s) => Ok(Val::Str(57 (s.chars()58 .skip(index)59 .take(end - index)60 .step_by(step)61 .collect::<String>())62 .into(),63 )),64 IndexableVal::Arr(arr) => Ok(Val::Arr(65 (arr.iter()66 .skip(index)67 .take(end - index)68 .step_by(step)69 .collect::<Result<Vec<Val>>>()?)70 .into(),71 )),72 }73}7475type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;7677thread_local! {78 pub static BUILTINS: BuiltinsType = {79 [80 ("length".into(), builtin_length::INST),81 ("type".into(), builtin_type::INST),82 ("makeArray".into(), builtin_make_array::INST),83 ("codepoint".into(), builtin_codepoint::INST),84 ("objectFieldsEx".into(), builtin_object_fields_ex::INST),85 ("objectHasEx".into(), builtin_object_has_ex::INST),86 ("slice".into(), builtin_slice::INST),87 ("substr".into(), builtin_substr::INST),88 ("primitiveEquals".into(), builtin_primitive_equals::INST),89 ("equals".into(), builtin_equals::INST),90 ("modulo".into(), builtin_modulo::INST),91 ("mod".into(), builtin_mod::INST),92 ("floor".into(), builtin_floor::INST),93 ("ceil".into(), builtin_ceil::INST),94 ("log".into(), builtin_log::INST),95 ("pow".into(), builtin_pow::INST),96 ("sqrt".into(), builtin_sqrt::INST),97 ("sin".into(), builtin_sin::INST),98 ("cos".into(), builtin_cos::INST),99 ("tan".into(), builtin_tan::INST),100 ("asin".into(), builtin_asin::INST),101 ("acos".into(), builtin_acos::INST),102 ("atan".into(), builtin_atan::INST),103 ("exp".into(), builtin_exp::INST),104 ("mantissa".into(), builtin_mantissa::INST),105 ("exponent".into(), builtin_exponent::INST),106 ("extVar".into(), builtin_ext_var::INST),107 ("native".into(), builtin_native::INST),108 ("filter".into(), builtin_filter::INST),109 ("map".into(), builtin_map::INST),110 ("flatMap".into(), builtin_flatmap::INST),111 ("foldl".into(), builtin_foldl::INST),112 ("foldr".into(), builtin_foldr::INST),113 ("sort".into(), builtin_sort::INST),114 ("format".into(), builtin_format::INST),115 ("range".into(), builtin_range::INST),116 ("char".into(), builtin_char::INST),117 ("encodeUTF8".into(), builtin_encode_utf8::INST),118 ("decodeUTF8".into(), builtin_decode_utf8::INST),119 ("md5".into(), builtin_md5::INST),120 ("base64".into(), builtin_base64::INST),121 ("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),122 ("base64Decode".into(), builtin_base64_decode::INST),123 ("trace".into(), builtin_trace::INST),124 ("join".into(), builtin_join::INST),125 ("escapeStringJson".into(), builtin_escape_string_json::INST),126 ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),127 ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),128 ("reverse".into(), builtin_reverse::INST),129 ("id".into(), builtin_id::INST),130 ("strReplace".into(), builtin_str_replace::INST),131 ("splitLimit".into(), builtin_splitlimit::INST),132 ("parseJson".into(), builtin_parse_json::INST),133 ("parseYaml".into(), builtin_parse_yaml::INST),134 ("asciiUpper".into(), builtin_ascii_upper::INST),135 ("asciiLower".into(), builtin_ascii_lower::INST),136 ("member".into(), builtin_member::INST),137 ("count".into(), builtin_count::INST),138 ].iter().cloned().collect()139 };140}141142#[jrsonnet_macros::builtin]143fn builtin_length(x: Either![IStr, VecVal, ObjValue, FuncVal]) -> Result<usize> {144 use Either4::*;145 Ok(match x {146 A(x) => x.chars().count(),147 B(x) => x.0.len(),148 C(x) => x149 .fields_visibility()150 .into_iter()151 .filter(|(_k, v)| *v)152 .count(),153 D(f) => f.args_len(),154 })155}156157#[jrsonnet_macros::builtin]158fn builtin_type(x: Any) -> Result<IStr> {159 Ok(x.0.value_type().name().into())160}161162#[jrsonnet_macros::builtin]163fn builtin_make_array(sz: usize, func: FuncVal) -> Result<VecVal> {164 let mut out = Vec::with_capacity(sz);165 for i in 0..sz {166 out.push(func.evaluate_simple(&[i as f64].as_slice())?)167 }168 Ok(VecVal(out))169}170171#[jrsonnet_macros::builtin]172const fn builtin_codepoint(str: char) -> Result<u32> {173 Ok(str as u32)174}175176#[jrsonnet_macros::builtin]177fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {178 let out = obj.fields_ex(inc_hidden);179 Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))180}181182#[jrsonnet_macros::builtin]183fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {184 Ok(obj.has_field_ex(f, inc_hidden))185}186187#[jrsonnet_macros::builtin]188fn builtin_parse_json(s: IStr) -> Result<Any> {189 let value: serde_json::Value = serde_json::from_str(&s)190 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;191 Ok(Any(Val::try_from(&value)?))192}193194#[jrsonnet_macros::builtin]195fn builtin_parse_yaml(s: IStr) -> Result<Any> {196 let value = serde_yaml::Deserializer::from_str_with_quirks(197 &s,198 DeserializingQuirks { old_octals: true },199 );200 let mut out = vec![];201 for item in value {202 let value = serde_json::Value::deserialize(item)203 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;204 let val = Val::try_from(&value)?;205 out.push(val);206 }207 Ok(Any(if out.is_empty() {208 Val::Null209 } else if out.len() == 1 {210 out.into_iter().next().unwrap()211 } else {212 Val::Arr(out.into())213 }))214}215216#[jrsonnet_macros::builtin]217fn builtin_slice(218 indexable: IndexableVal,219 index: Option<usize>,220 end: Option<usize>,221 step: Option<usize>,222) -> Result<Any> {223 std_slice(indexable, index, end, step).map(Any)224}225226#[jrsonnet_macros::builtin]227fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {228 Ok(str.chars().skip(from as usize).take(len as usize).collect())229}230231#[jrsonnet_macros::builtin]232fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {233 primitive_equals(&a.0, &b.0)234}235236#[jrsonnet_macros::builtin]237fn builtin_equals(a: Any, b: Any) -> Result<bool> {238 equals(&a.0, &b.0)239}240241#[jrsonnet_macros::builtin]242fn builtin_modulo(a: f64, b: f64) -> Result<f64> {243 Ok(a % b)244}245246#[jrsonnet_macros::builtin]247fn builtin_mod(a: Either![f64, IStr], b: Any) -> Result<Any> {248 use Either2::*;249 Ok(Any(evaluate_mod_op(250 &match a {251 A(v) => Val::Num(v),252 B(s) => Val::Str(s),253 },254 &b.0,255 )?))256}257258#[jrsonnet_macros::builtin]259fn builtin_floor(x: f64) -> Result<f64> {260 Ok(x.floor())261}262263#[jrsonnet_macros::builtin]264fn builtin_ceil(x: f64) -> Result<f64> {265 Ok(x.ceil())266}267268#[jrsonnet_macros::builtin]269fn builtin_log(n: f64) -> Result<f64> {270 Ok(n.ln())271}272273#[jrsonnet_macros::builtin]274fn builtin_pow(x: f64, n: f64) -> Result<f64> {275 Ok(x.powf(n))276}277278#[jrsonnet_macros::builtin]279fn builtin_sqrt(x: PositiveF64) -> Result<f64> {280 Ok(x.0.sqrt())281}282283#[jrsonnet_macros::builtin]284fn builtin_sin(x: f64) -> Result<f64> {285 Ok(x.sin())286}287288#[jrsonnet_macros::builtin]289fn builtin_cos(x: f64) -> Result<f64> {290 Ok(x.cos())291}292293#[jrsonnet_macros::builtin]294fn builtin_tan(x: f64) -> Result<f64> {295 Ok(x.tan())296}297298#[jrsonnet_macros::builtin]299fn builtin_asin(x: f64) -> Result<f64> {300 Ok(x.asin())301}302303#[jrsonnet_macros::builtin]304fn builtin_acos(x: f64) -> Result<f64> {305 Ok(x.acos())306}307308#[jrsonnet_macros::builtin]309fn builtin_atan(x: f64) -> Result<f64> {310 Ok(x.atan())311}312313#[jrsonnet_macros::builtin]314fn builtin_exp(x: f64) -> Result<f64> {315 Ok(x.exp())316}317318fn frexp(s: f64) -> (f64, i16) {319 if 0.0 == s {320 (s, 0)321 } else {322 let lg = s.abs().log2();323 let x = (lg - lg.floor() - 1.0).exp2();324 let exp = lg.floor() + 1.0;325 (s.signum() * x, exp as i16)326 }327}328329#[jrsonnet_macros::builtin]330fn builtin_mantissa(x: f64) -> Result<f64> {331 Ok(frexp(x).0)332}333334#[jrsonnet_macros::builtin]335fn builtin_exponent(x: f64) -> Result<i16> {336 Ok(frexp(x).1)337}338339#[jrsonnet_macros::builtin]340fn builtin_ext_var(x: IStr) -> Result<Any> {341 Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())342 .ok_or(UndefinedExternalVariable(x))?))343}344345#[jrsonnet_macros::builtin]346fn builtin_native(name: IStr) -> Result<FuncVal> {347 Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())348 .map(|v| FuncVal::Builtin(v.clone()))349 .ok_or(UndefinedExternalFunction(name))?)350}351352#[jrsonnet_macros::builtin]353fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {354 arr.filter(|val| bool::try_from(func.evaluate_simple(&[Any(val.clone())].as_slice())?))355}356357#[jrsonnet_macros::builtin]358fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {359 arr.map(|val| func.evaluate_simple(&[Any(val)].as_slice()))360}361362#[jrsonnet_macros::builtin]363fn builtin_flatmap(func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {364 match arr {365 IndexableVal::Str(s) => {366 let mut out = String::new();367 for c in s.chars() {368 match func.evaluate_simple(&[c.to_string()].as_slice())? {369 Val::Str(o) => out.push_str(&o),370 _ => throw!(RuntimeError(371 "in std.join all items should be strings".into()372 )),373 };374 }375 Ok(IndexableVal::Str(out.into()))376 }377 IndexableVal::Arr(a) => {378 let mut out = Vec::new();379 for el in a.iter() {380 let el = el?;381 match func.evaluate_simple(&[Any(el)].as_slice())? {382 Val::Arr(o) => {383 for oe in o.iter() {384 out.push(oe?)385 }386 }387 _ => throw!(RuntimeError(388 "in std.join all items should be arrays".into()389 )),390 };391 }392 Ok(IndexableVal::Arr(out.into()))393 }394 }395}396397#[jrsonnet_macros::builtin]398fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {399 let mut acc = init.0;400 for i in arr.iter() {401 acc = func.evaluate_simple(&[Any(acc), Any(i?)].as_slice())?;402 }403 Ok(Any(acc))404}405406#[jrsonnet_macros::builtin]407fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {408 let mut acc = init.0;409 for i in arr.iter().rev() {410 acc = func.evaluate_simple(&[Any(i?), Any(acc)].as_slice())?;411 }412 Ok(Any(acc))413}414415#[jrsonnet_macros::builtin]416#[allow(non_snake_case)]417fn builtin_sort(arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {418 if arr.len() <= 1 {419 return Ok(arr);420 }421 Ok(ArrValue::Eager(sort::sort(422 arr.evaluated()?,423 keyF.as_ref(),424 )?))425}426427#[jrsonnet_macros::builtin]428fn builtin_format(str: IStr, vals: Any) -> Result<String> {429 std_format(str, vals.0)430}431432#[jrsonnet_macros::builtin]433fn builtin_range(from: i32, to: i32) -> Result<VecVal> {434 if to < from {435 return Ok(VecVal(Vec::new()));436 }437 let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));438 for i in from as usize..=to as usize {439 out.push(Val::Num(i as f64));440 }441 Ok(VecVal(out))442}443444#[jrsonnet_macros::builtin]445fn builtin_char(n: u32) -> Result<char> {446 Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)447}448449#[jrsonnet_macros::builtin]450fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {451 Ok(VecVal(452 str.bytes()453 .map(|b| Val::Num(b as f64))454 .collect::<Vec<Val>>(),455 ))456}457458#[jrsonnet_macros::builtin]459fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {460 Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)461}462463#[jrsonnet_macros::builtin]464fn builtin_md5(str: IStr) -> Result<String> {465 Ok(format!("{:x}", md5::compute(&str.as_bytes())))466}467468#[jrsonnet_macros::builtin]469fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {470 eprint!("TRACE:");471 if let Some(loc) = loc.0 {472 with_state(|s| {473 let locs = s.map_source_locations(&loc.0, &[loc.1]);474 eprint!(475 " {}:{}",476 loc.0.file_name().unwrap().to_str().unwrap(),477 locs[0].line478 );479 });480 }481 eprintln!(" {}", str);482 Ok(rest) as Result<Any>483}484485#[jrsonnet_macros::builtin]486fn builtin_base64(input: Either![Vec<u8>, IStr]) -> Result<String> {487 use Either2::*;488 Ok(match input {489 A(a) => base64::encode(a),490 B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),491 })492}493494#[jrsonnet_macros::builtin]495fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {496 Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)497}498499#[jrsonnet_macros::builtin]500fn builtin_base64_decode(input: IStr) -> Result<String> {501 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;502 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)503}504505#[jrsonnet_macros::builtin]506fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {507 Ok(match sep {508 IndexableVal::Arr(joiner_items) => {509 let mut out = Vec::new();510511 let mut first = true;512 for item in arr.iter() {513 let item = item?.clone();514 if let Val::Arr(items) = item {515 if !first {516 out.reserve(joiner_items.len());517 // TODO: extend518 for item in joiner_items.iter() {519 out.push(item?);520 }521 }522 first = false;523 out.reserve(items.len());524 // TODO: extend525 for item in items.iter() {526 out.push(item?);527 }528 } else {529 throw!(RuntimeError(530 "in std.join all items should be arrays".into()531 ));532 }533 }534535 IndexableVal::Arr(out.into())536 }537 IndexableVal::Str(sep) => {538 let mut out = String::new();539540 let mut first = true;541 for item in arr.iter() {542 let item = item?.clone();543 if let Val::Str(item) = item {544 if !first {545 out += &sep;546 }547 first = false;548 out += &item;549 } else {550 throw!(RuntimeError(551 "in std.join all items should be strings".into()552 ));553 }554 }555556 IndexableVal::Str(out.into())557 }558 })559}560561#[jrsonnet_macros::builtin]562fn builtin_escape_string_json(str_: IStr) -> Result<String> {563 Ok(escape_string_json(&str_))564}565566#[jrsonnet_macros::builtin]567fn builtin_manifest_json_ex(568 value: Any,569 indent: IStr,570 newline: Option<IStr>,571 key_val_sep: Option<IStr>,572) -> Result<String> {573 let newline = newline.as_deref().unwrap_or("\n");574 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");575 manifest_json_ex(576 &value.0,577 &ManifestJsonOptions {578 padding: &indent,579 mtype: ManifestType::Std,580 newline,581 key_val_sep,582 },583 )584}585586#[jrsonnet_macros::builtin]587fn builtin_manifest_yaml_doc(588 value: Any,589 indent_array_in_object: Option<bool>,590 quote_keys: Option<bool>,591) -> Result<String> {592 manifest_yaml_ex(593 &value.0,594 &ManifestYamlOptions {595 padding: " ",596 arr_element_padding: if indent_array_in_object.unwrap_or(false) {597 " "598 } else {599 ""600 },601 quote_keys: quote_keys.unwrap_or(true),602 },603 )604}605606#[jrsonnet_macros::builtin]607fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {608 Ok(value.reversed())609}610611#[jrsonnet_macros::builtin]612const fn builtin_id(v: Any) -> Result<Any> {613 Ok(v)614}615616#[jrsonnet_macros::builtin]617fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {618 Ok(str.replace(&from as &str, &to as &str))619}620621#[jrsonnet_macros::builtin]622fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either![usize, M1]) -> Result<VecVal> {623 use Either2::*;624 Ok(VecVal(match maxsplits {625 A(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),626 B(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),627 }))628}629630#[jrsonnet_macros::builtin]631fn builtin_ascii_upper(str: IStr) -> Result<String> {632 Ok(str.to_ascii_uppercase())633}634635#[jrsonnet_macros::builtin]636fn builtin_ascii_lower(str: IStr) -> Result<String> {637 Ok(str.to_ascii_lowercase())638}639640#[jrsonnet_macros::builtin]641fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {642 match arr {643 IndexableVal::Str(s) => {644 let x: IStr = IStr::try_from(x.0)?;645 Ok(!x.is_empty() && s.contains(&*x))646 }647 IndexableVal::Arr(a) => {648 for item in a.iter() {649 let item = item?;650 if equals(&item, &x.0)? {651 return Ok(true);652 }653 }654 Ok(false)655 }656 }657}658659#[jrsonnet_macros::builtin]660fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {661 let mut count = 0;662 for item in arr.iter() {663 if equals(&item.0, &v.0)? {664 count += 1;665 }666 }667 Ok(count)668}1use crate::function::{CallLocation, StaticBuiltin};2use crate::typed::{Any, Bytes, PositiveF64, VecVal, M1};3use crate::{4 builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},5 equals,6 error::{Error::*, Result},7 operator::evaluate_mod_op,8 primitive_equals, push_frame, throw,9 typed::{Either2, Either4},10 with_state, ArrValue, FuncVal, IndexableVal, Val,11};12use crate::{Either, ObjValue};13use format::{format_arr, format_obj};14use jrsonnet_interner::IStr;15use serde::Deserialize;16use serde_yaml::DeserializingQuirks;17use std::collections::HashMap;18use std::convert::{TryFrom, TryInto};1920pub mod stdlib;21pub use stdlib::*;2223use self::manifest::{escape_string_json, manifest_json_ex, ManifestJsonOptions, ManifestType};2425pub mod format;26pub mod manifest;27pub mod sort;2829pub fn std_format(str: IStr, vals: Val) -> Result<String> {30 push_frame(31 CallLocation::native(),32 || format!("std.format of {}", str),33 || {34 Ok(match vals {35 Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,36 Val::Obj(obj) => format_obj(&str, &obj)?,37 o => format_arr(&str, &[o])?,38 })39 },40 )41}4243pub fn std_slice(44 indexable: IndexableVal,45 index: Option<usize>,46 end: Option<usize>,47 step: Option<usize>,48) -> Result<Val> {49 let index = index.unwrap_or(0);50 let end = end.unwrap_or_else(|| match &indexable {51 IndexableVal::Str(_) => usize::MAX,52 IndexableVal::Arr(v) => v.len(),53 });54 let step = step.unwrap_or(1);55 match &indexable {56 IndexableVal::Str(s) => Ok(Val::Str(57 (s.chars()58 .skip(index)59 .take(end - index)60 .step_by(step)61 .collect::<String>())62 .into(),63 )),64 IndexableVal::Arr(arr) => Ok(Val::Arr(65 (arr.iter()66 .skip(index)67 .take(end - index)68 .step_by(step)69 .collect::<Result<Vec<Val>>>()?)70 .into(),71 )),72 }73}7475type BuiltinsType = HashMap<IStr, &'static dyn StaticBuiltin>;7677thread_local! {78 pub static BUILTINS: BuiltinsType = {79 [80 ("length".into(), builtin_length::INST),81 ("type".into(), builtin_type::INST),82 ("makeArray".into(), builtin_make_array::INST),83 ("codepoint".into(), builtin_codepoint::INST),84 ("objectFieldsEx".into(), builtin_object_fields_ex::INST),85 ("objectHasEx".into(), builtin_object_has_ex::INST),86 ("slice".into(), builtin_slice::INST),87 ("substr".into(), builtin_substr::INST),88 ("primitiveEquals".into(), builtin_primitive_equals::INST),89 ("equals".into(), builtin_equals::INST),90 ("modulo".into(), builtin_modulo::INST),91 ("mod".into(), builtin_mod::INST),92 ("floor".into(), builtin_floor::INST),93 ("ceil".into(), builtin_ceil::INST),94 ("log".into(), builtin_log::INST),95 ("pow".into(), builtin_pow::INST),96 ("sqrt".into(), builtin_sqrt::INST),97 ("sin".into(), builtin_sin::INST),98 ("cos".into(), builtin_cos::INST),99 ("tan".into(), builtin_tan::INST),100 ("asin".into(), builtin_asin::INST),101 ("acos".into(), builtin_acos::INST),102 ("atan".into(), builtin_atan::INST),103 ("exp".into(), builtin_exp::INST),104 ("mantissa".into(), builtin_mantissa::INST),105 ("exponent".into(), builtin_exponent::INST),106 ("extVar".into(), builtin_ext_var::INST),107 ("native".into(), builtin_native::INST),108 ("filter".into(), builtin_filter::INST),109 ("map".into(), builtin_map::INST),110 ("flatMap".into(), builtin_flatmap::INST),111 ("foldl".into(), builtin_foldl::INST),112 ("foldr".into(), builtin_foldr::INST),113 ("sort".into(), builtin_sort::INST),114 ("format".into(), builtin_format::INST),115 ("range".into(), builtin_range::INST),116 ("char".into(), builtin_char::INST),117 ("encodeUTF8".into(), builtin_encode_utf8::INST),118 ("decodeUTF8".into(), builtin_decode_utf8::INST),119 ("md5".into(), builtin_md5::INST),120 ("base64".into(), builtin_base64::INST),121 ("base64DecodeBytes".into(), builtin_base64_decode_bytes::INST),122 ("base64Decode".into(), builtin_base64_decode::INST),123 ("trace".into(), builtin_trace::INST),124 ("join".into(), builtin_join::INST),125 ("escapeStringJson".into(), builtin_escape_string_json::INST),126 ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),127 ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),128 ("reverse".into(), builtin_reverse::INST),129 ("id".into(), builtin_id::INST),130 ("strReplace".into(), builtin_str_replace::INST),131 ("splitLimit".into(), builtin_splitlimit::INST),132 ("parseJson".into(), builtin_parse_json::INST),133 ("parseYaml".into(), builtin_parse_yaml::INST),134 ("asciiUpper".into(), builtin_ascii_upper::INST),135 ("asciiLower".into(), builtin_ascii_lower::INST),136 ("member".into(), builtin_member::INST),137 ("count".into(), builtin_count::INST),138 ].iter().cloned().collect()139 };140}141142#[jrsonnet_macros::builtin]143fn builtin_length(x: Either![IStr, VecVal, ObjValue, FuncVal]) -> Result<usize> {144 use Either4::*;145 Ok(match x {146 A(x) => x.chars().count(),147 B(x) => x.0.len(),148 C(x) => x149 .fields_visibility()150 .into_iter()151 .filter(|(_k, v)| *v)152 .count(),153 D(f) => f.args_len(),154 })155}156157#[jrsonnet_macros::builtin]158fn builtin_type(x: Any) -> Result<IStr> {159 Ok(x.0.value_type().name().into())160}161162#[jrsonnet_macros::builtin]163fn builtin_make_array(sz: usize, func: FuncVal) -> Result<VecVal> {164 let mut out = Vec::with_capacity(sz);165 for i in 0..sz {166 out.push(func.evaluate_simple(&[i as f64].as_slice())?)167 }168 Ok(VecVal(out))169}170171#[jrsonnet_macros::builtin]172const fn builtin_codepoint(str: char) -> Result<u32> {173 Ok(str as u32)174}175176#[jrsonnet_macros::builtin]177fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {178 let out = obj.fields_ex(inc_hidden);179 Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))180}181182#[jrsonnet_macros::builtin]183fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {184 Ok(obj.has_field_ex(f, inc_hidden))185}186187#[jrsonnet_macros::builtin]188fn builtin_parse_json(s: IStr) -> Result<Any> {189 let value: serde_json::Value = serde_json::from_str(&s)190 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;191 Ok(Any(Val::try_from(&value)?))192}193194#[jrsonnet_macros::builtin]195fn builtin_parse_yaml(s: IStr) -> Result<Any> {196 let value = serde_yaml::Deserializer::from_str_with_quirks(197 &s,198 DeserializingQuirks { old_octals: true },199 );200 let mut out = vec![];201 for item in value {202 let value = serde_json::Value::deserialize(item)203 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;204 let val = Val::try_from(&value)?;205 out.push(val);206 }207 Ok(Any(if out.is_empty() {208 Val::Null209 } else if out.len() == 1 {210 out.into_iter().next().unwrap()211 } else {212 Val::Arr(out.into())213 }))214}215216#[jrsonnet_macros::builtin]217fn builtin_slice(218 indexable: IndexableVal,219 index: Option<usize>,220 end: Option<usize>,221 step: Option<usize>,222) -> Result<Any> {223 std_slice(indexable, index, end, step).map(Any)224}225226#[jrsonnet_macros::builtin]227fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {228 Ok(str.chars().skip(from as usize).take(len as usize).collect())229}230231#[jrsonnet_macros::builtin]232fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {233 primitive_equals(&a.0, &b.0)234}235236#[jrsonnet_macros::builtin]237fn builtin_equals(a: Any, b: Any) -> Result<bool> {238 equals(&a.0, &b.0)239}240241#[jrsonnet_macros::builtin]242fn builtin_modulo(a: f64, b: f64) -> Result<f64> {243 Ok(a % b)244}245246#[jrsonnet_macros::builtin]247fn builtin_mod(a: Either![f64, IStr], b: Any) -> Result<Any> {248 use Either2::*;249 Ok(Any(evaluate_mod_op(250 &match a {251 A(v) => Val::Num(v),252 B(s) => Val::Str(s),253 },254 &b.0,255 )?))256}257258#[jrsonnet_macros::builtin]259fn builtin_floor(x: f64) -> Result<f64> {260 Ok(x.floor())261}262263#[jrsonnet_macros::builtin]264fn builtin_ceil(x: f64) -> Result<f64> {265 Ok(x.ceil())266}267268#[jrsonnet_macros::builtin]269fn builtin_log(n: f64) -> Result<f64> {270 Ok(n.ln())271}272273#[jrsonnet_macros::builtin]274fn builtin_pow(x: f64, n: f64) -> Result<f64> {275 Ok(x.powf(n))276}277278#[jrsonnet_macros::builtin]279fn builtin_sqrt(x: PositiveF64) -> Result<f64> {280 Ok(x.0.sqrt())281}282283#[jrsonnet_macros::builtin]284fn builtin_sin(x: f64) -> Result<f64> {285 Ok(x.sin())286}287288#[jrsonnet_macros::builtin]289fn builtin_cos(x: f64) -> Result<f64> {290 Ok(x.cos())291}292293#[jrsonnet_macros::builtin]294fn builtin_tan(x: f64) -> Result<f64> {295 Ok(x.tan())296}297298#[jrsonnet_macros::builtin]299fn builtin_asin(x: f64) -> Result<f64> {300 Ok(x.asin())301}302303#[jrsonnet_macros::builtin]304fn builtin_acos(x: f64) -> Result<f64> {305 Ok(x.acos())306}307308#[jrsonnet_macros::builtin]309fn builtin_atan(x: f64) -> Result<f64> {310 Ok(x.atan())311}312313#[jrsonnet_macros::builtin]314fn builtin_exp(x: f64) -> Result<f64> {315 Ok(x.exp())316}317318fn frexp(s: f64) -> (f64, i16) {319 if 0.0 == s {320 (s, 0)321 } else {322 let lg = s.abs().log2();323 let x = (lg - lg.floor() - 1.0).exp2();324 let exp = lg.floor() + 1.0;325 (s.signum() * x, exp as i16)326 }327}328329#[jrsonnet_macros::builtin]330fn builtin_mantissa(x: f64) -> Result<f64> {331 Ok(frexp(x).0)332}333334#[jrsonnet_macros::builtin]335fn builtin_exponent(x: f64) -> Result<i16> {336 Ok(frexp(x).1)337}338339#[jrsonnet_macros::builtin]340fn builtin_ext_var(x: IStr) -> Result<Any> {341 Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())342 .ok_or(UndefinedExternalVariable(x))?))343}344345#[jrsonnet_macros::builtin]346fn builtin_native(name: IStr) -> Result<FuncVal> {347 Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())348 .map(|v| FuncVal::Builtin(v.clone()))349 .ok_or(UndefinedExternalFunction(name))?)350}351352#[jrsonnet_macros::builtin]353fn builtin_filter(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {354 arr.filter(|val| bool::try_from(func.evaluate_simple(&[Any(val.clone())].as_slice())?))355}356357#[jrsonnet_macros::builtin]358fn builtin_map(func: FuncVal, arr: ArrValue) -> Result<ArrValue> {359 arr.map(|val| func.evaluate_simple(&[Any(val)].as_slice()))360}361362#[jrsonnet_macros::builtin]363fn builtin_flatmap(func: FuncVal, arr: IndexableVal) -> Result<IndexableVal> {364 match arr {365 IndexableVal::Str(s) => {366 let mut out = String::new();367 for c in s.chars() {368 match func.evaluate_simple(&[c.to_string()].as_slice())? {369 Val::Str(o) => out.push_str(&o),370 _ => throw!(RuntimeError(371 "in std.join all items should be strings".into()372 )),373 };374 }375 Ok(IndexableVal::Str(out.into()))376 }377 IndexableVal::Arr(a) => {378 let mut out = Vec::new();379 for el in a.iter() {380 let el = el?;381 match func.evaluate_simple(&[Any(el)].as_slice())? {382 Val::Arr(o) => {383 for oe in o.iter() {384 out.push(oe?)385 }386 }387 _ => throw!(RuntimeError(388 "in std.join all items should be arrays".into()389 )),390 };391 }392 Ok(IndexableVal::Arr(out.into()))393 }394 }395}396397#[jrsonnet_macros::builtin]398fn builtin_foldl(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {399 let mut acc = init.0;400 for i in arr.iter() {401 acc = func.evaluate_simple(&[Any(acc), Any(i?)].as_slice())?;402 }403 Ok(Any(acc))404}405406#[jrsonnet_macros::builtin]407fn builtin_foldr(func: FuncVal, arr: ArrValue, init: Any) -> Result<Any> {408 let mut acc = init.0;409 for i in arr.iter().rev() {410 acc = func.evaluate_simple(&[Any(i?), Any(acc)].as_slice())?;411 }412 Ok(Any(acc))413}414415#[jrsonnet_macros::builtin]416#[allow(non_snake_case)]417fn builtin_sort(arr: ArrValue, keyF: Option<FuncVal>) -> Result<ArrValue> {418 if arr.len() <= 1 {419 return Ok(arr);420 }421 Ok(ArrValue::Eager(sort::sort(422 arr.evaluated()?,423 keyF.as_ref(),424 )?))425}426427#[jrsonnet_macros::builtin]428fn builtin_format(str: IStr, vals: Any) -> Result<String> {429 std_format(str, vals.0)430}431432#[jrsonnet_macros::builtin]433fn builtin_range(from: i32, to: i32) -> Result<VecVal> {434 if to < from {435 return Ok(VecVal(Vec::new()));436 }437 let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));438 for i in from as usize..=to as usize {439 out.push(Val::Num(i as f64));440 }441 Ok(VecVal(out))442}443444#[jrsonnet_macros::builtin]445fn builtin_char(n: u32) -> Result<char> {446 Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)447}448449#[jrsonnet_macros::builtin]450fn builtin_encode_utf8(str: IStr) -> Result<Bytes> {451 Ok(Bytes(str.bytes().map(|b| b).collect::<Vec<u8>>().into()))452}453454#[jrsonnet_macros::builtin]455fn builtin_decode_utf8(arr: Bytes) -> Result<IStr> {456 Ok(std::str::from_utf8(&arr.0)457 .map_err(|_| RuntimeError("bad utf8".into()))?458 .into())459}460461#[jrsonnet_macros::builtin]462fn builtin_md5(str: IStr) -> Result<String> {463 Ok(format!("{:x}", md5::compute(&str.as_bytes())))464}465466#[jrsonnet_macros::builtin]467fn builtin_trace(loc: CallLocation, str: IStr, rest: Any) -> Result<Any> {468 eprint!("TRACE:");469 if let Some(loc) = loc.0 {470 with_state(|s| {471 let locs = s.map_source_locations(&loc.0, &[loc.1]);472 eprint!(473 " {}:{}",474 loc.0.file_name().unwrap().to_str().unwrap(),475 locs[0].line476 );477 });478 }479 eprintln!(" {}", str);480 Ok(rest) as Result<Any>481}482483#[jrsonnet_macros::builtin]484fn builtin_base64(input: Either![Bytes, IStr]) -> Result<String> {485 use Either2::*;486 Ok(match input {487 A(a) => base64::encode(a.0),488 B(l) => base64::encode(l.bytes().collect::<Vec<_>>()),489 })490}491492#[jrsonnet_macros::builtin]493fn builtin_base64_decode_bytes(input: IStr) -> Result<Bytes> {494 Ok(Bytes(495 base64::decode(&input.as_bytes())496 .map_err(|_| RuntimeError("bad base64".into()))?497 .into(),498 ))499}500501#[jrsonnet_macros::builtin]502fn builtin_base64_decode(input: IStr) -> Result<String> {503 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;504 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)505}506507#[jrsonnet_macros::builtin]508fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {509 Ok(match sep {510 IndexableVal::Arr(joiner_items) => {511 let mut out = Vec::new();512513 let mut first = true;514 for item in arr.iter() {515 let item = item?.clone();516 if let Val::Arr(items) = item {517 if !first {518 out.reserve(joiner_items.len());519 // TODO: extend520 for item in joiner_items.iter() {521 out.push(item?);522 }523 }524 first = false;525 out.reserve(items.len());526 // TODO: extend527 for item in items.iter() {528 out.push(item?);529 }530 } else {531 throw!(RuntimeError(532 "in std.join all items should be arrays".into()533 ));534 }535 }536537 IndexableVal::Arr(out.into())538 }539 IndexableVal::Str(sep) => {540 let mut out = String::new();541542 let mut first = true;543 for item in arr.iter() {544 let item = item?.clone();545 if let Val::Str(item) = item {546 if !first {547 out += &sep;548 }549 first = false;550 out += &item;551 } else {552 throw!(RuntimeError(553 "in std.join all items should be strings".into()554 ));555 }556 }557558 IndexableVal::Str(out.into())559 }560 })561}562563#[jrsonnet_macros::builtin]564fn builtin_escape_string_json(str_: IStr) -> Result<String> {565 Ok(escape_string_json(&str_))566}567568#[jrsonnet_macros::builtin]569fn builtin_manifest_json_ex(570 value: Any,571 indent: IStr,572 newline: Option<IStr>,573 key_val_sep: Option<IStr>,574) -> Result<String> {575 let newline = newline.as_deref().unwrap_or("\n");576 let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");577 manifest_json_ex(578 &value.0,579 &ManifestJsonOptions {580 padding: &indent,581 mtype: ManifestType::Std,582 newline,583 key_val_sep,584 },585 )586}587588#[jrsonnet_macros::builtin]589fn builtin_manifest_yaml_doc(590 value: Any,591 indent_array_in_object: Option<bool>,592 quote_keys: Option<bool>,593) -> Result<String> {594 manifest_yaml_ex(595 &value.0,596 &ManifestYamlOptions {597 padding: " ",598 arr_element_padding: if indent_array_in_object.unwrap_or(false) {599 " "600 } else {601 ""602 },603 quote_keys: quote_keys.unwrap_or(true),604 },605 )606}607608#[jrsonnet_macros::builtin]609fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {610 Ok(value.reversed())611}612613#[jrsonnet_macros::builtin]614const fn builtin_id(v: Any) -> Result<Any> {615 Ok(v)616}617618#[jrsonnet_macros::builtin]619fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {620 Ok(str.replace(&from as &str, &to as &str))621}622623#[jrsonnet_macros::builtin]624fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either![usize, M1]) -> Result<VecVal> {625 use Either2::*;626 Ok(VecVal(match maxsplits {627 A(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),628 B(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),629 }))630}631632#[jrsonnet_macros::builtin]633fn builtin_ascii_upper(str: IStr) -> Result<String> {634 Ok(str.to_ascii_uppercase())635}636637#[jrsonnet_macros::builtin]638fn builtin_ascii_lower(str: IStr) -> Result<String> {639 Ok(str.to_ascii_lowercase())640}641642#[jrsonnet_macros::builtin]643fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {644 match arr {645 IndexableVal::Str(s) => {646 let x: IStr = IStr::try_from(x.0)?;647 Ok(!x.is_empty() && s.contains(&*x))648 }649 IndexableVal::Arr(a) => {650 for item in a.iter() {651 let item = item?;652 if equals(&item, &x.0)? {653 return Ok(true);654 }655 }656 Ok(false)657 }658 }659}660661#[jrsonnet_macros::builtin]662fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {663 let mut count = 0;664 for item in arr.iter() {665 if equals(&item.0, &v.0)? {666 count += 1;667 }668 }669 Ok(count)670}crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -82,6 +82,8 @@
ResolvedFileNotFound(PathBuf),
#[error("imported file is not valid utf-8: {0:?}")]
ImportBadFileUtf8(PathBuf),
+ #[error("import io error: {0}")]
+ ImportIo(String),
#[error("tried to import {1} from {0}, but imports is not supported")]
ImportNotSupported(PathBuf, PathBuf),
#[error(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -701,5 +701,12 @@
import_location.pop();
Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
}
+ ImportBin(path) => {
+ let tmp = loc.clone().0;
+ let mut import_location = tmp.to_path_buf();
+ import_location.pop();
+ let bytes = with_state(|s| s.import_file_bin(&import_location, path))?;
+ Val::Arr(ArrValue::Bytes(bytes))
+ }
})
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -5,14 +5,12 @@
use fs::File;
use jrsonnet_interner::IStr;
use std::fs;
-use std::io::Read;
use std::{
any::Any,
- cell::RefCell,
- collections::HashMap,
path::{Path, PathBuf},
rc::Rc,
};
+use std::{convert::TryFrom, io::Read};
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver {
@@ -21,9 +19,19 @@
/// where `${vendor}` is a library path.
fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>>;
+ fn load_file_contents(&self, resolved: &Path) -> Result<Vec<u8>>;
+
/// Reads file from filesystem, should be used only with path received from `resolve_file`
- fn load_file_contents(&self, resolved: &Path) -> Result<IStr>;
+ fn load_file_str(&self, resolved: &Path) -> Result<IStr> {
+ Ok(IStr::try_from(&self.load_file_contents(resolved)? as &[u8])
+ .map_err(|_| ImportBadFileUtf8(resolved.to_path_buf()))?)
+ }
+ /// Reads file from filesystem, should be used only with path received from `resolve_file`
+ fn load_file_bin(&self, resolved: &Path) -> Result<Rc<[u8]>> {
+ Ok(self.load_file_contents(resolved)?.into())
+ }
+
/// # Safety
///
/// For use only in bindings, should not be used elsewhere.
@@ -39,8 +47,7 @@
throw!(ImportNotSupported(from.into(), path.into()))
}
- fn load_file_contents(&self, _resolved: &Path) -> Result<IStr> {
- // Can be only caused by library direct consumer, not by supplied jsonnet
+ fn load_file_contents(&self, _resolved: &Path) -> Result<Vec<u8>> {
panic!("dummy resolver can't load any file")
}
@@ -79,41 +86,12 @@
throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
}
}
- fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+ fn load_file_contents(&self, id: &Path) -> Result<Vec<u8>> {
let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
- let mut out = String::new();
- file.read_to_string(&mut out)
- .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
- Ok(out.into())
- }
- unsafe fn as_any(&self) -> &dyn Any {
- panic!("this resolver can't be used as any")
- }
-}
-
-type ResolutionData = (PathBuf, PathBuf);
-
-/// Caches results of the underlying resolver
-pub struct CachingImportResolver {
- resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<Path>>>>,
- loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,
- inner: Box<dyn ImportResolver>,
-}
-impl ImportResolver for CachingImportResolver {
- fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
- self.resolution_cache
- .borrow_mut()
- .entry((from.to_owned(), path.to_owned()))
- .or_insert_with(|| self.inner.resolve_file(from, path))
- .clone()
- }
-
- fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
- self.loading_cache
- .borrow_mut()
- .entry(resolved.to_owned())
- .or_insert_with(|| self.inner.load_file_contents(resolved))
- .clone()
+ let mut out = Vec::new();
+ file.read_to_end(&mut out)
+ .map_err(|e| ImportIo(e.to_string()))?;
+ Ok(out)
}
unsafe fn as_any(&self) -> &dyn Any {
panic!("this resolver can't be used as any")
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -118,8 +118,9 @@
breakpoints: Breakpoints,
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
- files: HashMap<Rc<Path>, FileData>,
- str_files: HashMap<Rc<Path>, IStr>,
+ files: GcHashMap<Rc<Path>, FileData>,
+ str_files: GcHashMap<Rc<Path>, IStr>,
+ bin_files: GcHashMap<Rc<Path>, Rc<[u8]>>,
}
pub struct FileData {
@@ -280,18 +281,26 @@
return self.evaluate_loaded_file_raw(&file_path);
}
}
- let contents = self.load_file_contents(&file_path)?;
+ let contents = self.load_file_str(&file_path)?;
self.add_file(file_path.clone(), contents)?;
self.evaluate_loaded_file_raw(&file_path)
}
pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {
let path = self.resolve_file(from, path)?;
if !self.data().str_files.contains_key(&path) {
- let file_str = self.load_file_contents(&path)?;
+ let file_str = self.load_file_str(&path)?;
self.data_mut().str_files.insert(path.clone(), file_str);
}
Ok(self.data().str_files.get(&path).cloned().unwrap())
}
+ pub(crate) fn import_file_bin(&self, from: &Path, path: &Path) -> Result<Rc<[u8]>> {
+ let path = self.resolve_file(from, path)?;
+ if !self.data().bin_files.contains_key(&path) {
+ let file_bin = self.load_file_bin(&path)?;
+ self.data_mut().bin_files.insert(path.clone(), file_bin);
+ }
+ Ok(self.data().bin_files.get(&path).cloned().unwrap())
+ }
fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {
let expr: LocExpr = {
@@ -607,8 +616,11 @@
pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
self.settings().import_resolver.resolve_file(from, path)
}
- pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {
- self.settings().import_resolver.load_file_contents(path)
+ pub fn load_file_str(&self, path: &Path) -> Result<IStr> {
+ self.settings().import_resolver.load_file_str(path)
+ }
+ pub fn load_file_bin(&self, path: &Path) -> Result<Rc<[u8]>> {
+ self.settings().import_resolver.load_file_bin(path)
}
pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {
@@ -687,7 +699,6 @@
primitive_equals, EvaluationState,
};
use gcmodule::{Cc, Trace};
- use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
use std::{
path::{Path, PathBuf},
@@ -1204,19 +1215,23 @@
Ok(())
}
- struct TestImportResolver(IStr);
+ struct TestImportResolver(Vec<u8>);
impl crate::import::ImportResolver for TestImportResolver {
fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {
Ok(PathBuf::from("/test").into())
}
- fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {
+ fn load_file_contents(&self, _: &Path) -> crate::error::Result<Vec<u8>> {
Ok(self.0.clone())
}
unsafe fn as_any(&self) -> &dyn std::any::Any {
panic!()
}
+
+ fn load_file_bin(&self, _resolved: &Path) -> crate::error::Result<Rc<[u8]>> {
+ panic!()
+ }
}
#[test]
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -1,4 +1,7 @@
-use std::convert::{TryFrom, TryInto};
+use std::{
+ convert::{TryFrom, TryInto},
+ rc::Rc,
+};
use gcmodule::Cc;
use jrsonnet_interner::IStr;
@@ -306,6 +309,44 @@
}
}
+/// Specialization
+pub struct Bytes(pub Rc<[u8]>);
+
+impl Typed for Bytes {
+ const TYPE: &'static ComplexValType =
+ &ComplexValType::ArrayRef(&ComplexValType::BoundedNumber(Some(0.0), Some(255.0)));
+}
+impl TryFrom<Val> for Bytes {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ match value {
+ Val::Arr(ArrValue::Bytes(bytes)) => Ok(Self(bytes)),
+ _ => {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => {
+ let mut out = Vec::with_capacity(a.len());
+ for e in a.iter() {
+ let r = e?;
+ out.push(u8::try_from(r)?);
+ }
+ Ok(Self(out.into()))
+ }
+ _ => unreachable!(),
+ }
+ }
+ }
+ }
+}
+impl TryFrom<Bytes> for Val {
+ type Error = LocError;
+
+ fn try_from(value: Bytes) -> Result<Self> {
+ Ok(Val::Arr(ArrValue::Bytes(value.0)))
+ }
+}
+
pub struct M1;
impl Typed for M1 {
const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -174,6 +174,7 @@
#[derive(Debug, Clone, Trace)]
#[force_tracking]
pub enum ArrValue {
+ Bytes(#[skip_trace] Rc<[u8]>),
Lazy(Cc<Vec<LazyVal>>),
Eager(Cc<Vec<Val>>),
Extended(Box<(Self, Self)>),
@@ -185,6 +186,7 @@
pub fn len(&self) -> usize {
match self {
+ Self::Bytes(i) => i.len(),
Self::Lazy(l) => l.len(),
Self::Eager(e) => e.len(),
Self::Extended(v) => v.0.len() + v.1.len(),
@@ -197,6 +199,9 @@
pub fn get(&self, index: usize) -> Result<Option<Val>> {
match self {
+ Self::Bytes(i) => i
+ .get(index)
+ .map_or(Ok(None), |v| Ok(Some(Val::Num(*v as f64)))),
Self::Lazy(vec) => {
if let Some(v) = vec.get(index) {
Ok(Some(v.evaluate()?))
@@ -218,6 +223,9 @@
pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {
match self {
+ Self::Bytes(i) => i
+ .get(index)
+ .map(|b| LazyVal::new_resolved(Val::Num(*b as f64))),
Self::Lazy(vec) => vec.get(index).cloned(),
Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),
Self::Extended(v) => {
@@ -233,6 +241,13 @@
pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {
Ok(match self {
+ Self::Bytes(i) => {
+ let mut out = Vec::with_capacity(i.len());
+ for v in i.iter() {
+ out.push(Val::Num(*v as f64));
+ }
+ Cc::new(out)
+ }
Self::Lazy(vec) => {
let mut out = Vec::with_capacity(vec.len());
for item in vec.iter() {
@@ -253,6 +268,7 @@
pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
+ Self::Bytes(b) => Ok(Val::Num(b[idx] as f64)),
Self::Lazy(l) => l[idx].evaluate(),
Self::Eager(e) => Ok(e[idx].clone()),
Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),
@@ -261,6 +277,7 @@
pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
(0..self.len()).map(move |idx| match self {
+ Self::Bytes(b) => LazyVal::new_resolved(Val::Num(b[idx] as f64)),
Self::Lazy(l) => l[idx].clone(),
Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
Self::Extended(_) => self.get_lazy(idx).unwrap(),
@@ -269,6 +286,11 @@
pub fn reversed(self) -> Self {
match self {
+ Self::Bytes(b) => {
+ let mut out = b.to_vec();
+ out.reverse();
+ Self::Bytes(out.into())
+ }
Self::Lazy(vec) => {
let mut out = (&vec as &Vec<_>).clone();
out.reverse();
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -4,10 +4,12 @@
use std::{
borrow::Cow,
cell::RefCell,
+ convert::TryFrom,
fmt::{self, Display},
hash::{BuildHasherDefault, Hash, Hasher},
ops::Deref,
rc::Rc,
+ str::Utf8Error,
};
#[derive(Clone, PartialOrd, Ord, Eq)]
@@ -85,6 +87,15 @@
}
}
+impl TryFrom<&[u8]> for IStr {
+ type Error = Utf8Error;
+
+ fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
+ let str = std::str::from_utf8(value)?;
+ Ok(str.into())
+ }
+}
+
impl From<String> for IStr {
fn from(str: String) -> Self {
(&str as &str).into()
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -285,6 +285,8 @@
Import(PathBuf),
/// importStr "file.txt"
ImportStr(PathBuf),
+ /// importBin "file.txt"
+ ImportBin(PathBuf),
/// error "I'm broken"
ErrorStmt(LocExpr),
/// a(b, c)
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -53,7 +53,7 @@
rule number() -> f64 = quiet!{a:$(uint_str() ("." uint_str())? (['e'|'E'] (s:['+'|'-'])? uint_str())?) {? a.parse().map_err(|_| "<number>") }} / expected!("<number>")
/// Reserved word followed by any non-alphanumberic
- rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
+ rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "importbin" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()
rule id() = quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")
rule keyword(id: &'static str) -> ()
@@ -218,6 +218,7 @@
/ array_comp_expr(s)
/ keyword("importstr") _ path:string() {Expr::ImportStr(PathBuf::from(path))}
+ / keyword("importbin") _ path:string() {Expr::ImportBin(PathBuf::from(path))}
/ keyword("import") _ path:string() {Expr::Import(PathBuf::from(path))}
/ var_expr(s)