difftreelog
feat implement argument parsing with proc macro
in: master
17 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth49 };49 };50 // Release memory occipied by arguments passed50 // Release memory occipied by arguments passed51 unsafe {51 unsafe {52 CString::from_raw(base);52 let _ = CString::from_raw(base);53 CString::from_raw(rel);53 let _ = CString::from_raw(rel);54 }54 }55 let result_raw = unsafe { CStr::from_ptr(result_ptr) };55 let result_raw = unsafe { CStr::from_ptr(result_ptr) };56 let result_str = result_raw.to_str().unwrap();56 let result_str = result_raw.to_str().unwrap();64 let found_here_raw = unsafe { CStr::from_ptr(found_here) };64 let found_here_raw = unsafe { CStr::from_ptr(found_here) };65 let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());65 let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());66 unsafe {66 unsafe {67 CString::from_raw(found_here);67 let _ = CString::from_raw(found_here);68 }68 }696970 let mut out = self.out.borrow_mut();70 let mut out = self.out.borrow_mut();bindings/jsonnet/src/native.rsdiffbeforeafterboth3 error::{Error, LocError},3 error::{Error, LocError},4 gc::TraceBox,4 gc::TraceBox,5 native::{NativeCallback, NativeCallbackHandler},5 native::{NativeCallback, NativeCallbackHandler},6 EvaluationState, Val,6 EvaluationState, IStr, Val,7};7};8use jrsonnet_parser::{Param, ParamsDesc};8use jrsonnet_parser::{Param, ParamsDesc};9use std::{9use std::{10 convert::TryFrom,10 ffi::{c_void, CStr},11 ffi::{c_void, CStr},11 os::raw::{c_char, c_int},12 os::raw::{c_char, c_int},12 path::Path,13 path::Path,45 if success == 1 {46 if success == 1 {46 Ok(v)47 Ok(v)47 } else {48 } else {48 let e = v.try_cast_str("native error").expect("error msg");49 let e = IStr::try_from(v).expect("error msg");49 Err(Error::RuntimeError(e).into())50 Err(Error::RuntimeError(e).into())50 }51 }51 }52 }crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth23jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }23jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }24jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }24jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }25jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }25jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }26jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }26pathdiff = "0.2.0"27pathdiff = "0.2.0"272828md5 = "0.7.0"29md5 = "0.7.0"crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth5use gcmodule::Trace;5use gcmodule::Trace;6use jrsonnet_interner::IStr;6use jrsonnet_interner::IStr;7use jrsonnet_types::ValType;7use jrsonnet_types::ValType;8use std::convert::TryFrom;8use thiserror::Error;9use thiserror::Error;91010#[derive(Debug, Clone, Error, Trace)]11#[derive(Debug, Clone, Error, Trace)]484 match code.convtype {485 match code.convtype {485 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),486 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),486 ConvTypeV::Decimal => {487 ConvTypeV::Decimal => {487 let value = value.clone().try_cast_num("%d/%u/%i requires number")?;488 let value = f64::try_from(value.clone())?;488 render_decimal(489 render_decimal(489 &mut tmp_out,490 &mut tmp_out,490 value as i64,491 value as i64,495 );496 );496 }497 }497 ConvTypeV::Octal => {498 ConvTypeV::Octal => {498 let value = value.clone().try_cast_num("%o requires number")?;499 let value = f64::try_from(value.clone())?;499 render_octal(500 render_octal(500 &mut tmp_out,501 &mut tmp_out,501 value as i64,502 value as i64,507 );508 );508 }509 }509 ConvTypeV::Hexadecimal => {510 ConvTypeV::Hexadecimal => {510 let value = value.clone().try_cast_num("%x/%X requires number")?;511 let value = f64::try_from(value.clone())?;511 render_hexadecimal(512 render_hexadecimal(512 &mut tmp_out,513 &mut tmp_out,513 value as i64,514 value as i64,520 );521 );521 }522 }522 ConvTypeV::Scientific => {523 ConvTypeV::Scientific => {523 let value = value.clone().try_cast_num("%e/%E requires number")?;524 let value = f64::try_from(value.clone())?;524 render_float_sci(525 render_float_sci(525 &mut tmp_out,526 &mut tmp_out,526 value,527 value,534 );535 );535 }536 }536 ConvTypeV::Float => {537 ConvTypeV::Float => {537 let value = value.clone().try_cast_num("%e/%E requires number")?;538 let value = f64::try_from(value.clone())?;538 render_float(539 render_float(539 &mut tmp_out,540 &mut tmp_out,540 value,541 value,547 );548 );548 }549 }549 ConvTypeV::Shorter => {550 ConvTypeV::Shorter => {550 let value = value.clone().try_cast_num("%g/%G requires number")?;551 let value = f64::try_from(value.clone())?;551 let exponent = value.log10().floor();552 let exponent = value.log10().floor();552 if exponent < -4.0 || exponent >= fpprec as f64 {553 if exponent < -4.0 || exponent >= fpprec as f64 {553 render_float_sci(554 render_float_sci(633 }634 }634 let value = &values[0];635 let value = &values[0];635 values = &values[1..];636 values = &values[1..];636 value.clone().try_cast_num("field width")? as usize637 usize::try_from(value.clone())?637 }638 }638 Width::Fixed(n) => n,639 Width::Fixed(n) => n,639 };640 };644 }645 }645 let value = &values[0];646 let value = &values[0];646 values = &values[1..];647 values = &values[1..];647 Some(value.clone().try_cast_num("field precision")? as usize)648 Some(usize::try_from(value.clone())?)648 }649 }649 Some(Width::Fixed(n)) => Some(n),650 Some(Width::Fixed(n)) => Some(n),650 None => None,651 None => None,crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth1use crate::typed::{Any, Either, Null, PositiveF64, VecVal, M1};2use crate::{self as jrsonnet_evaluator, ObjValue};1use crate::{3use crate::{2 builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},4 builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},3 equals,5 equals,4 error::{Error::*, Result},6 error::{Error::*, Result},5 operator::evaluate_mod_op,7 operator::evaluate_mod_op,6 parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,8 parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,7 IndexableVal, LazyVal, Val,9 IndexableVal, Val,8};10};9use format::{format_arr, format_obj};11use format::{format_arr, format_obj};10use gcmodule::Cc;12use gcmodule::Cc;13use jrsonnet_types::ty;15use jrsonnet_types::ty;14use serde::Deserialize;16use serde::Deserialize;15use serde_yaml::DeserializingQuirks;17use serde_yaml::DeserializingQuirks;16use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};18use std::{19 collections::HashMap,20 convert::{TryFrom, TryInto},21 path::PathBuf,22 rc::Rc,23};172418pub mod stdlib;25pub mod stdlib;19pub use stdlib::*;26pub use stdlib::*;24pub mod manifest;31pub mod manifest;25pub mod sort;32pub mod sort;263327pub fn std_format(str: IStr, vals: Val) -> Result<Val> {34pub fn std_format(str: IStr, vals: Val) -> Result<String> {28 push_frame(35 push_frame(29 &ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),36 &ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),30 || format!("std.format of {}", str),37 || format!("std.format of {}", str),31 || {38 || {32 Ok(match vals {39 Ok(match vals {33 Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),40 Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,34 Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),41 Val::Obj(obj) => format_obj(&str, &obj)?,35 o => Val::Str(format_arr(&str, &[o])?.into()),42 o => format_arr(&str, &[o])?,36 })43 })37 },44 },38 )45 )139 };146 };140}147}141148149#[jrsonnet_macros::builtin]142fn builtin_length(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {150fn builtin_length(x: Either<IStr, Either<VecVal, ObjValue>>) -> Result<usize> {143 parse_args!(context, "length", args, 1, [151 Ok(match x {144 0, x: ty!((string | object | array));145 ], {146 Ok(match x {147 Val::Str(n) => Val::Num(n.chars().count() as f64),152 Either::Left(x) => x.len(),148 Val::Arr(a) => Val::Num(a.len() as f64),153 Either::Right(Either::Left(x)) => x.0.len(),149 Val::Obj(o) => Val::Num(154 Either::Right(Either::Right(x)) => x150 o.fields_visibility()155 .fields_visibility()151 .into_iter()156 .into_iter()152 .filter(|(_k, v)| *v)157 .filter(|(_k, v)| *v)153 .count() as f64,158 .count(),154 ),155 _ => unreachable!(),156 })157 })159 })158}160}159161162#[jrsonnet_macros::builtin]160fn builtin_type(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {163fn builtin_type(x: Any) -> Result<IStr> {161 parse_args!(context, "type", args, 1, [164 Ok(x.0.value_type().name().into())162 0, x: ty!(any);163 ], {164 Ok(Val::Str(x.value_type().name().into()))165 })166}165}167166167#[jrsonnet_macros::builtin]168fn builtin_make_array(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {168fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {169 parse_args!(context, "makeArray", args, 2, [169 let mut out = Vec::with_capacity(sz);170 0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;171 1, func: ty!(function) => Val::Func;172 ], {173 let mut out = Vec::with_capacity(sz as usize);174 for i in 0..sz as usize {170 for i in 0..sz {175 out.push(LazyVal::new_resolved(func.evaluate_values(171 out.push(func.evaluate_values(&[Val::Num(i as f64)])?)176 context.clone(),177 &[Val::Num(i as f64)]178 )?))179 }172 }180 Ok(Val::Arr(out.into()))173 Ok(VecVal(out))181 })182}174}183175176#[jrsonnet_macros::builtin]184fn builtin_codepoint(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {177const fn builtin_codepoint(str: char) -> Result<u32> {185 parse_args!(context, "codepoint", args, 1, [178 Ok(str as u32)186 0, str: ty!(char) => Val::Str;187 ], {188 Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))189 })190}179}191180181#[jrsonnet_macros::builtin]192fn builtin_object_fields_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {182fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {193 parse_args!(context, "objectFieldsEx", args, 2, [183 let out = obj.fields_ex(inc_hidden);194 0, obj: ty!(object) => Val::Obj;195 1, inc_hidden: ty!(boolean) => Val::Bool;196 ], {197 let out = obj.fields_ex(inc_hidden);198 Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))184 Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))199 })200}185}201186187#[jrsonnet_macros::builtin]202fn builtin_object_has_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {188fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {203 parse_args!(context, "objectHasEx", args, 3, [189 Ok(obj.has_field_ex(f, inc_hidden))204 0, obj: ty!(object) => Val::Obj;205 1, f: ty!(string) => Val::Str;206 2, inc_hidden: ty!(boolean) => Val::Bool;207 ], {208 Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))209 })210}190}211191192#[jrsonnet_macros::builtin]212fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {193fn builtin_parse_json(s: IStr) -> Result<Any> {213 parse_args!(context, "parseJson", args, 1, [194 let value: serde_json::Value = serde_json::from_str(&s)214 0, s: ty!(string) => Val::Str;215 ], {216 let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;195 .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;217 Ok(Val::try_from(&value)?)196 Ok(Any(Val::try_from(&value)?))218 })219}197}220198199#[jrsonnet_macros::builtin]221fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {200fn builtin_parse_yaml(s: IStr) -> Result<Any> {222 parse_args!(context, "parseYaml", args, 1, [201 let value = serde_yaml::Deserializer::from_str_with_quirks(223 0, s: ty!(string) => Val::Str;224 ], {225 let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });202 &s,203 DeserializingQuirks { old_octals: true },204 );226 let mut out = vec![];205 let mut out = vec![];227 for item in value {206 for item in value {228 let value = serde_json::Value::deserialize(item)207 let value = serde_json::Value::deserialize(item)229 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;208 .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;230 let val = Val::try_from(&value)?;209 let val = Val::try_from(&value)?;231 out.push(val);210 out.push(val);232 }211 }233 if out.is_empty() {212 Ok(Any(if out.is_empty() {234 Ok(Val::Null)213 Val::Null235 } else if out.len() == 1 {214 } else if out.len() == 1 {236 Ok(out.into_iter().next().unwrap())215 out.into_iter().next().unwrap()237 } else {216 } else {238 Ok(Val::Arr(out.into()))217 Val::Arr(out.into())239 }218 }))240 })241}219}242220221#[jrsonnet_macros::builtin]243fn builtin_slice(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {222fn builtin_slice(244 parse_args!(context, "slice", args, 4, [223 indexable: IndexableVal,245 0, indexable: ty!((string | array));246 1, index: ty!((number | null));224 index: Either<usize, Null>,247 2, end: ty!((number | null));225 end: Either<usize, Null>,248 3, step: ty!((number | null));226 step: Either<usize, Null>,249 ], {227) -> Result<Any> {250 std_slice(228 std_slice(indexable, index.left(), end.left(), step.left()).map(Any)251 indexable.into_indexable()?,252 index.try_cast_nullable_num("index")?.map(|v| v as usize),253 end.try_cast_nullable_num("end")?.map(|v| v as usize),254 step.try_cast_nullable_num("step")?.map(|v| v as usize),255 )256 })257}229}258230231#[jrsonnet_macros::builtin]259fn builtin_substr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {232fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {260 parse_args!(context, "substr", args, 3, [233 Ok(str.chars().skip(from as usize).take(len as usize).collect())261 0, str: ty!(string) => Val::Str;262 1, from: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;263 2, len: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;264 ], {265 let out: String = str.chars().skip(from as usize).take(len as usize).collect();266 Ok(Val::Str(out.into()))267 })268}234}269235236#[jrsonnet_macros::builtin]270fn builtin_primitive_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {237fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {271 parse_args!(context, "primitiveEquals", args, 2, [238 primitive_equals(&a.0, &b.0)272 0, a: ty!(any);273 1, b: ty!(any);274 ], {275 Ok(Val::Bool(primitive_equals(&a, &b)?))276 })277}239}278240241#[jrsonnet_macros::builtin]279fn builtin_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {242fn builtin_equals(a: Any, b: Any) -> Result<bool> {280 parse_args!(context, "equals", args, 2, [243 equals(&a.0, &b.0)281 0, a: ty!(any);282 1, b: ty!(any);283 ], {284 Ok(Val::Bool(equals(&a, &b)?))285 })286}244}287245246#[jrsonnet_macros::builtin]288fn builtin_modulo(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {247fn builtin_modulo(a: f64, b: f64) -> Result<f64> {289 parse_args!(context, "modulo", args, 2, [248 Ok(a % b)290 0, a: ty!(number) => Val::Num;291 1, b: ty!(number) => Val::Num;292 ], {293 Ok(Val::Num(a % b))294 })295}249}296250251#[jrsonnet_macros::builtin]297fn builtin_mod(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {252fn builtin_mod(a: Either<f64, IStr>, b: Any) -> Result<Any> {298 parse_args!(context, "mod", args, 2, [253 Ok(Any(evaluate_mod_op(254 &match a {299 0, a: ty!((number | string));255 Either::Left(v) => Val::Num(v),300 1, b: ty!(any);256 Either::Right(s) => Val::Str(s),301 ], {257 },302 evaluate_mod_op(&a, &b)258 &b.0,303 })259 )?))304}260}305261262#[jrsonnet_macros::builtin]306fn builtin_floor(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {263fn builtin_floor(x: f64) -> Result<f64> {307 parse_args!(context, "floor", args, 1, [264 Ok(x.floor())308 0, x: ty!(number) => Val::Num;309 ], {310 Ok(Val::Num(x.floor()))311 })312}265}313266267#[jrsonnet_macros::builtin]314fn builtin_ceil(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {268fn builtin_ceil(x: f64) -> Result<f64> {315 parse_args!(context, "ceil", args, 1, [269 Ok(x.ceil())316 0, x: ty!(number) => Val::Num;317 ], {318 Ok(Val::Num(x.ceil()))319 })320}270}321271272#[jrsonnet_macros::builtin]322fn builtin_log(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {273fn builtin_log(n: f64) -> Result<f64> {323 parse_args!(context, "log", args, 1, [274 Ok(n.ln())324 0, n: ty!(number) => Val::Num;325 ], {326 Ok(Val::Num(n.ln()))327 })328}275}329276277#[jrsonnet_macros::builtin]330fn builtin_pow(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {278fn builtin_pow(x: f64, n: f64) -> Result<f64> {331 parse_args!(context, "pow", args, 2, [279 Ok(x.powf(n))332 0, x: ty!(number) => Val::Num;333 1, n: ty!(number) => Val::Num;334 ], {335 Ok(Val::Num(x.powf(n)))336 })337}280}338281282#[jrsonnet_macros::builtin]339fn builtin_sqrt(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {283fn builtin_sqrt(x: PositiveF64) -> Result<f64> {340 parse_args!(context, "sqrt", args, 1, [284 Ok(x.0.sqrt())341 0, x: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;342 ], {343 Ok(Val::Num(x.sqrt()))344 })345}285}346286287#[jrsonnet_macros::builtin]347fn builtin_sin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {288fn builtin_sin(x: f64) -> Result<f64> {348 parse_args!(context, "sin", args, 1, [289 Ok(x.sin())349 0, x: ty!(number) => Val::Num;350 ], {351 Ok(Val::Num(x.sin()))352 })353}290}354291292#[jrsonnet_macros::builtin]355fn builtin_cos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {293fn builtin_cos(x: f64) -> Result<f64> {356 parse_args!(context, "cos", args, 1, [294 Ok(x.cos())357 0, x: ty!(number) => Val::Num;358 ], {359 Ok(Val::Num(x.cos()))360 })361}295}362296297#[jrsonnet_macros::builtin]363fn builtin_tan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {298fn builtin_tan(x: f64) -> Result<f64> {364 parse_args!(context, "tan", args, 1, [299 Ok(x.tan())365 0, x: ty!(number) => Val::Num;366 ], {367 Ok(Val::Num(x.tan()))368 })369}300}370301302#[jrsonnet_macros::builtin]371fn builtin_asin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {303fn builtin_asin(x: f64) -> Result<f64> {372 parse_args!(context, "asin", args, 1, [304 Ok(x.asin())373 0, x: ty!(number) => Val::Num;374 ], {375 Ok(Val::Num(x.asin()))376 })377}305}378306307#[jrsonnet_macros::builtin]379fn builtin_acos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {308fn builtin_acos(x: f64) -> Result<f64> {380 parse_args!(context, "acos", args, 1, [309 Ok(x.acos())381 0, x: ty!(number) => Val::Num;382 ], {383 Ok(Val::Num(x.acos()))384 })385}310}386311312#[jrsonnet_macros::builtin]387fn builtin_atan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {313fn builtin_atan(x: f64) -> Result<f64> {388 parse_args!(context, "atan", args, 1, [314 Ok(x.atan())389 0, x: ty!(number) => Val::Num;390 ], {391 Ok(Val::Num(x.atan()))392 })393}315}394316317#[jrsonnet_macros::builtin]395fn builtin_exp(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {318fn builtin_exp(x: f64) -> Result<f64> {396 parse_args!(context, "exp", args, 1, [319 Ok(x.exp())397 0, x: ty!(number) => Val::Num;398 ], {399 Ok(Val::Num(x.exp()))400 })401}320}402321403fn frexp(s: f64) -> (f64, i16) {322fn frexp(s: f64) -> (f64, i16) {411 }330 }412}331}413332333#[jrsonnet_macros::builtin]414fn builtin_mantissa(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {334fn builtin_mantissa(x: f64) -> Result<f64> {415 parse_args!(context, "mantissa", args, 1, [335 Ok(frexp(x).0)416 0, x: ty!(number) => Val::Num;417 ], {418 Ok(Val::Num(frexp(x).0))419 })420}336}421337338#[jrsonnet_macros::builtin]422fn builtin_exponent(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {339fn builtin_exponent(x: f64) -> Result<i16> {423 parse_args!(context, "exponent", args, 1, [340 Ok(frexp(x).1)424 0, x: ty!(number) => Val::Num;425 ], {426 Ok(Val::Num(frexp(x).1.into()))427 })428}341}429342343#[jrsonnet_macros::builtin]430fn builtin_ext_var(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {344fn builtin_ext_var(x: IStr) -> Result<Any> {431 parse_args!(context, "extVar", args, 1, [345 Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())432 0, x: ty!(string) => Val::Str;433 ], {434 Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)346 .ok_or(UndefinedExternalVariable(x))?))435 })436}347}437348349#[jrsonnet_macros::builtin]438fn builtin_native(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {350fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {439 parse_args!(context, "native", args, 1, [440 0, x: ty!(string) => Val::Str;441 ], {442 Ok(with_state(|s| s.settings().ext_natives.get(&x).cloned()).map(|v| Val::Func(Cc::new(FuncVal::NativeExt(x.clone(), v)))).ok_or(UndefinedExternalFunction(x))?)351 Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())352 .map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))443 })353 .ok_or(UndefinedExternalFunction(name))?)444}354}445355356#[jrsonnet_macros::builtin]446fn builtin_filter(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {357fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {447 parse_args!(context, "filter", args, 2, [358 arr.filter(|val| bool::try_from(func.evaluate_values(&[val.clone()])?))448 0, func: ty!(function) => Val::Func;449 1, arr: ty!(array) => Val::Arr;450 ], {451 Ok(Val::Arr(arr.filter(|val| func452 .evaluate_values(context.clone(), &[val.clone()])?453 .try_cast_bool("filter predicate"))?))454 })455}359}456360361#[jrsonnet_macros::builtin]457fn builtin_map(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {362fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {458 parse_args!(context, "map", args, 2, [363 arr.map(|val| func.evaluate_values(&[val]))459 0, func: ty!(function) => Val::Func;460 1, arr: ty!(array) => Val::Arr;461 ], {462 Ok(Val::Arr(arr.map(|val| func463 .evaluate_values(context.clone(), &[val]))?))464 })465}364}466365366#[jrsonnet_macros::builtin]467fn builtin_flatmap(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {367fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {468 parse_args!(context, "flatMap", args, 2, [368 match arr {469 0, func: ty!(function) => Val::Func;470 1, arr: ty!((array | string));471 ], {472 match arr {473 Val::Str(s) => {369 IndexableVal::Str(s) => {474 let mut out = String::new();370 let mut out = String::new();475 for c in s.chars() {371 for c in s.chars() {476 match func.evaluate_values(context.clone(), &[Val::Str(c.to_string().into())])? {372 match func.evaluate_values(&[Val::Str(c.to_string().into())])? {477 Val::Str(o) => out.push_str(&o),373 Val::Str(o) => out.push_str(&o),478 _ => throw!(RuntimeError("in std.join all items should be strings".into())),374 _ => throw!(RuntimeError(375 "in std.join all items should be strings".into()376 )),479 };377 };480 }378 }481 Ok(Val::Str(out.into()))379 Ok(IndexableVal::Str(out.into()))482 },380 }483 Val::Arr(a) => {381 IndexableVal::Arr(a) => {484 let mut out = Vec::new();382 let mut out = Vec::new();485 for el in a.iter() {383 for el in a.iter() {486 let el = el?;384 let el = el?;487 match func.evaluate_values(context.clone(), &[el])? {385 match func.evaluate_values(&[el])? {488 Val::Arr(o) => for oe in o.iter() {386 Val::Arr(o) => {387 for oe in o.iter() {489 out.push(oe?)388 out.push(oe?)490 },389 }491 _ => throw!(RuntimeError("in std.join all items should be arrays".into())),390 }391 _ => throw!(RuntimeError(392 "in std.join all items should be arrays".into()393 )),492 };394 };493 }395 }494 Ok(Val::Arr(out.into()))396 Ok(IndexableVal::Arr(out.into()))495 },496 _ => unreachable!(),497 }397 }498 })398 }499}399}500400401#[jrsonnet_macros::builtin]501fn builtin_foldl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {402fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {502 parse_args!(context, "foldl", args, 3, [403 let mut acc = init.0;503 0, func: ty!(function) => Val::Func;504 1, arr: ty!(array) => Val::Arr;505 2, init: ty!(any);506 ], {507 let mut acc = init;508 for i in arr.iter() {404 for i in arr.iter() {509 acc = func.evaluate_values(context.clone(), &[acc, i?])?;405 acc = func.evaluate_values(&[acc, i?])?;510 }406 }511 Ok(acc)407 Ok(Any(acc))512 })513}408}514409410#[jrsonnet_macros::builtin]515fn builtin_foldr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {411fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {516 parse_args!(context, "foldr", args, 3, [412 let mut acc = init.0;517 0, func: ty!(function) => Val::Func;518 1, arr: ty!(array) => Val::Arr;519 2, init: ty!(any);520 ], {521 let mut acc = init;522 for i in arr.iter().rev() {413 for i in arr.iter().rev() {523 acc = func.evaluate_values(context.clone(), &[i?, acc])?;414 acc = func.evaluate_values(&[i?, acc])?;524 }415 }525 Ok(acc)416 Ok(Any(acc))526 })527}417}528418419#[jrsonnet_macros::builtin]529#[allow(non_snake_case)]420#[allow(non_snake_case)]530fn builtin_sort_impl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {421fn builtin_sort_impl(arr: ArrValue, keyF: Cc<FuncVal>) -> Result<ArrValue> {531 parse_args!(context, "sort", args, 2, [422 if arr.len() <= 1 {532 0, arr: ty!(array) => Val::Arr;533 1, keyF: ty!(function) => Val::Func;534 ], {535 if arr.len() <= 1 {536 return Ok(Val::Arr(arr))423 return Ok(arr);537 }424 }538 Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))425 Ok(ArrValue::Eager(sort::sort(arr.evaluated()?, &keyF)?))539 })540}426}541427428#[jrsonnet_macros::builtin]542fn builtin_format(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {429fn builtin_format(str: IStr, vals: Any) -> Result<String> {543 parse_args!(context, "format", args, 2, [430 std_format(str, vals.0)544 0, str: ty!(string) => Val::Str;545 1, vals: ty!(any)546 ], {547 std_format(str, vals)548 })549}431}550432433#[jrsonnet_macros::builtin]551fn builtin_range(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {434fn builtin_range(from: i32, to: i32) -> Result<VecVal> {552 parse_args!(context, "range", args, 2, [435 if to < from {553 0, from: ty!(number) => Val::Num;554 1, to: ty!(number) => Val::Num;555 ], {556 if to < from {557 return Ok(Val::Arr(ArrValue::new_eager()))436 return Ok(VecVal(Vec::new()));558 }437 }559 let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));438 let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));560 for i in from as usize..=to as usize {439 for i in from as usize..=to as usize {561 out.push(Val::Num(i as f64));440 out.push(Val::Num(i as f64));562 }441 }563 Ok(Val::Arr(out.into()))442 Ok(VecVal(out))564 })565}443}566444445#[jrsonnet_macros::builtin]567fn builtin_char(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {446fn builtin_char(n: u32) -> Result<char> {568 parse_args!(context, "char", args, 1, [569 0, n: ty!(number) => Val::Num;570 ], {571 let mut out = String::new();447 Ok(std::char::from_u32(n as u32).ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?)572 out.push(std::char::from_u32(n as u32).ok_or_else(||573 InvalidUnicodeCodepointGot(n as u32)574 )?);575 Ok(Val::Str(out.into()))576 })577}448}578449450#[jrsonnet_macros::builtin]579fn builtin_encode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {451fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {580 parse_args!(context, "encodeUTF8", args, 1, [452 Ok(VecVal(581 0, str: ty!(string) => Val::Str;453 str.bytes()582 ], {454 .map(|b| Val::Num(b as f64))583 Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))455 .collect::<Vec<Val>>(),584 })456 ))585}457}586458587fn builtin_decode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {459#[jrsonnet_macros::builtin]588 parse_args!(context, "decodeUTF8", args, 1, [460fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {589 0, arr: ty!((Array<ubyte>)) => Val::Arr;590 ], {591 let data: Result<Vec<u8>> = arr.iter().map(|v| v.map(|v| match v{592 Val::Num(n) => n as u8,461 Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)593 _ => unreachable!(),594 })).collect();595 let data = data?;596 Ok(Val::Str(String::from_utf8(data).map_err(|_| RuntimeError("bad utf8".into()))?.into()))597 })598}462}599463464#[jrsonnet_macros::builtin]600fn builtin_md5(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {465fn builtin_md5(str: IStr) -> Result<String> {601 parse_args!(context, "md5", args, 1, [466 Ok(format!("{:x}", md5::compute(&str.as_bytes())))602 0, str: ty!(string) => Val::Str;603 ], {604 Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))605 })606}467}607468608fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {469fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {620 })481 })621}482}622483484#[jrsonnet_macros::builtin]623fn builtin_base64(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {485fn builtin_base64(input: Either<Vec<u8>, IStr>) -> Result<String> {624 parse_args!(context, "base64", args, 1, [486 Ok(match input {625 0, input: ty!((string | (Array<number>)));626 ], {627 Ok(Val::Str(match input {628 Val::Str(s) => {487 Either::Left(a) => base64::encode(a),629 base64::encode(s.bytes().collect::<Vec<_>>()).into()630 },631 Val::Arr(a) => {488 Either::Right(l) => base64::encode(l.bytes().collect::<Vec<_>>()),632 base64::encode(a.iter().map(|v| {633 Ok(v?.unwrap_num()? as u8)634 }).collect::<Result<Vec<_>>>()?).into()635 },636 _ => unreachable!()637 }))638 })489 })639}490}640491492#[jrsonnet_macros::builtin]641fn builtin_base64_decode_bytes(493fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {642 context: Context,643 _loc: &ExprLocation,644 args: &ArgsDesc,645) -> Result<Val> {646 parse_args!(context, "base64DecodeBytes", args, 1, [647 0, input: ty!(string) => Val::Str;648 ], {649 Ok(Val::Arr(494 Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)650 base64::decode(&input.as_bytes())651 .map_err(|_| RuntimeError("bad base64".into()))?652 .iter()653 .map(|v| Val::Num(*v as f64)).collect::<Vec<_>>().into()654 ))655 })656}495}657496497#[jrsonnet_macros::builtin]658fn builtin_base64_decode(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {498fn builtin_base64_decode(input: IStr) -> Result<String> {659 parse_args!(context, "base64Decode", args, 1, [499 let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;660 0, input: ty!(string) => Val::Str;661 ], {662 Ok(Val::Str(663 String::from_utf8(base64::decode(&input.as_bytes())664 .map_err(|_| RuntimeError("bad base64".into()))?)665 .map_err(|_| RuntimeError("bad utf8".into()))?.into()500 Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)666 ))667 })668}501}669502503#[jrsonnet_macros::builtin]670fn builtin_join(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {504fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {671 parse_args!(context, "join", args, 2, [505 Ok(match sep {672 0, sep: ty!((string | array));673 1, arr: ty!(array) => Val::Arr;674 ], {675 Ok(match sep {676 Val::Arr(joiner_items) => {506 IndexableVal::Arr(joiner_items) => {677 let mut out = Vec::new();507 let mut out = Vec::new();678508679 let mut first = true;509 let mut first = true;680 for item in arr.iter() {510 for item in arr.iter() {681 let item = item?.clone();511 let item = item?.clone();682 if let Val::Arr(items) = item {512 if let Val::Arr(items) = item {683 if !first {513 if !first {684 out.reserve(joiner_items.len());514 out.reserve(joiner_items.len());685 // TODO: extend686 for item in joiner_items.iter() {687 out.push(item?);688 }689 }690 first = false;691 out.reserve(items.len());692 // TODO: extend515 // TODO: extend693 for item in items.iter() {516 for item in joiner_items.iter() {694 out.push(item?);517 out.push(item?);695 }518 }696 } else {697 throw!(RuntimeError("in std.join all items should be arrays".into()));698 }519 }520 first = false;521 out.reserve(items.len());522 // TODO: extend523 for item in items.iter() {524 out.push(item?);525 }526 } else {527 throw!(RuntimeError(528 "in std.join all items should be arrays".into()529 ));699 }530 }531 }700532701 Val::Arr(out.into())533 IndexableVal::Arr(out.into())702 },534 }703 Val::Str(sep) => {535 IndexableVal::Str(sep) => {704 let mut out = String::new();536 let mut out = String::new();705537706 let mut first = true;538 let mut first = true;707 for item in arr.iter() {539 for item in arr.iter() {708 let item = item?.clone();540 let item = item?.clone();709 if let Val::Str(item) = item {541 if let Val::Str(item) = item {710 if !first {542 if !first {711 out += &sep;543 out += &sep;712 }713 first = false;714 out += &item;715 } else {716 throw!(RuntimeError("in std.join all items should be strings".into()));717 }544 }545 first = false;546 out += &item;547 } else {548 throw!(RuntimeError(549 "in std.join all items should be strings".into()550 ));718 }551 }552 }719553720 Val::Str(out.into())554 IndexableVal::Str(out.into())721 },555 }722 _ => unreachable!()723 })724 })556 })725}557}726558559#[jrsonnet_macros::builtin]727fn builtin_escape_string_json(560fn builtin_escape_string_json(str_: IStr) -> Result<String> {728 context: Context,729 _loc: &ExprLocation,730 args: &ArgsDesc,731) -> Result<Val> {732 parse_args!(context, "escapeStringJson", args, 1, [561 Ok(escape_string_json(&str_))733 0, str_: ty!(string) => Val::Str;734 ], {735 Ok(Val::Str(escape_string_json(&str_).into()))736 })737}562}738563564#[jrsonnet_macros::builtin]739fn builtin_manifest_json_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {565fn builtin_manifest_json_ex(value: Any, indent: IStr) -> Result<String> {740 parse_args!(context, "manifestJsonEx", args, 2, [566 manifest_json_ex(741 0, value: ty!(any);567 &value.0,742 1, indent: ty!(string) => Val::Str;568 &ManifestJsonOptions {743 ], {744 Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {745 padding: &indent,569 padding: &indent,746 mtype: ManifestType::Std,570 mtype: ManifestType::Std,747 })?.into()))571 },748 })572 )749}573}750574575#[jrsonnet_macros::builtin]751fn builtin_manifest_yaml_doc(576fn builtin_manifest_yaml_doc(752 context: Context,577 value: Any,753 _loc: &ExprLocation,578 indent_array_in_object: bool,754 args: &ArgsDesc,579 quote_keys: bool,755) -> Result<Val> {580) -> Result<String> {756 parse_args!(context, "manifestYamlDoc", args, 3, [581 manifest_yaml_ex(757 0, value: ty!(any);582 &value.0,758 1, indent_array_in_object: ty!(boolean) => Val::Bool;583 &ManifestYamlOptions {759 2, quote_keys: ty!(boolean) => Val::Bool;760 ], {761 Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {762 padding: " ",584 padding: " ",763 arr_element_padding: if indent_array_in_object { " " } else { "" },585 arr_element_padding: if indent_array_in_object { " " } else { "" },764 quote_keys,586 quote_keys,765 })?.into()))587 },766 })588 )767}589}768590591#[jrsonnet_macros::builtin]769fn builtin_reverse(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {592fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {770 parse_args!(context, "reverse", args, 1, [593 Ok(value.reversed())771 0, value: ty!(array) => Val::Arr;772 ], {773 Ok(Val::Arr(value.reversed()))774 })775}594}776595596#[jrsonnet_macros::builtin]777fn builtin_id(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {597const fn builtin_id(v: Any) -> Result<Any> {778 parse_args!(context, "id", args, 1, [598 Ok(v)779 0, v: ty!(any);780 ], {781 Ok(v)782 })783}599}784600601#[jrsonnet_macros::builtin]785fn builtin_str_replace(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {602fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {786 parse_args!(context, "strReplace", args, 3, [603 Ok(str.replace(&from as &str, &to as &str))787 0, str: ty!(string) => Val::Str;788 1, from: ty!(string) => Val::Str;789 2, to: ty!(string) => Val::Str;790 ], {791 Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))792 })793}604}794605606#[jrsonnet_macros::builtin]795fn builtin_splitlimit(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {607fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either<usize, M1>) -> Result<VecVal> {796 parse_args!(context, "splitLimit", args, 3, [608 Ok(VecVal(match maxsplits {797 0, str: ty!(string) => Val::Str;798 1, c: ty!(char) => Val::Str;609 Either::Left(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),799 2, maxsplits: ty!(number) => Val::Num;800 ], {801 let maxsplits = maxsplits as isize;802 let c = c.chars().next().unwrap();803804 let out: Vec<Val> = if maxsplits == -1 {805 str.split(c).map(|s| Val::Str(s.into())).collect()806 } else {610 Either::Right(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),807 str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect()808 };611 }))809810 Ok(Val::Arr(out.into()))811 })812}612}813613614#[jrsonnet_macros::builtin]814fn builtin_ascii_upper(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {615fn builtin_ascii_upper(str: IStr) -> Result<String> {815 parse_args!(context, "asciiUpper", args, 1, [616 Ok(str.to_ascii_uppercase())816 0, str: ty!(string) => Val::Str;817 ], {818 Ok(Val::Str(str.to_ascii_uppercase().into()))819 })820}617}821618619#[jrsonnet_macros::builtin]822fn builtin_ascii_lower(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {620fn builtin_ascii_lower(str: IStr) -> Result<String> {823 parse_args!(context, "asciiLower", args, 1, [621 Ok(str.to_ascii_lowercase())824 0, str: ty!(string) => Val::Str;825 ], {826 Ok(Val::Str(str.to_ascii_lowercase().into()))827 })828}622}829623624#[jrsonnet_macros::builtin]830fn builtin_member(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {625fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {831 parse_args!(context, "member", args, 2, [626 match arr {832 0, arr: ty!((array | string));833 1, x: ty!(any);834 ], {835 match arr {836 Val::Str(s) => {627 IndexableVal::Str(s) => {837 let x = x.try_cast_str("x should be string")?;628 let x: IStr = IStr::try_from(x.0)?;838 Ok(Val::Bool(!x.is_empty() && s.contains(&*x)))629 Ok(!x.is_empty() && s.contains(&*x))839 }630 }840 Val::Arr(a) => {631 IndexableVal::Arr(a) => {841 for item in a.iter() {632 for item in a.iter() {842 let item = item?;633 let item = item?;843 if equals(&item, &x)? {634 if equals(&item, &x.0)? {844 return Ok(Val::Bool(true));635 return Ok(true);845 }846 }636 }847 Ok(Val::Bool(false))848 }637 }849 _ => unreachable!(),638 Ok(false)850 }639 }851 })640 }852}641}853642643#[jrsonnet_macros::builtin]854fn builtin_count(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {644fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {855 parse_args!(context, "count", args, 2, [645 let mut count = 0;856 0, arr: ty!(array) => Val::Arr;857 1, x: ty!(any);858 ], {859 let mut count = 0;860 for item in arr.iter() {646 for item in arr.iter() {861 let item = item?;647 if equals(&item.0, &v.0)? {862 if equals(&item, &x)? {863 count += 1;648 count += 1;864 }865 }649 }866 Ok(Val::Num(count as f64))650 }867 })651 Ok(count)868}652}869653870pub fn call_builtin(654pub fn call_builtin(crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth1use crate::{1use crate::{2 error::{Error, LocError, Result},2 error::{Error, LocError, Result},3 throw, Context, FuncVal, Val,3 throw, FuncVal, Val,4};4};5use gcmodule::{Cc, Trace};5use gcmodule::{Cc, Trace};6659 Ok(sort_type)59 Ok(sort_type)60}60}616162pub fn sort(ctx: Context, values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {62pub fn sort(values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {63 if values.len() <= 1 {63 if values.len() <= 1 {64 return Ok(values);64 return Ok(values);65 }65 }83 for value in values.iter() {83 for value in values.iter() {84 vk.push((84 vk.push((value.clone(), key_getter.evaluate_values(&[value.clone()])?));85 value.clone(),86 key_getter.evaluate_values(ctx.clone(), &[value.clone()])?,87 ));88 }85 }89 let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;86 let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::convert::TryFrom;21use crate::{3use crate::{2 builtin::std_slice,4 builtin::std_slice,189) -> Result<Option<IStr>> {191) -> Result<Option<IStr>> {190 Ok(match field_name {192 Ok(match field_name {191 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),193 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),192 jrsonnet_parser::FieldName::Dyn(expr) => {194 jrsonnet_parser::FieldName::Dyn(expr) => push_frame(195 &expr.1,196 || "evaluating field name".to_string(),197 || {193 let value = evaluate(context, expr)?;198 let value = evaluate(context, expr)?;194 if matches!(value, Val::Null) {199 if matches!(value, Val::Null) {195 None200 Ok(None)196 } else {201 } else {197 Some(value.try_cast_str("dynamic field name")?)202 Ok(Some(IStr::try_from(value)?))198 }203 }199 }204 },205 )?,200 })206 })201}207}202208208 match specs.get(0) {214 match specs.get(0) {209 None => callback(context)?,215 None => callback(context)?,210 Some(CompSpec::IfSpec(IfSpecData(cond))) => {216 Some(CompSpec::IfSpec(IfSpecData(cond))) => {211 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {217 if bool::try_from(evaluate(context.clone(), cond)?)? {212 evaluate_comp(context, &specs[1..], callback)?218 evaluate_comp(context, &specs[1..], callback)?213 }219 }214 }220 }459 let assertion_result = push_frame(465 let assertion_result = push_frame(460 &value.1,466 &value.1,461 || "assertion condition".to_owned(),467 || "assertion condition".to_owned(),462 || {468 || bool::try_from(evaluate(context.clone(), value)?),463 evaluate(context.clone(), value)?464 .try_cast_bool("assertion condition should be of type `boolean`")465 },466 )?;469 )?;467 if !assertion_result {470 if !assertion_result {468 push_frame(471 push_frame(633 ErrorStmt(e) => push_frame(636 ErrorStmt(e) => push_frame(634 loc,637 loc,635 || "error statement".to_owned(),638 || "error statement".to_owned(),636 || {639 || throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),637 throw!(RuntimeError(638 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,639 ))640 },641 )?,640 )?,642 IfElse {641 IfElse {643 cond,642 cond,647 if push_frame(646 if push_frame(648 loc,647 loc,649 || "if condition".to_owned(),648 || "if condition".to_owned(),650 || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),649 || bool::try_from(evaluate(context.clone(), &cond.0)?),651 )? {650 )? {652 evaluate(context, cond_then)?651 evaluate(context, cond_then)?653 } else {652 } else {crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth1use std::convert::TryInto;21use crate::builtin::std_format;3use crate::builtin::std_format;2use crate::{equals, evaluate, Context, Val};4use crate::{equals, evaluate, Context, Val};46 use Val::*;48 use Val::*;47 match (a, b) {49 match (a, b) {48 (Num(a), Num(b)) => Ok(Num(a % b)),50 (Num(a), Num(b)) => Ok(Num(a % b)),49 (Str(str), vals) => std_format(str.clone(), vals.clone()),51 (Str(str), vals) => std_format(str.clone(), vals.clone())?.try_into(),50 (a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(52 (a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(51 BinaryOpType::Mod,53 BinaryOpType::Mod,52 a.value_type(),54 a.value_type(),crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth141 }141 }142}142}143144#[derive(Clone, Copy)]145pub struct BuiltinParam {146 pub name: &'static str,147 pub has_default: bool,148}149150/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead151///152/// ## Parameters153/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)154/// * `params`: function parameters' definition155/// * `args`: passed function arguments156/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily157pub fn parse_builtin_call<'k>(158 ctx: Context,159 params: &'static [BuiltinParam],160 args: &'k ArgsDesc,161 tailstrict: bool,162) -> Result<GcHashMap<&'k str, LazyVal>> {163 let mut passed_args = GcHashMap::with_capacity(params.len());164 if args.unnamed.len() > params.len() {165 throw!(TooManyArgsFunctionHas(params.len()))166 }167168 let mut filled_args = 0;169170 for (id, arg) in args.unnamed.iter().enumerate() {171 let name = params[id].name;172 passed_args.insert(173 name,174 if tailstrict {175 LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)176 } else {177 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {178 context: ctx.clone(),179 expr: arg.clone(),180 })))181 },182 );183 filled_args += 1;184 }185186 for (name, value) in args.named.iter() {187 // FIXME: O(n) for arg existence check188 if !params.iter().any(|p| p.name == name as &str) {189 throw!(UnknownFunctionParameter((name as &str).to_owned()));190 }191 if passed_args192 .insert(193 name,194 if tailstrict {195 LazyVal::new_resolved(evaluate(ctx.clone(), value)?)196 } else {197 LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {198 context: ctx.clone(),199 expr: value.clone(),200 })))201 },202 )203 .is_some()204 {205 throw!(BindingParameterASecondTime(name.clone()));206 }207 filled_args += 1;208 }209210 if filled_args < params.len() {211 for param in params.iter().filter(|p| p.has_default) {212 if passed_args.contains_key(¶m.name) {213 continue;214 }215 filled_args += 1;216 }217218 // Some args still wasn't filled219 if filled_args != params.len() {220 for param in params.iter().skip(args.unnamed.len()) {221 if !args.named.iter().any(|a| &a.0 as &str == param.name) {222 throw!(FunctionParameterNotBoundInCall(param.name.into()));223 }224 }225 unreachable!();226 }227 }228 Ok(passed_args)229}143230144pub fn parse_function_call_map(231pub fn parse_function_call_map(145 ctx: Context,232 ctx: Context,202}289}203290204pub fn place_args(291pub fn place_args(body_ctx: Context, params: &ParamsDesc, args: &[Val]) -> Result<Context> {205 ctx: Context,206 body_ctx: Option<Context>,207 params: &ParamsDesc,208 args: &[Val],209) -> Result<Context> {210 let mut out = GcHashMap::with_capacity(params.len());292 let mut out = GcHashMap::with_capacity(params.len());211 let mut positioned_args = vec![None; params.0.len()];293 let mut positioned_args = vec![None; params.0.len()];220 let val = if let Some(arg) = &positioned_args[id] {302 let val = if let Some(arg) = &positioned_args[id] {221 (*arg).clone()303 (*arg).clone()222 } else if let Some(default) = &p.1 {304 } else if let Some(default) = &p.1 {223 evaluate(ctx.clone(), default)?305 evaluate(body_ctx.clone(), default)?224 } else {306 } else {225 throw!(FunctionParameterNotBoundInCall(p.0.clone()));307 throw!(FunctionParameterNotBoundInCall(p.0.clone()));226 };308 };227 out.insert(p.0.clone(), LazyVal::new_resolved(val));309 out.insert(p.0.clone(), LazyVal::new_resolved(val));228 }310 }229311230 Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))312 Ok(body_ctx.extend(out, None, None, None))231}313}232314233#[macro_export]315#[macro_export]crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth122 .map(|el| &el.location)122 .map(|el| &el.location)123 .map(|location| {123 .map(|location| {124 use std::fmt::Write;124 use std::fmt::Write;125 #[allow(clippy::option_if_let_else)]125 if let Some(location) = location {126 if let Some(location) = location {126 let mut resolved_path = self.resolver.resolve(&location.0);127 let mut resolved_path = self.resolver.resolve(&location.0);127 // TODO: Process all trace elements first128 // TODO: Process all trace elements firstcrates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterbothno changes
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterbothno changes
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterbothno changes
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth170 }170 }171 }171 }172172173 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {173 pub fn evaluate_values(&self, args: &[Val]) -> Result<Val> {174 match self {174 match self {175 Self::Normal(func) => {175 Self::Normal(func) => {176 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;176 let ctx = place_args(func.ctx.clone(), &func.params, args)?;177 evaluate(ctx, &func.body)177 evaluate(ctx, &func.body)178 }178 }179 Self::Intrinsic(_) => todo!(),179 Self::Intrinsic(_) => todo!(),363 Func(Cc<FuncVal>),363 Func(Cc<FuncVal>),364}364}365365366macro_rules! matches_unwrap {367 ($e: expr, $p: pat, $r: expr) => {368 match $e {369 $p => $r,370 _ => panic!("no match"),371 }372 };373}374impl Val {366impl Val {375 /// Creates `Val::Num` after checking for numeric overflow.367 /// Creates `Val::Num` after checking for numeric overflow.376 /// As numbers are `f64`, we can just check for their finity.368 /// As numbers are `f64`, we can just check for their finity.382 }374 }383 }375 }384376385 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {386 let this_type = self.value_type();387 if this_type != val_type {388 throw!(TypeMismatch(context, vec![val_type], this_type))389 } else {390 Ok(())391 }392 }393 pub fn unwrap_num(self) -> Result<f64> {394 Ok(matches_unwrap!(self, Self::Num(v), v))395 }396 pub fn unwrap_str(self) -> Result<IStr> {397 Ok(matches_unwrap!(self, Self::Str(v), v))398 }399 pub fn unwrap_arr(self) -> Result<ArrValue> {400 Ok(matches_unwrap!(self, Self::Arr(v), v))401 }402 pub fn unwrap_func(self) -> Result<Cc<FuncVal>> {403 Ok(matches_unwrap!(self, Self::Func(v), v))404 }405 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {406 self.assert_type(context, ValType::Bool)?;407 Ok(matches_unwrap!(self, Self::Bool(v), v))408 }409 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {410 self.assert_type(context, ValType::Str)?;411 Ok(matches_unwrap!(self, Self::Str(v), v))412 }413 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {414 self.assert_type(context, ValType::Num)?;415 self.unwrap_num()416 }417 pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {377 pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {418 Ok(match self {378 Ok(match self {419 Val::Null => None,379 Val::Null => None,crates/jrsonnet-macros/Cargo.tomldiffbeforeafterbothno changes
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterbothno changes
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth42 $crate::ComplexValType::Simple($crate::ValType::Func)42 $crate::ComplexValType::Simple($crate::ValType::Func)43 };43 };44 (($($a:tt) |+)) => {{44 (($($a:tt) |+)) => {{45 static CONTENTS: &'static [$crate::ComplexValType] = &[45 static CONTENTS: &'static [&'static $crate::ComplexValType] = &[46 $(ty!($a)),+46 $(&ty!($a)),+47 ];47 ];48 $crate::ComplexValType::UnionRef(CONTENTS)48 $crate::ComplexValType::UnionRef(CONTENTS)49 }};49 }};50 (($($a:tt) &+)) => {{50 (($($a:tt) &+)) => {{51 static CONTENTS: &'static [$crate::ComplexValType] = &[51 static CONTENTS: &'static [&'static $crate::ComplexValType] = &[52 $(ty!($a)),+52 $(&ty!($a)),+53 ];53 ];54 $crate::ComplexValType::SumRef(CONTENTS)54 $crate::ComplexValType::SumRef(CONTENTS)55 }};55 }};66 assert_eq!(66 assert_eq!(67 ty!((string | number)),67 ty!((string | number)),68 ComplexValType::UnionRef(&[68 ComplexValType::UnionRef(&[69 ComplexValType::Simple(ValType::Str),69 &ComplexValType::Simple(ValType::Str),70 ComplexValType::Simple(ValType::Num)70 &ComplexValType::Simple(ValType::Num)71 ])71 ])72 );72 );73 assert_eq!(73 assert_eq!(124 ArrayRef(&'static ComplexValType),124 ArrayRef(&'static ComplexValType),125 ObjectRef(&'static [(&'static str, ComplexValType)]),125 ObjectRef(&'static [(&'static str, ComplexValType)]),126 Union(Vec<ComplexValType>),126 Union(Vec<ComplexValType>),127 UnionRef(&'static [ComplexValType]),127 UnionRef(&'static [&'static ComplexValType]),128 Sum(Vec<ComplexValType>),128 Sum(Vec<ComplexValType>),129 SumRef(&'static [ComplexValType]),129 SumRef(&'static [&'static ComplexValType]),130}130}131131132impl From<ValType> for ComplexValType {132impl From<ValType> for ComplexValType {135 }135 }136}136}137137138fn write_union(138fn write_union<'i>(139 f: &mut std::fmt::Formatter<'_>,139 f: &mut std::fmt::Formatter<'_>,140 is_union: bool,140 is_union: bool,141 union: &[ComplexValType],141 union: impl Iterator<Item = &'i ComplexValType>,142) -> std::fmt::Result {142) -> std::fmt::Result {143 for (i, v) in union.iter().enumerate() {143 for (i, v) in union.enumerate() {144 let should_add_braces =144 let should_add_braces =145 matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);145 matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);146 if i != 0 {146 if i != 0 {190 }190 }191 write!(f, "}}")?;191 write!(f, "}}")?;192 }192 }193 ComplexValType::Union(v) => write_union(f, true, v)?,193 ComplexValType::Union(v) => write_union(f, true, v.iter())?,194 ComplexValType::UnionRef(v) => write_union(f, true, v)?,194 ComplexValType::UnionRef(v) => write_union(f, true, v.iter().map(|v| *v))?,195 ComplexValType::Sum(v) => write_union(f, false, v)?,195 ComplexValType::Sum(v) => write_union(f, false, v.iter())?,196 ComplexValType::SumRef(v) => write_union(f, false, v)?,196 ComplexValType::SumRef(v) => write_union(f, false, v.iter().map(|v| *v))?,197 };197 };198 Ok(())198 Ok(())199 }199 }