difftreelog
feat implement argument parsing with proc macro
in: master
17 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -49,8 +49,8 @@
};
// Release memory occipied by arguments passed
unsafe {
- CString::from_raw(base);
- CString::from_raw(rel);
+ let _ = CString::from_raw(base);
+ let _ = CString::from_raw(rel);
}
let result_raw = unsafe { CStr::from_ptr(result_ptr) };
let result_str = result_raw.to_str().unwrap();
@@ -64,7 +64,7 @@
let found_here_raw = unsafe { CStr::from_ptr(found_here) };
let found_here_buf = PathBuf::from(found_here_raw.to_str().unwrap());
unsafe {
- CString::from_raw(found_here);
+ let _ = CString::from_raw(found_here);
}
let mut out = self.out.borrow_mut();
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -3,10 +3,11 @@
error::{Error, LocError},
gc::TraceBox,
native::{NativeCallback, NativeCallbackHandler},
- EvaluationState, Val,
+ EvaluationState, IStr, Val,
};
use jrsonnet_parser::{Param, ParamsDesc};
use std::{
+ convert::TryFrom,
ffi::{c_void, CStr},
os::raw::{c_char, c_int},
path::Path,
@@ -45,7 +46,7 @@
if success == 1 {
Ok(v)
} else {
- let e = v.try_cast_str("native error").expect("error msg");
+ let e = IStr::try_from(v).expect("error msg");
Err(Error::RuntimeError(e).into())
}
}
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -23,6 +23,7 @@
jrsonnet-parser = { path = "../jrsonnet-parser", version = "0.4.2" }
jrsonnet-stdlib = { path = "../jrsonnet-stdlib", version = "0.4.2" }
jrsonnet-types = { path = "../jrsonnet-types", version = "0.4.2" }
+jrsonnet-macros = { path = "../jrsonnet-macros", version = "0.4.2" }
pathdiff = "0.2.0"
md5 = "0.7.0"
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};5use gcmodule::Trace;6use jrsonnet_interner::IStr;7use jrsonnet_types::ValType;8use thiserror::Error;910#[derive(Debug, Clone, Error, Trace)]11pub enum FormatError {12 #[error("truncated format code")]13 TruncatedFormatCode,14 #[error("unrecognized conversion type: {0}")]15 UnrecognizedConversionType(char),1617 #[error("not enough values")]18 NotEnoughValues,1920 #[error("cannot use * width with object")]21 CannotUseStarWidthWithObject,22 #[error("mapping keys required")]23 MappingKeysRequired,24 #[error("no such format field: {0}")]25 NoSuchFormatField(IStr),26}2728impl From<FormatError> for LocError {29 fn from(e: FormatError) -> Self {30 Self::new(Format(e))31 }32}3334use FormatError::*;3536type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;3738pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {39 if str.is_empty() {40 return Err(TruncatedFormatCode);41 }42 let bytes = str.as_bytes();43 if bytes[0] == b'(' {44 let mut i = 1;45 while i < bytes.len() {46 if bytes[i] == b')' {47 return Ok((&str[1..i as usize], &str[i as usize + 1..]));48 }49 i += 1;50 }51 Err(TruncatedFormatCode)52 } else {53 Ok(("", str))54 }55}5657#[cfg(test)]58pub mod tests_key {59 use super::*;6061 #[test]62 fn parse_key() {63 assert_eq!(64 try_parse_mapping_key("(hello ) world").unwrap(),65 ("hello ", " world")66 );67 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));68 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));69 assert_eq!(70 try_parse_mapping_key(" () world").unwrap(),71 ("", " () world")72 );73 }7475 #[test]76 #[should_panic]77 fn parse_key_missing_start() {78 try_parse_mapping_key("").unwrap();79 }8081 #[test]82 #[should_panic]83 fn parse_key_missing_end() {84 try_parse_mapping_key("( ").unwrap();85 }86}8788#[derive(Default, Debug)]89pub struct CFlags {90 pub alt: bool,91 pub zero: bool,92 pub left: bool,93 pub blank: bool,94 pub sign: bool,95}9697pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {98 if str.is_empty() {99 return Err(TruncatedFormatCode);100 }101 let bytes = str.as_bytes();102 let mut i = 0;103 let mut out = CFlags::default();104 loop {105 if bytes.len() == i {106 return Err(TruncatedFormatCode);107 }108 match bytes[i] {109 b'#' => out.alt = true,110 b'0' => out.zero = true,111 b'-' => out.left = true,112 b' ' => out.blank = true,113 b'+' => out.sign = true,114 _ => break,115 }116 i += 1;117 }118 Ok((out, &str[i..]))119}120121#[derive(Debug, PartialEq)]122pub enum Width {123 Star,124 Fixed(usize),125}126pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {127 if str.is_empty() {128 return Err(TruncatedFormatCode);129 }130 let bytes = str.as_bytes();131 if bytes[0] == b'*' {132 return Ok((Width::Star, &str[1..]));133 }134 let mut out: usize = 0;135 let mut digits = 0;136 while let Some(digit) = (bytes[digits] as char).to_digit(10) {137 out *= 10;138 out += digit as usize;139 digits += 1;140 if digits == bytes.len() {141 return Err(TruncatedFormatCode);142 }143 }144 Ok((Width::Fixed(out), &str[digits..]))145}146147pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {148 if str.is_empty() {149 return Err(TruncatedFormatCode);150 }151 let bytes = str.as_bytes();152 if bytes[0] == b'.' {153 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))154 } else {155 Ok((None, str))156 }157}158159// Only skips160pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {161 if str.is_empty() {162 return Err(TruncatedFormatCode);163 }164 let bytes = str.as_bytes();165 let mut idx = 0;166 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {167 idx += 1;168 if bytes.len() == idx {169 return Err(TruncatedFormatCode);170 }171 }172 Ok(((), &str[idx..]))173}174175#[derive(Debug, PartialEq)]176pub enum ConvTypeV {177 Decimal,178 Octal,179 Hexadecimal,180 Scientific,181 Float,182 Shorter,183 Char,184 String,185 Percent,186}187pub struct ConvType {188 v: ConvTypeV,189 caps: bool,190}191192pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {193 if str.is_empty() {194 return Err(TruncatedFormatCode);195 }196197 let code = str.as_bytes()[0];198 let v: (ConvTypeV, bool) = match code {199 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),200 b'o' => (ConvTypeV::Octal, false),201 b'x' => (ConvTypeV::Hexadecimal, false),202 b'X' => (ConvTypeV::Hexadecimal, true),203 b'e' => (ConvTypeV::Scientific, false),204 b'E' => (ConvTypeV::Scientific, true),205 b'f' => (ConvTypeV::Float, false),206 b'F' => (ConvTypeV::Float, true),207 b'g' => (ConvTypeV::Shorter, false),208 b'G' => (ConvTypeV::Shorter, true),209 b'c' => (ConvTypeV::Char, false),210 b's' => (ConvTypeV::String, false),211 b'%' => (ConvTypeV::Percent, false),212 c => return Err(UnrecognizedConversionType(c as char)),213 };214215 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))216}217218#[derive(Debug)]219pub struct Code<'s> {220 mkey: &'s str,221 cflags: CFlags,222 width: Width,223 precision: Option<Width>,224 convtype: ConvTypeV,225 caps: bool,226}227pub fn parse_code(str: &str) -> ParseResult<Code> {228 if str.is_empty() {229 return Err(TruncatedFormatCode);230 }231 let (mkey, str) = try_parse_mapping_key(str)?;232 let (cflags, str) = try_parse_cflags(str)?;233 let (width, str) = try_parse_field_width(str)?;234 let (precision, str) = try_parse_precision(str)?;235 let (_, str) = try_parse_length_modifier(str)?;236 let (convtype, str) = parse_conversion_type(str)?;237238 Ok((239 Code {240 mkey,241 cflags,242 width,243 precision,244 convtype: convtype.v,245 caps: convtype.caps,246 },247 str,248 ))249}250251#[derive(Debug)]252pub enum Element<'s> {253 String(&'s str),254 Code(Code<'s>),255}256pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {257 let mut bytes = str.as_bytes();258 let mut out = vec![];259 let mut offset = 0;260261 loop {262 while offset != bytes.len() && bytes[offset] != b'%' {263 offset += 1;264 }265 if offset != 0 {266 out.push(Element::String(&str[0..offset]));267 }268 if offset == bytes.len() {269 return Ok(out);270 }271 str = &str[offset + 1..];272 let (code, nstr) = parse_code(str)?;273 str = nstr;274 bytes = str.as_bytes();275 offset = 0;276277 out.push(Element::Code(code))278 }279}280281const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";282283#[inline]284pub fn render_integer(285 out: &mut String,286 iv: i64,287 padding: usize,288 precision: usize,289 blank: bool,290 sign: bool,291 radix: i64,292 prefix: &str,293 caps: bool,294) {295 // Digit char indexes in reverse order, i.e296 // for radix = 16 and n = 12f: [15, 2, 1]297 let digits = if iv == 0 {298 vec![0u8]299 } else {300 let mut v = iv.abs();301 let mut nums = Vec::with_capacity(1);302 while v > 0 {303 nums.push((v % radix) as u8);304 v /= radix;305 }306 nums307 };308 let neg = iv < 0;309 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });310 let zp2 = zp311 .max(precision)312 .saturating_sub(prefix.len() + digits.len());313314 if neg {315 out.push('-')316 } else if sign {317 out.push('+');318 } else if blank {319 out.push(' ');320 }321322 out.reserve(zp2);323 for _ in 0..zp2 {324 out.push('0');325 }326 out.push_str(prefix);327328 for digit in digits.into_iter().rev() {329 let ch = NUMBERS[digit as usize] as char;330 out.push(if caps { ch.to_ascii_uppercase() } else { ch });331 }332}333334pub fn render_decimal(335 out: &mut String,336 iv: i64,337 padding: usize,338 precision: usize,339 blank: bool,340 sign: bool,341) {342 render_integer(out, iv, padding, precision, blank, sign, 10, "", false)343}344pub fn render_octal(345 out: &mut String,346 iv: i64,347 padding: usize,348 precision: usize,349 alt: bool,350 blank: bool,351 sign: bool,352) {353 render_integer(354 out,355 iv,356 padding,357 precision,358 blank,359 sign,360 8,361 if alt && iv != 0 { "0" } else { "" },362 false,363 )364}365pub fn render_hexadecimal(366 out: &mut String,367 iv: i64,368 padding: usize,369 precision: usize,370 alt: bool,371 blank: bool,372 sign: bool,373 caps: bool,374) {375 render_integer(376 out,377 iv,378 padding,379 precision,380 blank,381 sign,382 16,383 match (alt, caps) {384 (true, true) => "0X",385 (true, false) => "0x",386 (false, _) => "",387 },388 caps,389 )390}391392pub fn render_float(393 out: &mut String,394 n: f64,395 mut padding: usize,396 precision: usize,397 blank: bool,398 sign: bool,399 ensure_pt: bool,400 trailing: bool,401) {402 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };403 padding = padding.saturating_sub(dot_size + precision);404 render_decimal(out, n.floor() as i64, padding, 0, blank, sign);405 if precision == 0 {406 if ensure_pt {407 out.push('.');408 }409 return;410 }411 let frac = n412 .fract()413 .mul_add(10.0_f64.powf(precision as f64), 0.5)414 .floor();415 if trailing || frac > 0.0 {416 out.push('.');417 let mut frac_str = String::new();418 render_decimal(&mut frac_str, frac as i64, precision, 0, false, false);419 let mut trim = frac_str.len();420 if !trailing {421 for b in frac_str.as_bytes().iter().rev() {422 if *b == b'0' {423 trim -= 1;424 }425 }426 }427 out.push_str(&frac_str[..trim]);428 } else if ensure_pt {429 out.push('.');430 }431}432433pub fn render_float_sci(434 out: &mut String,435 n: f64,436 mut padding: usize,437 precision: usize,438 blank: bool,439 sign: bool,440 ensure_pt: bool,441 trailing: bool,442 caps: bool,443) {444 let exponent = n.log10().floor();445 let mantissa = if exponent as i16 == -324 {446 n * 10.0 / 10.0_f64.powf(exponent + 1.0)447 } else {448 n / 10.0_f64.powf(exponent)449 };450 let mut exponent_str = String::new();451 render_decimal(&mut exponent_str, exponent as i64, 3, 0, false, true);452453 // +1 for e454 padding = padding.saturating_sub(exponent_str.len() + 1);455456 render_float(457 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,458 );459 out.push(if caps { 'E' } else { 'e' });460 out.push_str(&exponent_str);461}462463pub fn format_code(464 out: &mut String,465 value: &Val,466 code: &Code,467 width: usize,468 precision: Option<usize>,469) -> Result<()> {470 let clfags = &code.cflags;471 let (fpprec, iprec) = match precision {472 Some(v) => (v, v),473 None => (6, 0),474 };475 let padding = if clfags.zero && !clfags.left {476 width477 } else {478 0479 };480481 // TODO: If left padded, can optimize by writing directly to out482 let mut tmp_out = String::new();483484 match code.convtype {485 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),486 ConvTypeV::Decimal => {487 let value = value.clone().try_cast_num("%d/%u/%i requires number")?;488 render_decimal(489 &mut tmp_out,490 value as i64,491 padding,492 iprec,493 clfags.blank,494 clfags.sign,495 );496 }497 ConvTypeV::Octal => {498 let value = value.clone().try_cast_num("%o requires number")?;499 render_octal(500 &mut tmp_out,501 value as i64,502 padding,503 iprec,504 clfags.alt,505 clfags.blank,506 clfags.sign,507 );508 }509 ConvTypeV::Hexadecimal => {510 let value = value.clone().try_cast_num("%x/%X requires number")?;511 render_hexadecimal(512 &mut tmp_out,513 value as i64,514 padding,515 iprec,516 clfags.alt,517 clfags.blank,518 clfags.sign,519 code.caps,520 );521 }522 ConvTypeV::Scientific => {523 let value = value.clone().try_cast_num("%e/%E requires number")?;524 render_float_sci(525 &mut tmp_out,526 value,527 padding,528 fpprec,529 clfags.blank,530 clfags.sign,531 clfags.alt,532 true,533 code.caps,534 );535 }536 ConvTypeV::Float => {537 let value = value.clone().try_cast_num("%e/%E requires number")?;538 render_float(539 &mut tmp_out,540 value,541 padding,542 fpprec,543 clfags.blank,544 clfags.sign,545 clfags.alt,546 true,547 );548 }549 ConvTypeV::Shorter => {550 let value = value.clone().try_cast_num("%g/%G requires number")?;551 let exponent = value.log10().floor();552 if exponent < -4.0 || exponent >= fpprec as f64 {553 render_float_sci(554 &mut tmp_out,555 value,556 padding,557 fpprec - 1,558 clfags.blank,559 clfags.sign,560 clfags.alt,561 clfags.alt,562 code.caps,563 );564 } else {565 let digits_before_pt = 1.max(exponent as usize + 1);566 render_float(567 &mut tmp_out,568 value,569 padding,570 fpprec - digits_before_pt,571 clfags.blank,572 clfags.sign,573 clfags.alt,574 clfags.alt,575 );576 }577 }578 ConvTypeV::Char => match value.clone() {579 Val::Num(n) => tmp_out.push(580 std::char::from_u32(n as u32)581 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,582 ),583 Val::Str(s) => {584 if s.chars().count() != 1 {585 throw!(RuntimeError(586 format!("%c expected 1 char string, got {}", s.chars().count()).into(),587 ));588 }589 tmp_out.push_str(&s);590 }591 _ => {592 throw!(TypeMismatch(593 "%c requires number/string",594 vec![ValType::Num, ValType::Str],595 value.value_type(),596 ));597 }598 },599 ConvTypeV::Percent => tmp_out.push('%'),600 };601602 let padding = width.saturating_sub(tmp_out.len());603604 if !clfags.left {605 for _ in 0..padding {606 out.push(' ');607 }608 }609 out.push_str(&tmp_out);610 if clfags.left {611 for _ in 0..padding {612 out.push(' ');613 }614 }615616 Ok(())617}618619pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {620 let codes = parse_codes(str)?;621 let mut out = String::new();622623 for code in codes {624 match code {625 Element::String(s) => {626 out.push_str(s);627 }628 Element::Code(c) => {629 let width = match c.width {630 Width::Star => {631 if values.is_empty() {632 throw!(NotEnoughValues);633 }634 let value = &values[0];635 values = &values[1..];636 value.clone().try_cast_num("field width")? as usize637 }638 Width::Fixed(n) => n,639 };640 let precision = match c.precision {641 Some(Width::Star) => {642 if values.is_empty() {643 throw!(NotEnoughValues);644 }645 let value = &values[0];646 values = &values[1..];647 Some(value.clone().try_cast_num("field precision")? as usize)648 }649 Some(Width::Fixed(n)) => Some(n),650 None => None,651 };652653 // %% should not consume a value654 let value = if c.convtype == ConvTypeV::Percent {655 &Val::Null656 } else {657 if values.is_empty() {658 throw!(NotEnoughValues);659 }660 let value = &values[0];661 values = &values[1..];662 value663 };664665 format_code(&mut out, value, &c, width, precision)?;666 }667 }668 }669670 Ok(out)671}672673pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {674 let codes = parse_codes(str)?;675 let mut out = String::new();676677 for code in codes {678 match code {679 Element::String(s) => {680 out.push_str(s);681 }682 Element::Code(c) => {683 // TODO: Operate on ref684 let f: IStr = c.mkey.into();685 let width = match c.width {686 Width::Star => {687 throw!(CannotUseStarWidthWithObject);688 }689 Width::Fixed(n) => n,690 };691 let precision = match c.precision {692 Some(Width::Star) => {693 throw!(CannotUseStarWidthWithObject);694 }695 Some(Width::Fixed(n)) => Some(n),696 None => None,697 };698699 let value = if c.convtype == ConvTypeV::Percent {700 Val::Null701 } else {702 if f.is_empty() {703 throw!(MappingKeysRequired);704 }705 if let Some(v) = values.get(f.clone())? {706 v707 } else {708 throw!(NoSuchFormatField(f));709 }710 };711712 format_code(&mut out, &value, &c, width, precision)?;713 }714 }715 }716717 Ok(out)718}719720#[cfg(test)]721pub mod test_format {722 use super::*;723724 #[test]725 fn parse() {726 assert_eq!(727 parse_codes(728 "How much error budget is left looking at our %.3f%% availability gurantees?"729 )730 .unwrap()731 .len(),732 4733 );734 }735736 #[test]737 fn octals() {738 assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");739 assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");740 assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), " 10");741 assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");742 assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");743 assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");744 assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10 ");745 assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");746 assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");747 }748749 #[test]750 fn percent_doesnt_consumes_values() {751 assert_eq!(752 format_arr(753 "How much error budget is left looking at our %.3f%% availability gurantees?",754 &[Val::Num(4.0)]755 )756 .unwrap(),757 "How much error budget is left looking at our 4.000% availability gurantees?"758 );759 }760}1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use crate::{error::Error::*, throw, LocError, ObjValue, Result, Val};5use gcmodule::Trace;6use jrsonnet_interner::IStr;7use jrsonnet_types::ValType;8use std::convert::TryFrom;9use thiserror::Error;1011#[derive(Debug, Clone, Error, Trace)]12pub enum FormatError {13 #[error("truncated format code")]14 TruncatedFormatCode,15 #[error("unrecognized conversion type: {0}")]16 UnrecognizedConversionType(char),1718 #[error("not enough values")]19 NotEnoughValues,2021 #[error("cannot use * width with object")]22 CannotUseStarWidthWithObject,23 #[error("mapping keys required")]24 MappingKeysRequired,25 #[error("no such format field: {0}")]26 NoSuchFormatField(IStr),27}2829impl From<FormatError> for LocError {30 fn from(e: FormatError) -> Self {31 Self::new(Format(e))32 }33}3435use FormatError::*;3637type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;3839pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {40 if str.is_empty() {41 return Err(TruncatedFormatCode);42 }43 let bytes = str.as_bytes();44 if bytes[0] == b'(' {45 let mut i = 1;46 while i < bytes.len() {47 if bytes[i] == b')' {48 return Ok((&str[1..i as usize], &str[i as usize + 1..]));49 }50 i += 1;51 }52 Err(TruncatedFormatCode)53 } else {54 Ok(("", str))55 }56}5758#[cfg(test)]59pub mod tests_key {60 use super::*;6162 #[test]63 fn parse_key() {64 assert_eq!(65 try_parse_mapping_key("(hello ) world").unwrap(),66 ("hello ", " world")67 );68 assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));69 assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));70 assert_eq!(71 try_parse_mapping_key(" () world").unwrap(),72 ("", " () world")73 );74 }7576 #[test]77 #[should_panic]78 fn parse_key_missing_start() {79 try_parse_mapping_key("").unwrap();80 }8182 #[test]83 #[should_panic]84 fn parse_key_missing_end() {85 try_parse_mapping_key("( ").unwrap();86 }87}8889#[derive(Default, Debug)]90pub struct CFlags {91 pub alt: bool,92 pub zero: bool,93 pub left: bool,94 pub blank: bool,95 pub sign: bool,96}9798pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {99 if str.is_empty() {100 return Err(TruncatedFormatCode);101 }102 let bytes = str.as_bytes();103 let mut i = 0;104 let mut out = CFlags::default();105 loop {106 if bytes.len() == i {107 return Err(TruncatedFormatCode);108 }109 match bytes[i] {110 b'#' => out.alt = true,111 b'0' => out.zero = true,112 b'-' => out.left = true,113 b' ' => out.blank = true,114 b'+' => out.sign = true,115 _ => break,116 }117 i += 1;118 }119 Ok((out, &str[i..]))120}121122#[derive(Debug, PartialEq)]123pub enum Width {124 Star,125 Fixed(usize),126}127pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {128 if str.is_empty() {129 return Err(TruncatedFormatCode);130 }131 let bytes = str.as_bytes();132 if bytes[0] == b'*' {133 return Ok((Width::Star, &str[1..]));134 }135 let mut out: usize = 0;136 let mut digits = 0;137 while let Some(digit) = (bytes[digits] as char).to_digit(10) {138 out *= 10;139 out += digit as usize;140 digits += 1;141 if digits == bytes.len() {142 return Err(TruncatedFormatCode);143 }144 }145 Ok((Width::Fixed(out), &str[digits..]))146}147148pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {149 if str.is_empty() {150 return Err(TruncatedFormatCode);151 }152 let bytes = str.as_bytes();153 if bytes[0] == b'.' {154 try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))155 } else {156 Ok((None, str))157 }158}159160// Only skips161pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {162 if str.is_empty() {163 return Err(TruncatedFormatCode);164 }165 let bytes = str.as_bytes();166 let mut idx = 0;167 while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {168 idx += 1;169 if bytes.len() == idx {170 return Err(TruncatedFormatCode);171 }172 }173 Ok(((), &str[idx..]))174}175176#[derive(Debug, PartialEq)]177pub enum ConvTypeV {178 Decimal,179 Octal,180 Hexadecimal,181 Scientific,182 Float,183 Shorter,184 Char,185 String,186 Percent,187}188pub struct ConvType {189 v: ConvTypeV,190 caps: bool,191}192193pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {194 if str.is_empty() {195 return Err(TruncatedFormatCode);196 }197198 let code = str.as_bytes()[0];199 let v: (ConvTypeV, bool) = match code {200 b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),201 b'o' => (ConvTypeV::Octal, false),202 b'x' => (ConvTypeV::Hexadecimal, false),203 b'X' => (ConvTypeV::Hexadecimal, true),204 b'e' => (ConvTypeV::Scientific, false),205 b'E' => (ConvTypeV::Scientific, true),206 b'f' => (ConvTypeV::Float, false),207 b'F' => (ConvTypeV::Float, true),208 b'g' => (ConvTypeV::Shorter, false),209 b'G' => (ConvTypeV::Shorter, true),210 b'c' => (ConvTypeV::Char, false),211 b's' => (ConvTypeV::String, false),212 b'%' => (ConvTypeV::Percent, false),213 c => return Err(UnrecognizedConversionType(c as char)),214 };215216 Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))217}218219#[derive(Debug)]220pub struct Code<'s> {221 mkey: &'s str,222 cflags: CFlags,223 width: Width,224 precision: Option<Width>,225 convtype: ConvTypeV,226 caps: bool,227}228pub fn parse_code(str: &str) -> ParseResult<Code> {229 if str.is_empty() {230 return Err(TruncatedFormatCode);231 }232 let (mkey, str) = try_parse_mapping_key(str)?;233 let (cflags, str) = try_parse_cflags(str)?;234 let (width, str) = try_parse_field_width(str)?;235 let (precision, str) = try_parse_precision(str)?;236 let (_, str) = try_parse_length_modifier(str)?;237 let (convtype, str) = parse_conversion_type(str)?;238239 Ok((240 Code {241 mkey,242 cflags,243 width,244 precision,245 convtype: convtype.v,246 caps: convtype.caps,247 },248 str,249 ))250}251252#[derive(Debug)]253pub enum Element<'s> {254 String(&'s str),255 Code(Code<'s>),256}257pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {258 let mut bytes = str.as_bytes();259 let mut out = vec![];260 let mut offset = 0;261262 loop {263 while offset != bytes.len() && bytes[offset] != b'%' {264 offset += 1;265 }266 if offset != 0 {267 out.push(Element::String(&str[0..offset]));268 }269 if offset == bytes.len() {270 return Ok(out);271 }272 str = &str[offset + 1..];273 let (code, nstr) = parse_code(str)?;274 str = nstr;275 bytes = str.as_bytes();276 offset = 0;277278 out.push(Element::Code(code))279 }280}281282const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";283284#[inline]285pub fn render_integer(286 out: &mut String,287 iv: i64,288 padding: usize,289 precision: usize,290 blank: bool,291 sign: bool,292 radix: i64,293 prefix: &str,294 caps: bool,295) {296 // Digit char indexes in reverse order, i.e297 // for radix = 16 and n = 12f: [15, 2, 1]298 let digits = if iv == 0 {299 vec![0u8]300 } else {301 let mut v = iv.abs();302 let mut nums = Vec::with_capacity(1);303 while v > 0 {304 nums.push((v % radix) as u8);305 v /= radix;306 }307 nums308 };309 let neg = iv < 0;310 let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });311 let zp2 = zp312 .max(precision)313 .saturating_sub(prefix.len() + digits.len());314315 if neg {316 out.push('-')317 } else if sign {318 out.push('+');319 } else if blank {320 out.push(' ');321 }322323 out.reserve(zp2);324 for _ in 0..zp2 {325 out.push('0');326 }327 out.push_str(prefix);328329 for digit in digits.into_iter().rev() {330 let ch = NUMBERS[digit as usize] as char;331 out.push(if caps { ch.to_ascii_uppercase() } else { ch });332 }333}334335pub fn render_decimal(336 out: &mut String,337 iv: i64,338 padding: usize,339 precision: usize,340 blank: bool,341 sign: bool,342) {343 render_integer(out, iv, padding, precision, blank, sign, 10, "", false)344}345pub fn render_octal(346 out: &mut String,347 iv: i64,348 padding: usize,349 precision: usize,350 alt: bool,351 blank: bool,352 sign: bool,353) {354 render_integer(355 out,356 iv,357 padding,358 precision,359 blank,360 sign,361 8,362 if alt && iv != 0 { "0" } else { "" },363 false,364 )365}366pub fn render_hexadecimal(367 out: &mut String,368 iv: i64,369 padding: usize,370 precision: usize,371 alt: bool,372 blank: bool,373 sign: bool,374 caps: bool,375) {376 render_integer(377 out,378 iv,379 padding,380 precision,381 blank,382 sign,383 16,384 match (alt, caps) {385 (true, true) => "0X",386 (true, false) => "0x",387 (false, _) => "",388 },389 caps,390 )391}392393pub fn render_float(394 out: &mut String,395 n: f64,396 mut padding: usize,397 precision: usize,398 blank: bool,399 sign: bool,400 ensure_pt: bool,401 trailing: bool,402) {403 let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };404 padding = padding.saturating_sub(dot_size + precision);405 render_decimal(out, n.floor() as i64, padding, 0, blank, sign);406 if precision == 0 {407 if ensure_pt {408 out.push('.');409 }410 return;411 }412 let frac = n413 .fract()414 .mul_add(10.0_f64.powf(precision as f64), 0.5)415 .floor();416 if trailing || frac > 0.0 {417 out.push('.');418 let mut frac_str = String::new();419 render_decimal(&mut frac_str, frac as i64, precision, 0, false, false);420 let mut trim = frac_str.len();421 if !trailing {422 for b in frac_str.as_bytes().iter().rev() {423 if *b == b'0' {424 trim -= 1;425 }426 }427 }428 out.push_str(&frac_str[..trim]);429 } else if ensure_pt {430 out.push('.');431 }432}433434pub fn render_float_sci(435 out: &mut String,436 n: f64,437 mut padding: usize,438 precision: usize,439 blank: bool,440 sign: bool,441 ensure_pt: bool,442 trailing: bool,443 caps: bool,444) {445 let exponent = n.log10().floor();446 let mantissa = if exponent as i16 == -324 {447 n * 10.0 / 10.0_f64.powf(exponent + 1.0)448 } else {449 n / 10.0_f64.powf(exponent)450 };451 let mut exponent_str = String::new();452 render_decimal(&mut exponent_str, exponent as i64, 3, 0, false, true);453454 // +1 for e455 padding = padding.saturating_sub(exponent_str.len() + 1);456457 render_float(458 out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,459 );460 out.push(if caps { 'E' } else { 'e' });461 out.push_str(&exponent_str);462}463464pub fn format_code(465 out: &mut String,466 value: &Val,467 code: &Code,468 width: usize,469 precision: Option<usize>,470) -> Result<()> {471 let clfags = &code.cflags;472 let (fpprec, iprec) = match precision {473 Some(v) => (v, v),474 None => (6, 0),475 };476 let padding = if clfags.zero && !clfags.left {477 width478 } else {479 0480 };481482 // TODO: If left padded, can optimize by writing directly to out483 let mut tmp_out = String::new();484485 match code.convtype {486 ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),487 ConvTypeV::Decimal => {488 let value = f64::try_from(value.clone())?;489 render_decimal(490 &mut tmp_out,491 value as i64,492 padding,493 iprec,494 clfags.blank,495 clfags.sign,496 );497 }498 ConvTypeV::Octal => {499 let value = f64::try_from(value.clone())?;500 render_octal(501 &mut tmp_out,502 value as i64,503 padding,504 iprec,505 clfags.alt,506 clfags.blank,507 clfags.sign,508 );509 }510 ConvTypeV::Hexadecimal => {511 let value = f64::try_from(value.clone())?;512 render_hexadecimal(513 &mut tmp_out,514 value as i64,515 padding,516 iprec,517 clfags.alt,518 clfags.blank,519 clfags.sign,520 code.caps,521 );522 }523 ConvTypeV::Scientific => {524 let value = f64::try_from(value.clone())?;525 render_float_sci(526 &mut tmp_out,527 value,528 padding,529 fpprec,530 clfags.blank,531 clfags.sign,532 clfags.alt,533 true,534 code.caps,535 );536 }537 ConvTypeV::Float => {538 let value = f64::try_from(value.clone())?;539 render_float(540 &mut tmp_out,541 value,542 padding,543 fpprec,544 clfags.blank,545 clfags.sign,546 clfags.alt,547 true,548 );549 }550 ConvTypeV::Shorter => {551 let value = f64::try_from(value.clone())?;552 let exponent = value.log10().floor();553 if exponent < -4.0 || exponent >= fpprec as f64 {554 render_float_sci(555 &mut tmp_out,556 value,557 padding,558 fpprec - 1,559 clfags.blank,560 clfags.sign,561 clfags.alt,562 clfags.alt,563 code.caps,564 );565 } else {566 let digits_before_pt = 1.max(exponent as usize + 1);567 render_float(568 &mut tmp_out,569 value,570 padding,571 fpprec - digits_before_pt,572 clfags.blank,573 clfags.sign,574 clfags.alt,575 clfags.alt,576 );577 }578 }579 ConvTypeV::Char => match value.clone() {580 Val::Num(n) => tmp_out.push(581 std::char::from_u32(n as u32)582 .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,583 ),584 Val::Str(s) => {585 if s.chars().count() != 1 {586 throw!(RuntimeError(587 format!("%c expected 1 char string, got {}", s.chars().count()).into(),588 ));589 }590 tmp_out.push_str(&s);591 }592 _ => {593 throw!(TypeMismatch(594 "%c requires number/string",595 vec![ValType::Num, ValType::Str],596 value.value_type(),597 ));598 }599 },600 ConvTypeV::Percent => tmp_out.push('%'),601 };602603 let padding = width.saturating_sub(tmp_out.len());604605 if !clfags.left {606 for _ in 0..padding {607 out.push(' ');608 }609 }610 out.push_str(&tmp_out);611 if clfags.left {612 for _ in 0..padding {613 out.push(' ');614 }615 }616617 Ok(())618}619620pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {621 let codes = parse_codes(str)?;622 let mut out = String::new();623624 for code in codes {625 match code {626 Element::String(s) => {627 out.push_str(s);628 }629 Element::Code(c) => {630 let width = match c.width {631 Width::Star => {632 if values.is_empty() {633 throw!(NotEnoughValues);634 }635 let value = &values[0];636 values = &values[1..];637 usize::try_from(value.clone())?638 }639 Width::Fixed(n) => n,640 };641 let precision = match c.precision {642 Some(Width::Star) => {643 if values.is_empty() {644 throw!(NotEnoughValues);645 }646 let value = &values[0];647 values = &values[1..];648 Some(usize::try_from(value.clone())?)649 }650 Some(Width::Fixed(n)) => Some(n),651 None => None,652 };653654 // %% should not consume a value655 let value = if c.convtype == ConvTypeV::Percent {656 &Val::Null657 } else {658 if values.is_empty() {659 throw!(NotEnoughValues);660 }661 let value = &values[0];662 values = &values[1..];663 value664 };665666 format_code(&mut out, value, &c, width, precision)?;667 }668 }669 }670671 Ok(out)672}673674pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {675 let codes = parse_codes(str)?;676 let mut out = String::new();677678 for code in codes {679 match code {680 Element::String(s) => {681 out.push_str(s);682 }683 Element::Code(c) => {684 // TODO: Operate on ref685 let f: IStr = c.mkey.into();686 let width = match c.width {687 Width::Star => {688 throw!(CannotUseStarWidthWithObject);689 }690 Width::Fixed(n) => n,691 };692 let precision = match c.precision {693 Some(Width::Star) => {694 throw!(CannotUseStarWidthWithObject);695 }696 Some(Width::Fixed(n)) => Some(n),697 None => None,698 };699700 let value = if c.convtype == ConvTypeV::Percent {701 Val::Null702 } else {703 if f.is_empty() {704 throw!(MappingKeysRequired);705 }706 if let Some(v) = values.get(f.clone())? {707 v708 } else {709 throw!(NoSuchFormatField(f));710 }711 };712713 format_code(&mut out, &value, &c, width, precision)?;714 }715 }716 }717718 Ok(out)719}720721#[cfg(test)]722pub mod test_format {723 use super::*;724725 #[test]726 fn parse() {727 assert_eq!(728 parse_codes(729 "How much error budget is left looking at our %.3f%% availability gurantees?"730 )731 .unwrap()732 .len(),733 4734 );735 }736737 #[test]738 fn octals() {739 assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");740 assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");741 assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), " 10");742 assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");743 assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");744 assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");745 assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10 ");746 assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");747 assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");748 }749750 #[test]751 fn percent_doesnt_consumes_values() {752 assert_eq!(753 format_arr(754 "How much error budget is left looking at our %.3f%% availability gurantees?",755 &[Val::Num(4.0)]756 )757 .unwrap(),758 "How much error budget is left looking at our 4.000% availability gurantees?"759 );760 }761}crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,10 +1,12 @@
+use crate::typed::{Any, Either, Null, PositiveF64, VecVal, M1};
+use crate::{self as jrsonnet_evaluator, ObjValue};
use crate::{
builtin::manifest::{manifest_yaml_ex, ManifestYamlOptions},
equals,
error::{Error::*, Result},
operator::evaluate_mod_op,
parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context, FuncVal,
- IndexableVal, LazyVal, Val,
+ IndexableVal, Val,
};
use format::{format_arr, format_obj};
use gcmodule::Cc;
@@ -13,7 +15,12 @@
use jrsonnet_types::ty;
use serde::Deserialize;
use serde_yaml::DeserializingQuirks;
-use std::{collections::HashMap, convert::TryFrom, path::PathBuf, rc::Rc};
+use std::{
+ collections::HashMap,
+ convert::{TryFrom, TryInto},
+ path::PathBuf,
+ rc::Rc,
+};
pub mod stdlib;
pub use stdlib::*;
@@ -24,15 +31,15 @@
pub mod manifest;
pub mod sort;
-pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
+pub fn std_format(str: IStr, vals: Val) -> Result<String> {
push_frame(
&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0),
|| format!("std.format of {}", str),
|| {
Ok(match vals {
- Val::Arr(vals) => Val::Str(format_arr(&str, &vals.evaluated()?)?.into()),
- Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
- o => Val::Str(format_arr(&str, &[o])?.into()),
+ Val::Arr(vals) => format_arr(&str, &vals.evaluated()?)?,
+ Val::Obj(obj) => format_obj(&str, &obj)?,
+ o => format_arr(&str, &[o])?,
})
},
)
@@ -139,265 +146,177 @@
};
}
-fn builtin_length(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "length", args, 1, [
- 0, x: ty!((string | object | array));
- ], {
- Ok(match x {
- Val::Str(n) => Val::Num(n.chars().count() as f64),
- Val::Arr(a) => Val::Num(a.len() as f64),
- Val::Obj(o) => Val::Num(
- o.fields_visibility()
- .into_iter()
- .filter(|(_k, v)| *v)
- .count() as f64,
- ),
- _ => unreachable!(),
- })
+#[jrsonnet_macros::builtin]
+fn builtin_length(x: Either<IStr, Either<VecVal, ObjValue>>) -> Result<usize> {
+ Ok(match x {
+ Either::Left(x) => x.len(),
+ Either::Right(Either::Left(x)) => x.0.len(),
+ Either::Right(Either::Right(x)) => x
+ .fields_visibility()
+ .into_iter()
+ .filter(|(_k, v)| *v)
+ .count(),
})
}
-fn builtin_type(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "type", args, 1, [
- 0, x: ty!(any);
- ], {
- Ok(Val::Str(x.value_type().name().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_type(x: Any) -> Result<IStr> {
+ Ok(x.0.value_type().name().into())
}
-fn builtin_make_array(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "makeArray", args, 2, [
- 0, sz: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- 1, func: ty!(function) => Val::Func;
- ], {
- let mut out = Vec::with_capacity(sz as usize);
- for i in 0..sz as usize {
- out.push(LazyVal::new_resolved(func.evaluate_values(
- context.clone(),
- &[Val::Num(i as f64)]
- )?))
- }
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_make_array(sz: usize, func: Cc<FuncVal>) -> Result<VecVal> {
+ let mut out = Vec::with_capacity(sz);
+ for i in 0..sz {
+ out.push(func.evaluate_values(&[Val::Num(i as f64)])?)
+ }
+ Ok(VecVal(out))
}
-fn builtin_codepoint(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "codepoint", args, 1, [
- 0, str: ty!(char) => Val::Str;
- ], {
- Ok(Val::Num(str.chars().next().unwrap() as u32 as f64))
- })
+#[jrsonnet_macros::builtin]
+const fn builtin_codepoint(str: char) -> Result<u32> {
+ Ok(str as u32)
}
-fn builtin_object_fields_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "objectFieldsEx", args, 2, [
- 0, obj: ty!(object) => Val::Obj;
- 1, inc_hidden: ty!(boolean) => Val::Bool;
- ], {
- let out = obj.fields_ex(inc_hidden);
- Ok(Val::Arr(out.into_iter().map(Val::Str).collect::<Vec<_>>().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_object_fields_ex(obj: ObjValue, inc_hidden: bool) -> Result<VecVal> {
+ let out = obj.fields_ex(inc_hidden);
+ Ok(VecVal(out.into_iter().map(Val::Str).collect::<Vec<_>>()))
}
-fn builtin_object_has_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "objectHasEx", args, 3, [
- 0, obj: ty!(object) => Val::Obj;
- 1, f: ty!(string) => Val::Str;
- 2, inc_hidden: ty!(boolean) => Val::Bool;
- ], {
- Ok(Val::Bool(obj.has_field_ex(f, inc_hidden)))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_object_has_ex(obj: ObjValue, f: IStr, inc_hidden: bool) -> Result<bool> {
+ Ok(obj.has_field_ex(f, inc_hidden))
}
-fn builtin_parse_json(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "parseJson", args, 1, [
- 0, s: ty!(string) => Val::Str;
- ], {
- let value: serde_json::Value = serde_json::from_str(&s).map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
- Ok(Val::try_from(&value)?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_parse_json(s: IStr) -> Result<Any> {
+ let value: serde_json::Value = serde_json::from_str(&s)
+ .map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+ Ok(Any(Val::try_from(&value)?))
}
-fn builtin_parse_yaml(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "parseYaml", args, 1, [
- 0, s: ty!(string) => Val::Str;
- ], {
- let value = serde_yaml::Deserializer::from_str_with_quirks(&s, DeserializingQuirks { old_octals: true });
- let mut out = vec![];
- for item in value {
- let value = serde_json::Value::deserialize(item)
- .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
- let val = Val::try_from(&value)?;
- out.push(val);
- }
- if out.is_empty() {
- Ok(Val::Null)
- } else if out.len() == 1 {
- Ok(out.into_iter().next().unwrap())
- } else {
- Ok(Val::Arr(out.into()))
- }
- })
+#[jrsonnet_macros::builtin]
+fn builtin_parse_yaml(s: IStr) -> Result<Any> {
+ let value = serde_yaml::Deserializer::from_str_with_quirks(
+ &s,
+ DeserializingQuirks { old_octals: true },
+ );
+ let mut out = vec![];
+ for item in value {
+ let value = serde_json::Value::deserialize(item)
+ .map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+ let val = Val::try_from(&value)?;
+ out.push(val);
+ }
+ Ok(Any(if out.is_empty() {
+ Val::Null
+ } else if out.len() == 1 {
+ out.into_iter().next().unwrap()
+ } else {
+ Val::Arr(out.into())
+ }))
}
-fn builtin_slice(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "slice", args, 4, [
- 0, indexable: ty!((string | array));
- 1, index: ty!((number | null));
- 2, end: ty!((number | null));
- 3, step: ty!((number | null));
- ], {
- std_slice(
- indexable.into_indexable()?,
- index.try_cast_nullable_num("index")?.map(|v| v as usize),
- end.try_cast_nullable_num("end")?.map(|v| v as usize),
- step.try_cast_nullable_num("step")?.map(|v| v as usize),
- )
- })
+#[jrsonnet_macros::builtin]
+fn builtin_slice(
+ indexable: IndexableVal,
+ index: Either<usize, Null>,
+ end: Either<usize, Null>,
+ step: Either<usize, Null>,
+) -> Result<Any> {
+ std_slice(indexable, index.left(), end.left(), step.left()).map(Any)
}
-fn builtin_substr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "substr", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, from: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- 2, len: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- ], {
- let out: String = str.chars().skip(from as usize).take(len as usize).collect();
- Ok(Val::Str(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {
+ Ok(str.chars().skip(from as usize).take(len as usize).collect())
}
-fn builtin_primitive_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "primitiveEquals", args, 2, [
- 0, a: ty!(any);
- 1, b: ty!(any);
- ], {
- Ok(Val::Bool(primitive_equals(&a, &b)?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_primitive_equals(a: Any, b: Any) -> Result<bool> {
+ primitive_equals(&a.0, &b.0)
}
-fn builtin_equals(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "equals", args, 2, [
- 0, a: ty!(any);
- 1, b: ty!(any);
- ], {
- Ok(Val::Bool(equals(&a, &b)?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_equals(a: Any, b: Any) -> Result<bool> {
+ equals(&a.0, &b.0)
}
-fn builtin_modulo(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "modulo", args, 2, [
- 0, a: ty!(number) => Val::Num;
- 1, b: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(a % b))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_modulo(a: f64, b: f64) -> Result<f64> {
+ Ok(a % b)
}
-fn builtin_mod(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "mod", args, 2, [
- 0, a: ty!((number | string));
- 1, b: ty!(any);
- ], {
- evaluate_mod_op(&a, &b)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_mod(a: Either<f64, IStr>, b: Any) -> Result<Any> {
+ Ok(Any(evaluate_mod_op(
+ &match a {
+ Either::Left(v) => Val::Num(v),
+ Either::Right(s) => Val::Str(s),
+ },
+ &b.0,
+ )?))
}
-fn builtin_floor(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "floor", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.floor()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_floor(x: f64) -> Result<f64> {
+ Ok(x.floor())
}
-fn builtin_ceil(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "ceil", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.ceil()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ceil(x: f64) -> Result<f64> {
+ Ok(x.ceil())
}
-fn builtin_log(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "log", args, 1, [
- 0, n: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(n.ln()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_log(n: f64) -> Result<f64> {
+ Ok(n.ln())
}
-fn builtin_pow(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "pow", args, 2, [
- 0, x: ty!(number) => Val::Num;
- 1, n: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.powf(n)))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_pow(x: f64, n: f64) -> Result<f64> {
+ Ok(x.powf(n))
}
-fn builtin_sqrt(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sqrt", args, 1, [
- 0, x: ty!(BoundedNumber<(Some(0.0)), (None)>) => Val::Num;
- ], {
- Ok(Val::Num(x.sqrt()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_sqrt(x: PositiveF64) -> Result<f64> {
+ Ok(x.0.sqrt())
}
-fn builtin_sin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sin", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.sin()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_sin(x: f64) -> Result<f64> {
+ Ok(x.sin())
}
-fn builtin_cos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "cos", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.cos()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_cos(x: f64) -> Result<f64> {
+ Ok(x.cos())
}
-fn builtin_tan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "tan", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.tan()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_tan(x: f64) -> Result<f64> {
+ Ok(x.tan())
}
-fn builtin_asin(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asin", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.asin()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_asin(x: f64) -> Result<f64> {
+ Ok(x.asin())
}
-fn builtin_acos(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "acos", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.acos()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_acos(x: f64) -> Result<f64> {
+ Ok(x.acos())
}
-fn builtin_atan(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "atan", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.atan()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_atan(x: f64) -> Result<f64> {
+ Ok(x.atan())
}
-fn builtin_exp(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "exp", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(x.exp()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_exp(x: f64) -> Result<f64> {
+ Ok(x.exp())
}
fn frexp(s: f64) -> (f64, i16) {
@@ -411,198 +330,140 @@
}
}
-fn builtin_mantissa(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "mantissa", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(frexp(x).0))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_mantissa(x: f64) -> Result<f64> {
+ Ok(frexp(x).0)
}
-fn builtin_exponent(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "exponent", args, 1, [
- 0, x: ty!(number) => Val::Num;
- ], {
- Ok(Val::Num(frexp(x).1.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_exponent(x: f64) -> Result<i16> {
+ Ok(frexp(x).1)
}
-fn builtin_ext_var(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "extVar", args, 1, [
- 0, x: ty!(string) => Val::Str;
- ], {
- Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or(UndefinedExternalVariable(x))?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ext_var(x: IStr) -> Result<Any> {
+ Ok(Any(with_state(|s| s.settings().ext_vars.get(&x).cloned())
+ .ok_or(UndefinedExternalVariable(x))?))
}
-fn builtin_native(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "native", args, 1, [
- 0, x: ty!(string) => Val::Str;
- ], {
- 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))?)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_native(name: IStr) -> Result<Cc<FuncVal>> {
+ Ok(with_state(|s| s.settings().ext_natives.get(&name).cloned())
+ .map(|v| Cc::new(FuncVal::NativeExt(name.clone(), v)))
+ .ok_or(UndefinedExternalFunction(name))?)
}
-fn builtin_filter(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "filter", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(arr.filter(|val| func
- .evaluate_values(context.clone(), &[val.clone()])?
- .try_cast_bool("filter predicate"))?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_filter(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+ arr.filter(|val| bool::try_from(func.evaluate_values(&[val.clone()])?))
}
-fn builtin_map(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "map", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(arr.map(|val| func
- .evaluate_values(context.clone(), &[val]))?))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_map(func: Cc<FuncVal>, arr: ArrValue) -> Result<ArrValue> {
+ arr.map(|val| func.evaluate_values(&[val]))
}
-fn builtin_flatmap(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "flatMap", args, 2, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!((array | string));
- ], {
- match arr {
- Val::Str(s) => {
- let mut out = String::new();
- for c in s.chars() {
- match func.evaluate_values(context.clone(), &[Val::Str(c.to_string().into())])? {
- Val::Str(o) => out.push_str(&o),
- _ => throw!(RuntimeError("in std.join all items should be strings".into())),
- };
- }
- Ok(Val::Str(out.into()))
- },
- Val::Arr(a) => {
- let mut out = Vec::new();
- for el in a.iter() {
- let el = el?;
- match func.evaluate_values(context.clone(), &[el])? {
- Val::Arr(o) => for oe in o.iter() {
+#[jrsonnet_macros::builtin]
+fn builtin_flatmap(func: Cc<FuncVal>, arr: IndexableVal) -> Result<IndexableVal> {
+ match arr {
+ IndexableVal::Str(s) => {
+ let mut out = String::new();
+ for c in s.chars() {
+ match func.evaluate_values(&[Val::Str(c.to_string().into())])? {
+ Val::Str(o) => out.push_str(&o),
+ _ => throw!(RuntimeError(
+ "in std.join all items should be strings".into()
+ )),
+ };
+ }
+ Ok(IndexableVal::Str(out.into()))
+ }
+ IndexableVal::Arr(a) => {
+ let mut out = Vec::new();
+ for el in a.iter() {
+ let el = el?;
+ match func.evaluate_values(&[el])? {
+ Val::Arr(o) => {
+ for oe in o.iter() {
out.push(oe?)
- },
- _ => throw!(RuntimeError("in std.join all items should be arrays".into())),
- };
- }
- Ok(Val::Arr(out.into()))
- },
- _ => unreachable!(),
+ }
+ }
+ _ => throw!(RuntimeError(
+ "in std.join all items should be arrays".into()
+ )),
+ };
+ }
+ Ok(IndexableVal::Arr(out.into()))
}
- })
+ }
}
-fn builtin_foldl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "foldl", args, 3, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- 2, init: ty!(any);
- ], {
- let mut acc = init;
- for i in arr.iter() {
- acc = func.evaluate_values(context.clone(), &[acc, i?])?;
- }
- Ok(acc)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_foldl(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+ let mut acc = init.0;
+ for i in arr.iter() {
+ acc = func.evaluate_values(&[acc, i?])?;
+ }
+ Ok(Any(acc))
}
-fn builtin_foldr(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "foldr", args, 3, [
- 0, func: ty!(function) => Val::Func;
- 1, arr: ty!(array) => Val::Arr;
- 2, init: ty!(any);
- ], {
- let mut acc = init;
- for i in arr.iter().rev() {
- acc = func.evaluate_values(context.clone(), &[i?, acc])?;
- }
- Ok(acc)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_foldr(func: Cc<FuncVal>, arr: ArrValue, init: Any) -> Result<Any> {
+ let mut acc = init.0;
+ for i in arr.iter().rev() {
+ acc = func.evaluate_values(&[i?, acc])?;
+ }
+ Ok(Any(acc))
}
+#[jrsonnet_macros::builtin]
#[allow(non_snake_case)]
-fn builtin_sort_impl(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "sort", args, 2, [
- 0, arr: ty!(array) => Val::Arr;
- 1, keyF: ty!(function) => Val::Func;
- ], {
- if arr.len() <= 1 {
- return Ok(Val::Arr(arr))
- }
- Ok(Val::Arr(ArrValue::Eager(sort::sort(context, arr.evaluated()?, &keyF)?)))
- })
+fn builtin_sort_impl(arr: ArrValue, keyF: Cc<FuncVal>) -> Result<ArrValue> {
+ if arr.len() <= 1 {
+ return Ok(arr);
+ }
+ Ok(ArrValue::Eager(sort::sort(arr.evaluated()?, &keyF)?))
}
-fn builtin_format(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "format", args, 2, [
- 0, str: ty!(string) => Val::Str;
- 1, vals: ty!(any)
- ], {
- std_format(str, vals)
- })
+#[jrsonnet_macros::builtin]
+fn builtin_format(str: IStr, vals: Any) -> Result<String> {
+ std_format(str, vals.0)
}
-fn builtin_range(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "range", args, 2, [
- 0, from: ty!(number) => Val::Num;
- 1, to: ty!(number) => Val::Num;
- ], {
- if to < from {
- return Ok(Val::Arr(ArrValue::new_eager()))
- }
- let mut out = Vec::with_capacity((1+to as usize-from as usize).max(0));
- for i in from as usize..=to as usize {
- out.push(Val::Num(i as f64));
- }
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_range(from: i32, to: i32) -> Result<VecVal> {
+ if to < from {
+ return Ok(VecVal(Vec::new()));
+ }
+ let mut out = Vec::with_capacity((1 + to as usize - from as usize).max(0));
+ for i in from as usize..=to as usize {
+ out.push(Val::Num(i as f64));
+ }
+ Ok(VecVal(out))
}
-fn builtin_char(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "char", args, 1, [
- 0, n: ty!(number) => Val::Num;
- ], {
- let mut out = String::new();
- out.push(std::char::from_u32(n as u32).ok_or_else(||
- InvalidUnicodeCodepointGot(n as u32)
- )?);
- Ok(Val::Str(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_char(n: u32) -> Result<char> {
+ Ok(std::char::from_u32(n as u32).ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?)
}
-fn builtin_encode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "encodeUTF8", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Arr((str.bytes().map(|b| Val::Num(b as f64)).collect::<Vec<Val>>()).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_encode_utf8(str: IStr) -> Result<VecVal> {
+ Ok(VecVal(
+ str.bytes()
+ .map(|b| Val::Num(b as f64))
+ .collect::<Vec<Val>>(),
+ ))
}
-fn builtin_decode_utf8(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "decodeUTF8", args, 1, [
- 0, arr: ty!((Array<ubyte>)) => Val::Arr;
- ], {
- let data: Result<Vec<u8>> = arr.iter().map(|v| v.map(|v| match v{
- Val::Num(n) => n as u8,
- _ => unreachable!(),
- })).collect();
- let data = data?;
- Ok(Val::Str(String::from_utf8(data).map_err(|_| RuntimeError("bad utf8".into()))?.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_decode_utf8(arr: Vec<u8>) -> Result<String> {
+ Ok(String::from_utf8(arr).map_err(|_| RuntimeError("bad utf8".into()))?)
}
-fn builtin_md5(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "md5", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(format!("{:x}", md5::compute(&str.as_bytes())).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_md5(str: IStr) -> Result<String> {
+ Ok(format!("{:x}", md5::compute(&str.as_bytes())))
}
fn builtin_trace(context: Context, loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
@@ -620,251 +481,174 @@
})
}
-fn builtin_base64(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "base64", args, 1, [
- 0, input: ty!((string | (Array<number>)));
- ], {
- Ok(Val::Str(match input {
- Val::Str(s) => {
- base64::encode(s.bytes().collect::<Vec<_>>()).into()
- },
- Val::Arr(a) => {
- base64::encode(a.iter().map(|v| {
- Ok(v?.unwrap_num()? as u8)
- }).collect::<Result<Vec<_>>>()?).into()
- },
- _ => unreachable!()
- }))
+#[jrsonnet_macros::builtin]
+fn builtin_base64(input: Either<Vec<u8>, IStr>) -> Result<String> {
+ Ok(match input {
+ Either::Left(a) => base64::encode(a),
+ Either::Right(l) => base64::encode(l.bytes().collect::<Vec<_>>()),
})
}
-fn builtin_base64_decode_bytes(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "base64DecodeBytes", args, 1, [
- 0, input: ty!(string) => Val::Str;
- ], {
- Ok(Val::Arr(
- base64::decode(&input.as_bytes())
- .map_err(|_| RuntimeError("bad base64".into()))?
- .iter()
- .map(|v| Val::Num(*v as f64)).collect::<Vec<_>>().into()
- ))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode_bytes(input: IStr) -> Result<Vec<u8>> {
+ Ok(base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?)
}
-fn builtin_base64_decode(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "base64Decode", args, 1, [
- 0, input: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(
- String::from_utf8(base64::decode(&input.as_bytes())
- .map_err(|_| RuntimeError("bad base64".into()))?)
- .map_err(|_| RuntimeError("bad utf8".into()))?.into()
- ))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_base64_decode(input: IStr) -> Result<String> {
+ let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+ Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
}
-fn builtin_join(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "join", args, 2, [
- 0, sep: ty!((string | array));
- 1, arr: ty!(array) => Val::Arr;
- ], {
- Ok(match sep {
- Val::Arr(joiner_items) => {
- let mut out = Vec::new();
+#[jrsonnet_macros::builtin]
+fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {
+ Ok(match sep {
+ IndexableVal::Arr(joiner_items) => {
+ let mut out = Vec::new();
- let mut first = true;
- for item in arr.iter() {
- let item = item?.clone();
- if let Val::Arr(items) = item {
- if !first {
- out.reserve(joiner_items.len());
- // TODO: extend
- for item in joiner_items.iter() {
- out.push(item?);
- }
- }
- first = false;
- out.reserve(items.len());
+ let mut first = true;
+ for item in arr.iter() {
+ let item = item?.clone();
+ if let Val::Arr(items) = item {
+ if !first {
+ out.reserve(joiner_items.len());
// TODO: extend
- for item in items.iter() {
+ for item in joiner_items.iter() {
out.push(item?);
}
- } else {
- throw!(RuntimeError("in std.join all items should be arrays".into()));
}
+ first = false;
+ out.reserve(items.len());
+ // TODO: extend
+ for item in items.iter() {
+ out.push(item?);
+ }
+ } else {
+ throw!(RuntimeError(
+ "in std.join all items should be arrays".into()
+ ));
}
+ }
- Val::Arr(out.into())
- },
- Val::Str(sep) => {
- let mut out = String::new();
+ IndexableVal::Arr(out.into())
+ }
+ IndexableVal::Str(sep) => {
+ let mut out = String::new();
- let mut first = true;
- for item in arr.iter() {
- let item = item?.clone();
- if let Val::Str(item) = item {
- if !first {
- out += &sep;
- }
- first = false;
- out += &item;
- } else {
- throw!(RuntimeError("in std.join all items should be strings".into()));
+ let mut first = true;
+ for item in arr.iter() {
+ let item = item?.clone();
+ if let Val::Str(item) = item {
+ if !first {
+ out += &sep;
}
+ first = false;
+ out += &item;
+ } else {
+ throw!(RuntimeError(
+ "in std.join all items should be strings".into()
+ ));
}
+ }
- Val::Str(out.into())
- },
- _ => unreachable!()
- })
+ IndexableVal::Str(out.into())
+ }
})
}
-fn builtin_escape_string_json(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "escapeStringJson", args, 1, [
- 0, str_: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(escape_string_json(&str_).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_escape_string_json(str_: IStr) -> Result<String> {
+ Ok(escape_string_json(&str_))
}
-fn builtin_manifest_json_ex(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "manifestJsonEx", args, 2, [
- 0, value: ty!(any);
- 1, indent: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(manifest_json_ex(&value, &ManifestJsonOptions {
+#[jrsonnet_macros::builtin]
+fn builtin_manifest_json_ex(value: Any, indent: IStr) -> Result<String> {
+ manifest_json_ex(
+ &value.0,
+ &ManifestJsonOptions {
padding: &indent,
mtype: ManifestType::Std,
- })?.into()))
- })
+ },
+ )
}
+#[jrsonnet_macros::builtin]
fn builtin_manifest_yaml_doc(
- context: Context,
- _loc: &ExprLocation,
- args: &ArgsDesc,
-) -> Result<Val> {
- parse_args!(context, "manifestYamlDoc", args, 3, [
- 0, value: ty!(any);
- 1, indent_array_in_object: ty!(boolean) => Val::Bool;
- 2, quote_keys: ty!(boolean) => Val::Bool;
- ], {
- Ok(Val::Str(manifest_yaml_ex(&value, &ManifestYamlOptions {
+ value: Any,
+ indent_array_in_object: bool,
+ quote_keys: bool,
+) -> Result<String> {
+ manifest_yaml_ex(
+ &value.0,
+ &ManifestYamlOptions {
padding: " ",
arr_element_padding: if indent_array_in_object { " " } else { "" },
quote_keys,
- })?.into()))
- })
+ },
+ )
}
-fn builtin_reverse(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "reverse", args, 1, [
- 0, value: ty!(array) => Val::Arr;
- ], {
- Ok(Val::Arr(value.reversed()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_reverse(value: ArrValue) -> Result<ArrValue> {
+ Ok(value.reversed())
}
-fn builtin_id(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "id", args, 1, [
- 0, v: ty!(any);
- ], {
- Ok(v)
- })
+#[jrsonnet_macros::builtin]
+const fn builtin_id(v: Any) -> Result<Any> {
+ Ok(v)
}
-fn builtin_str_replace(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "strReplace", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, from: ty!(string) => Val::Str;
- 2, to: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.replace(&from as &str, &to as &str).into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {
+ Ok(str.replace(&from as &str, &to as &str))
}
-
-fn builtin_splitlimit(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "splitLimit", args, 3, [
- 0, str: ty!(string) => Val::Str;
- 1, c: ty!(char) => Val::Str;
- 2, maxsplits: ty!(number) => Val::Num;
- ], {
- let maxsplits = maxsplits as isize;
- let c = c.chars().next().unwrap();
- let out: Vec<Val> = if maxsplits == -1 {
- str.split(c).map(|s| Val::Str(s.into())).collect()
- } else {
- str.splitn(maxsplits as usize + 1, c).map(|s| Val::Str(s.into())).collect()
- };
-
- Ok(Val::Arr(out.into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_splitlimit(str: IStr, c: char, maxsplits: Either<usize, M1>) -> Result<VecVal> {
+ Ok(VecVal(match maxsplits {
+ Either::Left(n) => str.splitn(n + 1, c).map(|s| Val::Str(s.into())).collect(),
+ Either::Right(_) => str.split(c).map(|s| Val::Str(s.into())).collect(),
+ }))
}
-fn builtin_ascii_upper(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asciiUpper", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.to_ascii_uppercase().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_upper(str: IStr) -> Result<String> {
+ Ok(str.to_ascii_uppercase())
}
-fn builtin_ascii_lower(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "asciiLower", args, 1, [
- 0, str: ty!(string) => Val::Str;
- ], {
- Ok(Val::Str(str.to_ascii_lowercase().into()))
- })
+#[jrsonnet_macros::builtin]
+fn builtin_ascii_lower(str: IStr) -> Result<String> {
+ Ok(str.to_ascii_lowercase())
}
-fn builtin_member(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "member", args, 2, [
- 0, arr: ty!((array | string));
- 1, x: ty!(any);
- ], {
- match arr {
- Val::Str(s) => {
- let x = x.try_cast_str("x should be string")?;
- Ok(Val::Bool(!x.is_empty() && s.contains(&*x)))
- }
- Val::Arr(a) => {
- for item in a.iter() {
- let item = item?;
- if equals(&item, &x)? {
- return Ok(Val::Bool(true));
- }
+#[jrsonnet_macros::builtin]
+fn builtin_member(arr: IndexableVal, x: Any) -> Result<bool> {
+ match arr {
+ IndexableVal::Str(s) => {
+ let x: IStr = IStr::try_from(x.0)?;
+ Ok(!x.is_empty() && s.contains(&*x))
+ }
+ IndexableVal::Arr(a) => {
+ for item in a.iter() {
+ let item = item?;
+ if equals(&item, &x.0)? {
+ return Ok(true);
}
- Ok(Val::Bool(false))
}
- _ => unreachable!(),
+ Ok(false)
}
- })
+ }
}
-fn builtin_count(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
- parse_args!(context, "count", args, 2, [
- 0, arr: ty!(array) => Val::Arr;
- 1, x: ty!(any);
- ], {
- let mut count = 0;
- for item in arr.iter() {
- let item = item?;
- if equals(&item, &x)? {
- count += 1;
- }
+#[jrsonnet_macros::builtin]
+fn builtin_count(arr: Vec<Any>, v: Any) -> Result<usize> {
+ let mut count = 0;
+ for item in arr.iter() {
+ if equals(&item.0, &v.0)? {
+ count += 1;
}
- Ok(Val::Num(count as f64))
- })
+ }
+ Ok(count)
}
pub fn call_builtin(
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -1,6 +1,6 @@
use crate::{
error::{Error, LocError, Result},
- throw, Context, FuncVal, Val,
+ throw, FuncVal, Val,
};
use gcmodule::{Cc, Trace};
@@ -59,7 +59,7 @@
Ok(sort_type)
}
-pub fn sort(ctx: Context, values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
+pub fn sort(values: Cc<Vec<Val>>, key_getter: &FuncVal) -> Result<Cc<Vec<Val>>> {
if values.len() <= 1 {
return Ok(values);
}
@@ -81,10 +81,7 @@
} else {
let mut vk = Vec::with_capacity(values.len());
for value in values.iter() {
- vk.push((
- value.clone(),
- key_getter.evaluate_values(ctx.clone(), &[value.clone()])?,
- ));
+ vk.push((value.clone(), key_getter.evaluate_values(&[value.clone()])?));
}
let sort_type = get_sort_type(&mut vk, |v| &mut v.1)?;
match sort_type {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -1,3 +1,5 @@
+use std::convert::TryFrom;
+
use crate::{
builtin::std_slice,
error::Error::*,
@@ -189,14 +191,18 @@
) -> Result<Option<IStr>> {
Ok(match field_name {
jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
- jrsonnet_parser::FieldName::Dyn(expr) => {
- let value = evaluate(context, expr)?;
- if matches!(value, Val::Null) {
- None
- } else {
- Some(value.try_cast_str("dynamic field name")?)
- }
- }
+ jrsonnet_parser::FieldName::Dyn(expr) => push_frame(
+ &expr.1,
+ || "evaluating field name".to_string(),
+ || {
+ let value = evaluate(context, expr)?;
+ if matches!(value, Val::Null) {
+ Ok(None)
+ } else {
+ Ok(Some(IStr::try_from(value)?))
+ }
+ },
+ )?,
})
}
@@ -208,7 +214,7 @@
match specs.get(0) {
None => callback(context)?,
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
- if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
+ if bool::try_from(evaluate(context.clone(), cond)?)? {
evaluate_comp(context, &specs[1..], callback)?
}
}
@@ -459,10 +465,7 @@
let assertion_result = push_frame(
&value.1,
|| "assertion condition".to_owned(),
- || {
- evaluate(context.clone(), value)?
- .try_cast_bool("assertion condition should be of type `boolean`")
- },
+ || bool::try_from(evaluate(context.clone(), value)?),
)?;
if !assertion_result {
push_frame(
@@ -633,11 +636,7 @@
ErrorStmt(e) => push_frame(
loc,
|| "error statement".to_owned(),
- || {
- throw!(RuntimeError(
- evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
- ))
- },
+ || throw!(RuntimeError(IStr::try_from(evaluate(context, e)?)?,)),
)?,
IfElse {
cond,
@@ -647,7 +646,7 @@
if push_frame(
loc,
|| "if condition".to_owned(),
- || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
+ || bool::try_from(evaluate(context.clone(), &cond.0)?),
)? {
evaluate(context, cond_then)?
} else {
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -1,3 +1,5 @@
+use std::convert::TryInto;
+
use crate::builtin::std_format;
use crate::{equals, evaluate, Context, Val};
use crate::{error::Error::*, throw, Result};
@@ -46,7 +48,7 @@
use Val::*;
match (a, b) {
(Num(a), Num(b)) => Ok(Num(a % b)),
- (Str(str), vals) => std_format(str.clone(), vals.clone()),
+ (Str(str), vals) => std_format(str.clone(), vals.clone())?.try_into(),
(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
BinaryOpType::Mod,
a.value_type(),
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -141,6 +141,93 @@
}
}
+#[derive(Clone, Copy)]
+pub struct BuiltinParam {
+ pub name: &'static str,
+ pub has_default: bool,
+}
+
+/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead
+///
+/// ## Parameters
+/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)
+/// * `params`: function parameters' definition
+/// * `args`: passed function arguments
+/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
+pub fn parse_builtin_call<'k>(
+ ctx: Context,
+ params: &'static [BuiltinParam],
+ args: &'k ArgsDesc,
+ tailstrict: bool,
+) -> Result<GcHashMap<&'k str, LazyVal>> {
+ let mut passed_args = GcHashMap::with_capacity(params.len());
+ if args.unnamed.len() > params.len() {
+ throw!(TooManyArgsFunctionHas(params.len()))
+ }
+
+ let mut filled_args = 0;
+
+ for (id, arg) in args.unnamed.iter().enumerate() {
+ let name = params[id].name;
+ passed_args.insert(
+ name,
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), arg)?)
+ } else {
+ LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: arg.clone(),
+ })))
+ },
+ );
+ filled_args += 1;
+ }
+
+ for (name, value) in args.named.iter() {
+ // FIXME: O(n) for arg existence check
+ if !params.iter().any(|p| p.name == name as &str) {
+ throw!(UnknownFunctionParameter((name as &str).to_owned()));
+ }
+ if passed_args
+ .insert(
+ name,
+ if tailstrict {
+ LazyVal::new_resolved(evaluate(ctx.clone(), value)?)
+ } else {
+ LazyVal::new(TraceBox(Box::new(EvaluateLazyVal {
+ context: ctx.clone(),
+ expr: value.clone(),
+ })))
+ },
+ )
+ .is_some()
+ {
+ throw!(BindingParameterASecondTime(name.clone()));
+ }
+ filled_args += 1;
+ }
+
+ if filled_args < params.len() {
+ for param in params.iter().filter(|p| p.has_default) {
+ if passed_args.contains_key(¶m.name) {
+ continue;
+ }
+ filled_args += 1;
+ }
+
+ // Some args still wasn't filled
+ if filled_args != params.len() {
+ for param in params.iter().skip(args.unnamed.len()) {
+ if !args.named.iter().any(|a| &a.0 as &str == param.name) {
+ throw!(FunctionParameterNotBoundInCall(param.name.into()));
+ }
+ }
+ unreachable!();
+ }
+ }
+ Ok(passed_args)
+}
+
pub fn parse_function_call_map(
ctx: Context,
body_ctx: Option<Context>,
@@ -201,12 +288,7 @@
Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
}
-pub fn place_args(
- ctx: Context,
- body_ctx: Option<Context>,
- params: &ParamsDesc,
- args: &[Val],
-) -> Result<Context> {
+pub fn place_args(body_ctx: Context, params: &ParamsDesc, args: &[Val]) -> Result<Context> {
let mut out = GcHashMap::with_capacity(params.len());
let mut positioned_args = vec![None; params.0.len()];
for (id, arg) in args.iter().enumerate() {
@@ -220,14 +302,14 @@
let val = if let Some(arg) = &positioned_args[id] {
(*arg).clone()
} else if let Some(default) = &p.1 {
- evaluate(ctx.clone(), default)?
+ evaluate(body_ctx.clone(), default)?
} else {
throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
out.insert(p.0.clone(), LazyVal::new_resolved(val));
}
- Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))
+ Ok(body_ctx.extend(out, None, None, None))
}
#[macro_export]
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -122,6 +122,7 @@
.map(|el| &el.location)
.map(|location| {
use std::fmt::Write;
+ #[allow(clippy::option_if_let_else)]
if let Some(location) = location {
let mut resolved_path = self.resolver.resolve(&location.0);
// TODO: Process all trace elements first
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-use std::{fmt::Display, rc::Rc};
-
-use crate::{
- error::{Error, LocError, Result},
- push_description_frame, Val,
-};
-use gcmodule::Trace;
-use jrsonnet_types::{ComplexValType, ValType};
-use thiserror::Error;
-
-#[macro_export]
-macro_rules! unwrap_type {
- ($desc: expr, $value: expr, $typ: expr => $match: path) => {{
- use $crate::{push_stack_frame, typed::CheckType};
- push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
- match $value {
- $match(v) => v,
- _ => unreachable!(),
- }
- }};
-}
-
-#[derive(Debug, Error, Clone, Trace)]
-pub enum TypeError {
- #[error("expected {0}, got {1}")]
- ExpectedGot(ComplexValType, ValType),
- #[error("missing property {0} from {1:?}")]
- MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
- #[error("every failed from {0}:\n{1}")]
- UnionFailed(ComplexValType, TypeLocErrorList),
- #[error(
- "number out of bounds: {0} not in {}..{}",
- .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
- )]
- BoundsFailed(f64, Option<f64>, Option<f64>),
-}
-impl From<TypeError> for LocError {
- fn from(e: TypeError) -> Self {
- Error::TypeError(e.into()).into()
- }
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocError(Box<TypeError>, ValuePathStack);
-impl From<TypeError> for TypeLocError {
- fn from(e: TypeError) -> Self {
- Self(Box::new(e), ValuePathStack(Vec::new()))
- }
-}
-impl From<TypeLocError> for LocError {
- fn from(e: TypeLocError) -> Self {
- Error::TypeError(e).into()
- }
-}
-impl Display for TypeLocError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}", self.0)?;
- if !(self.1).0.is_empty() {
- write!(f, " at {}", self.1)?;
- }
- Ok(())
- }
-}
-
-#[derive(Debug, Clone, Trace)]
-pub struct TypeLocErrorList(Vec<TypeLocError>);
-impl Display for TypeLocErrorList {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- use std::fmt::Write;
- let mut out = String::new();
- for (i, err) in self.0.iter().enumerate() {
- if i != 0 {
- writeln!(f)?;
- }
- out.clear();
- write!(out, "{}", err)?;
-
- for (i, line) in out.lines().enumerate() {
- if line.trim().is_empty() {
- continue;
- }
- if i != 0 {
- writeln!(f)?;
- write!(f, " ")?;
- } else {
- write!(f, " - ")?;
- }
- write!(f, "{}", line)?;
- }
- }
- Ok(())
- }
-}
-
-fn push_type_description(
- error_reason: impl Fn() -> String,
- path: impl Fn() -> ValuePathItem,
- item: impl Fn() -> Result<()>,
-) -> Result<()> {
- push_description_frame(error_reason, || match item() {
- Ok(_) => Ok(()),
- Err(mut e) => {
- if let Error::TypeError(e) = &mut e.error_mut() {
- (e.1).0.push(path())
- }
- Err(e)
- }
- })
-}
-
-// TODO: check_fast for fast path of union type checking
-pub trait CheckType {
- fn check(&self, value: &Val) -> Result<()>;
-}
-
-impl CheckType for ValType {
- fn check(&self, value: &Val) -> Result<()> {
- let got = value.value_type();
- if got != *self {
- let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
- return Err(loc_error.into());
- }
- Ok(())
- }
-}
-
-#[derive(Clone, Debug, Trace)]
-enum ValuePathItem {
- Field(#[skip_trace] Rc<str>),
- Index(u64),
-}
-impl Display for ValuePathItem {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::Field(name) => write!(f, ".{}", name)?,
- Self::Index(idx) => write!(f, "[{}]", idx)?,
- }
- Ok(())
- }
-}
-
-#[derive(Clone, Debug, Trace)]
-struct ValuePathStack(Vec<ValuePathItem>);
-impl Display for ValuePathStack {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "self")?;
- for elem in self.0.iter().rev() {
- write!(f, "{}", elem)?;
- }
- Ok(())
- }
-}
-
-impl CheckType for ComplexValType {
- fn check(&self, value: &Val) -> Result<()> {
- match self {
- Self::Any => Ok(()),
- Self::Simple(s) => s.check(value),
- Self::Char => match value {
- Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::BoundedNumber(from, to) => {
- if let Val::Num(n) = value {
- if from.map(|from| from > *n).unwrap_or(false)
- || to.map(|to| to <= *n).unwrap_or(false)
- {
- return Err(TypeError::BoundsFailed(*n, *from, *to).into());
- }
- Ok(())
- } else {
- Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
- }
- }
- Self::Array(elem_type) => match value {
- Val::Arr(a) => {
- for (i, item) in a.iter().enumerate() {
- push_type_description(
- || format!("array index {}", i),
- || ValuePathItem::Index(i as u64),
- || elem_type.check(&item.clone()?),
- )?;
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::ArrayRef(elem_type) => match value {
- Val::Arr(a) => {
- for (i, item) in a.iter().enumerate() {
- push_type_description(
- || format!("array index {}", i),
- || ValuePathItem::Index(i as u64),
- || elem_type.check(&item.clone()?),
- )?;
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::ObjectRef(elems) => match value {
- Val::Obj(obj) => {
- for (k, v) in elems.iter() {
- if let Some(got_v) = obj.get((*k).into())? {
- push_type_description(
- || format!("property {}", k),
- || ValuePathItem::Field((*k).into()),
- || v.check(&got_v),
- )?
- } else {
- return Err(
- TypeError::MissingProperty((*k).into(), self.clone()).into()
- );
- }
- }
- Ok(())
- }
- v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
- },
- Self::Union(types) => {
- let mut errors = Vec::new();
- for ty in types.iter() {
- match ty.check(value) {
- Ok(()) => {
- return Ok(());
- }
- Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
- _ => return Err(e),
- },
- }
- }
- Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
- }
- Self::UnionRef(types) => {
- let mut errors = Vec::new();
- for ty in types.iter() {
- match ty.check(value) {
- Ok(()) => {
- return Ok(());
- }
- Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
- _ => return Err(e),
- },
- }
- }
- Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
- }
- Self::Sum(types) => {
- for ty in types.iter() {
- ty.check(value)?
- }
- Ok(())
- }
- Self::SumRef(types) => {
- for ty in types.iter() {
- ty.check(value)?
- }
- Ok(())
- }
- }
- }
-}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -0,0 +1,508 @@
+use std::convert::{TryFrom, TryInto};
+
+use gcmodule::Cc;
+use jrsonnet_interner::IStr;
+use jrsonnet_types::{ComplexValType, ValType};
+
+use crate::{
+ error::{Error::*, LocError, Result},
+ throw,
+ typed::CheckType,
+ ArrValue, FuncVal, IndexableVal, ObjValue, Val,
+};
+
+pub trait Typed: TryFrom<Val, Error = LocError> + TryInto<Val, Error = LocError> {
+ const TYPE: &'static ComplexValType;
+}
+
+macro_rules! impl_int {
+ ($($ty:ty)*) => {$(
+ impl Typed for $ty {
+ const TYPE: &'static ComplexValType =
+ &ComplexValType::BoundedNumber(Some(<$ty>::MIN as f64), Some(<$ty>::MAX as f64));
+ }
+ impl TryFrom<Val> for $ty {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => {
+ if n.trunc() != n {
+ throw!(RuntimeError(
+ format!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
+ .into()
+ ))
+ }
+ Ok(n as $ty)
+ }
+ _ => unreachable!(),
+ }
+ }
+ }
+ impl TryFrom<$ty> for Val {
+ type Error = LocError;
+
+ fn try_from(value: $ty) -> Result<Self> {
+ Ok(Self::Num(value as f64))
+ }
+ }
+ )*};
+}
+
+impl_int!(i8 u8 i16 u16 i32 u32);
+
+impl Typed for f64 {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Num);
+}
+impl TryFrom<Val> for f64 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => Ok(n),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<f64> for Val {
+ type Error = LocError;
+
+ fn try_from(value: f64) -> Result<Self> {
+ Ok(Self::Num(value))
+ }
+}
+
+pub struct PositiveF64(pub f64);
+impl Typed for PositiveF64 {
+ const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(0.0), None);
+}
+impl TryFrom<Val> for PositiveF64 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => Ok(Self(n)),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<PositiveF64> for Val {
+ type Error = LocError;
+
+ fn try_from(value: PositiveF64) -> Result<Self> {
+ Ok(Self::Num(value.0))
+ }
+}
+
+impl Typed for usize {
+ // It is possible to store 54 bits of precision in f64, but leaving u32::MAX here for compatibility
+ const TYPE: &'static ComplexValType =
+ &ComplexValType::BoundedNumber(Some(0.0), Some(4294967295.0));
+}
+impl TryFrom<Val> for usize {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Num(n) => {
+ if n.trunc() != n {
+ throw!(RuntimeError(
+ "cannot convert number with fractional part to usize".into()
+ ))
+ }
+ Ok(n as Self)
+ }
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<usize> for Val {
+ type Error = LocError;
+
+ fn try_from(value: usize) -> Result<Self> {
+ if value > u32::MAX as usize {
+ throw!(RuntimeError("number is too large".into()))
+ }
+ Ok(Self::Num(value as f64))
+ }
+}
+
+impl Typed for IStr {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for IStr {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<IStr> for Val {
+ type Error = LocError;
+
+ fn try_from(value: IStr) -> Result<Self> {
+ Ok(Self::Str(value))
+ }
+}
+
+impl Typed for String {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
+}
+impl TryFrom<Val> for String {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s.to_string()),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<String> for Val {
+ type Error = LocError;
+
+ fn try_from(value: String) -> Result<Self> {
+ Ok(Self::Str(value.into()))
+ }
+}
+
+impl Typed for char {
+ const TYPE: &'static ComplexValType = &ComplexValType::Char;
+}
+impl TryFrom<Val> for char {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Str(s) => Ok(s.chars().next().unwrap()),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<char> for Val {
+ type Error = LocError;
+
+ fn try_from(value: char) -> Result<Self> {
+ Ok(Self::Str(value.to_string().into()))
+ }
+}
+
+impl<T> Typed for Vec<T>
+where
+ T: Typed,
+ T: TryFrom<Val, Error = LocError>,
+ T: TryInto<Val, Error = LocError>,
+{
+ const TYPE: &'static ComplexValType = &ComplexValType::ArrayRef(T::TYPE);
+}
+impl<T> TryFrom<Val> for Vec<T>
+where
+ T: Typed,
+ T: TryFrom<Val, Error = LocError>,
+ T: TryInto<Val, Error = LocError>,
+{
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => {
+ let mut o = Self::with_capacity(a.len());
+ for i in a.iter() {
+ o.push(T::try_from(i?)?);
+ }
+ Ok(o)
+ }
+ _ => unreachable!(),
+ }
+ }
+}
+impl<T> TryFrom<Vec<T>> for Val
+where
+ T: Typed,
+ T: TryFrom<Self, Error = LocError>,
+ T: TryInto<Self, Error = LocError>,
+{
+ type Error = LocError;
+
+ fn try_from(value: Vec<T>) -> Result<Self> {
+ let mut o = Vec::with_capacity(value.len());
+ for i in value {
+ o.push(i.try_into()?);
+ }
+ Ok(Self::Arr(o.into()))
+ }
+}
+
+/// To be used in Vec<Any>
+/// Regular Val can't be used here, because it has wrong TryFrom::Error type
+pub struct Any(pub Val);
+
+impl Typed for Any {
+ const TYPE: &'static ComplexValType = &ComplexValType::Any;
+}
+impl TryFrom<Val> for Any {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ Ok(Self(value))
+ }
+}
+impl TryFrom<Any> for Val {
+ type Error = LocError;
+
+ fn try_from(value: Any) -> Result<Self> {
+ Ok(value.0)
+ }
+}
+
+/// Specialization, provides faster TryFrom<VecVal> for Val
+pub struct VecVal(pub Vec<Val>);
+
+impl Typed for VecVal {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for VecVal {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => Ok(Self(a.evaluated()?.to_vec())),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<VecVal> for Val {
+ type Error = LocError;
+
+ fn try_from(value: VecVal) -> Result<Self> {
+ Ok(Self::Arr(value.0.into()))
+ }
+}
+
+pub struct M1;
+impl Typed for M1 {
+ const TYPE: &'static ComplexValType = &ComplexValType::BoundedNumber(Some(-1.0), Some(-1.0));
+}
+impl TryFrom<Val> for M1 {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ Ok(Self)
+ }
+}
+impl TryFrom<M1> for Val {
+ type Error = LocError;
+
+ fn try_from(_: M1) -> Result<Self> {
+ Ok(Self::Num(-1.0))
+ }
+}
+
+pub enum Either<A, B> {
+ Left(A),
+ Right(B),
+}
+
+impl<A, B> Either<A, B> {
+ pub fn to_left(self, f: impl FnOnce(B) -> A) -> A {
+ match self {
+ Either::Left(l) => l,
+ Either::Right(r) => f(r),
+ }
+ }
+ #[allow(clippy::missing_const_for_fn)]
+ pub fn left(self) -> Option<A> {
+ match self {
+ Either::Left(a) => Some(a),
+ Either::Right(_) => None,
+ }
+ }
+}
+
+impl<A, B> Typed for Either<A, B>
+where
+ A: Typed,
+ B: Typed,
+{
+ const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[A::TYPE, B::TYPE]);
+}
+impl<A, B> TryFrom<Val> for Either<A, B>
+where
+ A: Typed,
+ B: Typed,
+{
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ if A::TYPE.check(&value).is_ok() {
+ A::try_from(value).map(Self::Left)
+ } else if B::TYPE.check(&value).is_ok() {
+ B::try_from(value).map(Self::Right)
+ } else {
+ <Self as Typed>::TYPE.check(&value)?;
+ unreachable!()
+ }
+ }
+}
+impl<A, B> TryFrom<Either<A, B>> for Val
+where
+ A: Typed,
+ B: Typed,
+{
+ type Error = LocError;
+
+ fn try_from(value: Either<A, B>) -> Result<Self> {
+ match value {
+ Either::Left(a) => a.try_into(),
+ Either::Right(b) => b.try_into(),
+ }
+ }
+}
+
+impl Typed for ArrValue {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Arr);
+}
+impl TryFrom<Val> for ArrValue {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Arr(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<ArrValue> for Val {
+ type Error = LocError;
+
+ fn try_from(value: ArrValue) -> Result<Self> {
+ Ok(Self::Arr(value))
+ }
+}
+
+impl Typed for Cc<FuncVal> {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Func);
+}
+impl TryFrom<Val> for Cc<FuncVal> {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Func(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<Cc<FuncVal>> for Val {
+ type Error = LocError;
+
+ fn try_from(value: Cc<FuncVal>) -> Result<Self> {
+ Ok(Self::Func(value))
+ }
+}
+impl Typed for ObjValue {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Obj);
+}
+impl TryFrom<Val> for ObjValue {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Obj(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<ObjValue> for Val {
+ type Error = LocError;
+
+ fn try_from(value: ObjValue) -> Result<Self> {
+ Ok(Self::Obj(value))
+ }
+}
+
+impl Typed for bool {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Bool);
+}
+impl TryFrom<Val> for bool {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ match value {
+ Val::Bool(a) => Ok(a),
+ _ => unreachable!(),
+ }
+ }
+}
+impl TryFrom<bool> for Val {
+ type Error = LocError;
+
+ fn try_from(value: bool) -> Result<Self> {
+ Ok(Self::Bool(value))
+ }
+}
+
+impl Typed for IndexableVal {
+ const TYPE: &'static ComplexValType = &ComplexValType::UnionRef(&[
+ &ComplexValType::Simple(ValType::Arr),
+ &ComplexValType::Simple(ValType::Str),
+ ]);
+}
+impl TryFrom<Val> for IndexableVal {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ value.into_indexable()
+ }
+}
+impl TryFrom<IndexableVal> for Val {
+ type Error = LocError;
+
+ fn try_from(value: IndexableVal) -> Result<Self> {
+ match value {
+ IndexableVal::Str(s) => Ok(Self::Str(s)),
+ IndexableVal::Arr(a) => Ok(Self::Arr(a)),
+ }
+ }
+}
+
+pub struct Null;
+impl Typed for Null {
+ const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Null);
+}
+impl TryFrom<Val> for Null {
+ type Error = LocError;
+
+ fn try_from(value: Val) -> Result<Self> {
+ <Self as Typed>::TYPE.check(&value)?;
+ Ok(Self)
+ }
+}
+impl TryFrom<Null> for Val {
+ type Error = LocError;
+
+ fn try_from(_: Null) -> Result<Self> {
+ Ok(Self::Null)
+ }
+}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -0,0 +1,268 @@
+use std::{fmt::Display, rc::Rc};
+
+mod conversions;
+pub use conversions::*;
+
+use crate::{
+ error::{Error, LocError, Result},
+ push_description_frame, Val,
+};
+use gcmodule::Trace;
+use jrsonnet_types::{ComplexValType, ValType};
+use thiserror::Error;
+
+#[macro_export]
+macro_rules! unwrap_type {
+ ($desc: expr, $value: expr, $typ: expr => $match: path) => {{
+ use $crate::{push_stack_frame, typed::CheckType};
+ push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;
+ match $value {
+ $match(v) => v,
+ _ => unreachable!(),
+ }
+ }};
+}
+
+#[derive(Debug, Error, Clone, Trace)]
+pub enum TypeError {
+ #[error("expected {0}, got {1}")]
+ ExpectedGot(ComplexValType, ValType),
+ #[error("missing property {0} from {1:?}")]
+ MissingProperty(#[skip_trace] Rc<str>, ComplexValType),
+ #[error("every failed from {0}:\n{1}")]
+ UnionFailed(ComplexValType, TypeLocErrorList),
+ #[error(
+ "number out of bounds: {0} not in {}..{}",
+ .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+ )]
+ BoundsFailed(f64, Option<f64>, Option<f64>),
+}
+impl From<TypeError> for LocError {
+ fn from(e: TypeError) -> Self {
+ Error::TypeError(e.into()).into()
+ }
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocError(Box<TypeError>, ValuePathStack);
+impl From<TypeError> for TypeLocError {
+ fn from(e: TypeError) -> Self {
+ Self(Box::new(e), ValuePathStack(Vec::new()))
+ }
+}
+impl From<TypeLocError> for LocError {
+ fn from(e: TypeLocError) -> Self {
+ Error::TypeError(e).into()
+ }
+}
+impl Display for TypeLocError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.0)?;
+ if !(self.1).0.is_empty() {
+ write!(f, " at {}", self.1)?;
+ }
+ Ok(())
+ }
+}
+
+#[derive(Debug, Clone, Trace)]
+pub struct TypeLocErrorList(Vec<TypeLocError>);
+impl Display for TypeLocErrorList {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ use std::fmt::Write;
+ let mut out = String::new();
+ for (i, err) in self.0.iter().enumerate() {
+ if i != 0 {
+ writeln!(f)?;
+ }
+ out.clear();
+ write!(out, "{}", err)?;
+
+ for (i, line) in out.lines().enumerate() {
+ if line.trim().is_empty() {
+ continue;
+ }
+ if i != 0 {
+ writeln!(f)?;
+ write!(f, " ")?;
+ } else {
+ write!(f, " - ")?;
+ }
+ write!(f, "{}", line)?;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn push_type_description(
+ error_reason: impl Fn() -> String,
+ path: impl Fn() -> ValuePathItem,
+ item: impl Fn() -> Result<()>,
+) -> Result<()> {
+ push_description_frame(error_reason, || match item() {
+ Ok(_) => Ok(()),
+ Err(mut e) => {
+ if let Error::TypeError(e) = &mut e.error_mut() {
+ (e.1).0.push(path())
+ }
+ Err(e)
+ }
+ })
+}
+
+// TODO: check_fast for fast path of union type checking
+pub trait CheckType {
+ fn check(&self, value: &Val) -> Result<()>;
+}
+
+impl CheckType for ValType {
+ fn check(&self, value: &Val) -> Result<()> {
+ let got = value.value_type();
+ if got != *self {
+ let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();
+ return Err(loc_error.into());
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, Trace)]
+enum ValuePathItem {
+ Field(#[skip_trace] Rc<str>),
+ Index(u64),
+}
+impl Display for ValuePathItem {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Field(name) => write!(f, ".{}", name)?,
+ Self::Index(idx) => write!(f, "[{}]", idx)?,
+ }
+ Ok(())
+ }
+}
+
+#[derive(Clone, Debug, Trace)]
+struct ValuePathStack(Vec<ValuePathItem>);
+impl Display for ValuePathStack {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "self")?;
+ for elem in self.0.iter().rev() {
+ write!(f, "{}", elem)?;
+ }
+ Ok(())
+ }
+}
+
+impl CheckType for ComplexValType {
+ fn check(&self, value: &Val) -> Result<()> {
+ match self {
+ Self::Any => Ok(()),
+ Self::Simple(s) => s.check(value),
+ Self::Char => match value {
+ Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::BoundedNumber(from, to) => {
+ if let Val::Num(n) = value {
+ if from.map(|from| from > *n).unwrap_or(false)
+ || to.map(|to| to < *n).unwrap_or(false)
+ {
+ return Err(TypeError::BoundsFailed(*n, *from, *to).into());
+ }
+ Ok(())
+ } else {
+ Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())
+ }
+ }
+ Self::Array(elem_type) => match value {
+ Val::Arr(a) => {
+ for (i, item) in a.iter().enumerate() {
+ push_type_description(
+ || format!("array index {}", i),
+ || ValuePathItem::Index(i as u64),
+ || elem_type.check(&item.clone()?),
+ )?;
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::ArrayRef(elem_type) => match value {
+ Val::Arr(a) => {
+ for (i, item) in a.iter().enumerate() {
+ push_type_description(
+ || format!("array index {}", i),
+ || ValuePathItem::Index(i as u64),
+ || elem_type.check(&item.clone()?),
+ )?;
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::ObjectRef(elems) => match value {
+ Val::Obj(obj) => {
+ for (k, v) in elems.iter() {
+ if let Some(got_v) = obj.get((*k).into())? {
+ push_type_description(
+ || format!("property {}", k),
+ || ValuePathItem::Field((*k).into()),
+ || v.check(&got_v),
+ )?
+ } else {
+ return Err(
+ TypeError::MissingProperty((*k).into(), self.clone()).into()
+ );
+ }
+ }
+ Ok(())
+ }
+ v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
+ },
+ Self::Union(types) => {
+ let mut errors = Vec::new();
+ for ty in types.iter() {
+ match ty.check(value) {
+ Ok(()) => {
+ return Ok(());
+ }
+ Err(e) => match e.error() {
+ Error::TypeError(e) => errors.push(e.clone()),
+ _ => return Err(e),
+ },
+ }
+ }
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+ }
+ Self::UnionRef(types) => {
+ let mut errors = Vec::new();
+ for ty in types.iter() {
+ match ty.check(value) {
+ Ok(()) => {
+ return Ok(());
+ }
+ Err(e) => match e.error() {
+ Error::TypeError(e) => errors.push(e.clone()),
+ _ => return Err(e),
+ },
+ }
+ }
+ Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())
+ }
+ Self::Sum(types) => {
+ for ty in types.iter() {
+ ty.check(value)?
+ }
+ Ok(())
+ }
+ Self::SumRef(types) => {
+ for ty in types.iter() {
+ ty.check(value)?
+ }
+ Ok(())
+ }
+ }
+ }
+}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -170,10 +170,10 @@
}
}
- pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {
+ pub fn evaluate_values(&self, args: &[Val]) -> Result<Val> {
match self {
Self::Normal(func) => {
- let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;
+ let ctx = place_args(func.ctx.clone(), &func.params, args)?;
evaluate(ctx, &func.body)
}
Self::Intrinsic(_) => todo!(),
@@ -363,14 +363,6 @@
Func(Cc<FuncVal>),
}
-macro_rules! matches_unwrap {
- ($e: expr, $p: pat, $r: expr) => {
- match $e {
- $p => $r,
- _ => panic!("no match"),
- }
- };
-}
impl Val {
/// Creates `Val::Num` after checking for numeric overflow.
/// As numbers are `f64`, we can just check for their finity.
@@ -382,38 +374,6 @@
}
}
- pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
- let this_type = self.value_type();
- if this_type != val_type {
- throw!(TypeMismatch(context, vec![val_type], this_type))
- } else {
- Ok(())
- }
- }
- pub fn unwrap_num(self) -> Result<f64> {
- Ok(matches_unwrap!(self, Self::Num(v), v))
- }
- pub fn unwrap_str(self) -> Result<IStr> {
- Ok(matches_unwrap!(self, Self::Str(v), v))
- }
- pub fn unwrap_arr(self) -> Result<ArrValue> {
- Ok(matches_unwrap!(self, Self::Arr(v), v))
- }
- pub fn unwrap_func(self) -> Result<Cc<FuncVal>> {
- Ok(matches_unwrap!(self, Self::Func(v), v))
- }
- pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {
- self.assert_type(context, ValType::Bool)?;
- Ok(matches_unwrap!(self, Self::Bool(v), v))
- }
- pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {
- self.assert_type(context, ValType::Str)?;
- Ok(matches_unwrap!(self, Self::Str(v), v))
- }
- pub fn try_cast_num(self, context: &'static str) -> Result<f64> {
- self.assert_type(context, ValType::Num)?;
- self.unwrap_num()
- }
pub fn try_cast_nullable_num(self, context: &'static str) -> Result<Option<f64>> {
Ok(match self {
Val::Null => None,
crates/jrsonnet-macros/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-macros/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "jrsonnet-macros"
+version = "0.4.2"
+edition = "2021"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1.0.32"
+quote = "1.0.10"
+syn = { version = "1.0.82", features = ["full"] }
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -0,0 +1,87 @@
+use proc_macro2::Span;
+use quote::quote;
+use syn::{parse_macro_input, FnArg, Ident, ItemFn, Pat};
+
+#[proc_macro_attribute]
+pub fn builtin(
+ _attr: proc_macro::TokenStream,
+ item: proc_macro::TokenStream,
+) -> proc_macro::TokenStream {
+ // syn::ItemFn::parse(input)
+ let fun: ItemFn = parse_macro_input!(item);
+
+ let inner_name = Ident::new("inner", Span::call_site());
+ let mut inner_fun = fun.clone();
+ inner_fun.sig.ident = inner_name.clone();
+ let result = match fun.sig.output {
+ syn::ReturnType::Default => panic!("builtin should return something"),
+ syn::ReturnType::Type(_, ty) => ty,
+ };
+
+ let params = fun
+ .sig
+ .inputs
+ .iter()
+ .map(|i| match i {
+ FnArg::Receiver(_) => unreachable!(),
+ FnArg::Typed(t) => t,
+ })
+ .map(|t| {
+ let ident = match &t.pat as &Pat {
+ Pat::Ident(i) => i.ident.to_string(),
+ _ => panic!("only idents supported yet"),
+ };
+ // TODO: Check if ty == Option<_>
+ let optional = false;
+ quote! {
+ BuiltinParam {
+ name: #ident,
+ has_default: #optional,
+ }
+ }
+ });
+
+ let args = fun
+ .sig
+ .inputs
+ .iter()
+ .map(|i| match i {
+ FnArg::Receiver(_) => unreachable!(),
+ FnArg::Typed(t) => t,
+ })
+ .map(|t| {
+ let ident = match &t.pat as &Pat {
+ Pat::Ident(i) => i.ident.to_string(),
+ _ => panic!("only idents supported yet"),
+ };
+ let ty = &t.ty;
+ quote! {{
+ let value = parsed.get(#ident).unwrap();
+
+ jrsonnet_evaluator::push_description_frame(
+ || format!("argument <{}> evaluation", #ident),
+ || <#ty>::try_from(value.evaluate()?),
+ )?
+ }}
+ });
+
+ let attrs = &fun.attrs;
+ let vis = &fun.vis;
+ let name = &fun.sig.ident;
+ (quote! {
+ #(#attrs)*
+ #vis fn #name(context: Context, _loc: &ExprLocation, args: &ArgsDesc) -> Result<Val> {
+ #inner_fun
+ use jrsonnet_evaluator::function::BuiltinParam;
+ const PARAMS: &'static [BuiltinParam] = &[
+ #(#params),*
+ ];
+ let parsed = jrsonnet_evaluator::function::parse_builtin_call(context, &PARAMS, args, false)?;
+
+ let result: #result = #inner_name(#(#args),*);
+ let result = result?;
+ result.try_into()
+ }
+ })
+ .into()
+}
crates/jrsonnet-types/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-types/src/lib.rs
+++ b/crates/jrsonnet-types/src/lib.rs
@@ -42,14 +42,14 @@
$crate::ComplexValType::Simple($crate::ValType::Func)
};
(($($a:tt) |+)) => {{
- static CONTENTS: &'static [$crate::ComplexValType] = &[
- $(ty!($a)),+
+ static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+ $(&ty!($a)),+
];
$crate::ComplexValType::UnionRef(CONTENTS)
}};
(($($a:tt) &+)) => {{
- static CONTENTS: &'static [$crate::ComplexValType] = &[
- $(ty!($a)),+
+ static CONTENTS: &'static [&'static $crate::ComplexValType] = &[
+ $(&ty!($a)),+
];
$crate::ComplexValType::SumRef(CONTENTS)
}};
@@ -66,8 +66,8 @@
assert_eq!(
ty!((string | number)),
ComplexValType::UnionRef(&[
- ComplexValType::Simple(ValType::Str),
- ComplexValType::Simple(ValType::Num)
+ &ComplexValType::Simple(ValType::Str),
+ &ComplexValType::Simple(ValType::Num)
])
);
assert_eq!(
@@ -124,9 +124,9 @@
ArrayRef(&'static ComplexValType),
ObjectRef(&'static [(&'static str, ComplexValType)]),
Union(Vec<ComplexValType>),
- UnionRef(&'static [ComplexValType]),
+ UnionRef(&'static [&'static ComplexValType]),
Sum(Vec<ComplexValType>),
- SumRef(&'static [ComplexValType]),
+ SumRef(&'static [&'static ComplexValType]),
}
impl From<ValType> for ComplexValType {
@@ -135,12 +135,12 @@
}
}
-fn write_union(
+fn write_union<'i>(
f: &mut std::fmt::Formatter<'_>,
is_union: bool,
- union: &[ComplexValType],
+ union: impl Iterator<Item = &'i ComplexValType>,
) -> std::fmt::Result {
- for (i, v) in union.iter().enumerate() {
+ for (i, v) in union.enumerate() {
let should_add_braces =
matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);
if i != 0 {
@@ -190,10 +190,10 @@
}
write!(f, "}}")?;
}
- ComplexValType::Union(v) => write_union(f, true, v)?,
- ComplexValType::UnionRef(v) => write_union(f, true, v)?,
- ComplexValType::Sum(v) => write_union(f, false, v)?,
- ComplexValType::SumRef(v) => write_union(f, false, v)?,
+ ComplexValType::Union(v) => write_union(f, true, v.iter())?,
+ ComplexValType::UnionRef(v) => write_union(f, true, v.iter().map(|v| *v))?,
+ ComplexValType::Sum(v) => write_union(f, false, v.iter())?,
+ ComplexValType::SumRef(v) => write_union(f, false, v.iter().map(|v| *v))?,
};
Ok(())
}