difftreelog
refact: simplify error management
in: master
18 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -1,7 +1,8 @@
//! Import resolution manipulation utilities
use jrsonnet_evaluator::{
- create_error, create_error_result, Error, EvaluationState, ImportResolver, Result,
+ error::{Error::*, Result},
+ throw, EvaluationState, ImportResolver,
};
use std::{
any::Any,
@@ -55,10 +56,9 @@
let result_str = result_raw.to_str().unwrap();
assert!(success == 0 || success == 1);
if success == 0 {
+ unsafe { CString::from_raw(result_ptr) };
let result = result_str.to_owned();
- let err = Err(create_error(Error::ImportCallbackError(result)));
- unsafe { CString::from_raw(result_ptr) };
- return err;
+ throw!(ImportCallbackError(result));
}
let found_here_raw = unsafe { CStr::from_ptr(found_here) };
@@ -121,15 +121,14 @@
return Ok(Rc::new(cloned));
}
}
- create_error_result(Error::ImportFileNotFound(from.clone(), path.clone()))
+ throw!(ImportFileNotFound(from.clone(), path.clone()))
}
}
fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {
- let mut file =
- File::open(id).map_err(|_e| create_error(Error::ResolvedFileNotFound(id.clone())))?;
+ let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
let mut out = String::new();
file.read_to_string(&mut out)
- .map_err(|_e| create_error(Error::ImportBadFileUtf8(id.clone())))?;
+ .map_err(|_e| ImportBadFileUtf8(id.clone()))?;
Ok(out.into())
}
unsafe fn as_any(&self) -> &dyn Any {
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -1,6 +1,6 @@
use clap::Clap;
use jrsonnet_cli::{ConfigureState, GeneralOpts, InputOpts, ManifestOpts};
-use jrsonnet_evaluator::{EvaluationState, Result};
+use jrsonnet_evaluator::{error::Result, EvaluationState};
use std::{path::PathBuf, rc::Rc};
#[global_allocator]
crates/jrsonnet-cli/src/ext.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/ext.rs
+++ b/crates/jrsonnet-cli/src/ext.rs
@@ -1,6 +1,6 @@
use crate::ConfigureState;
use clap::Clap;
-use jrsonnet_evaluator::{EvaluationState, Result};
+use jrsonnet_evaluator::{error::Result, EvaluationState};
use std::str::FromStr;
#[derive(Clone)]
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -9,7 +9,7 @@
pub use trace::*;
use clap::Clap;
-use jrsonnet_evaluator::{EvaluationState, FileImportResolver, Result};
+use jrsonnet_evaluator::{error::Result, EvaluationState, FileImportResolver};
use std::path::PathBuf;
pub trait ConfigureState {
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,6 +1,6 @@
use crate::ConfigureState;
use clap::Clap;
-use jrsonnet_evaluator::{EvaluationState, ManifestFormat, Result};
+use jrsonnet_evaluator::{error::Result, EvaluationState, ManifestFormat};
use std::str::FromStr;
pub enum ManifestFormatName {
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,6 +1,6 @@
use crate::{ConfigureState, ExtStr};
use clap::Clap;
-use jrsonnet_evaluator::{EvaluationState, Result};
+use jrsonnet_evaluator::{error::Result, EvaluationState};
#[derive(Clap)]
// #[clap(help_heading = "TOP LEVEL ARGUMENTS")]
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,8 +1,9 @@
use crate::ConfigureState;
use clap::Clap;
use jrsonnet_evaluator::{
+ error::Result,
trace::{CompactFormat, ExplainingFormat, PathResolver},
- EvaluationState, Result,
+ EvaluationState,
};
use std::str::FromStr;
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -1,31 +1,32 @@
//! faster std.format impl
#![allow(clippy::too_many_arguments)]
-use crate::{
- create_error, create_error_result, to_string, Error, LocError, ObjValue, Val, ValType,
-};
+use crate::{error::Error::*, throw, to_string, LocError, ObjValue, Result, Val, ValType};
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub enum FormatError {
TruncatedFormatCode,
UnrecognizedConversionType(char),
- ValueError(LocError),
NotEnoughValues,
CannotUseStarWidthWithObject,
MappingKeysRequired,
- NoSuchField(Rc<str>),
+ NoSuchFormatField(Rc<str>),
}
-impl From<LocError> for FormatError {
- fn from(e: LocError) -> Self {
- Self::ValueError(e)
+
+impl From<FormatError> for LocError {
+ fn from(e: FormatError) -> Self {
+ Self::new(Format(e))
}
}
+
use std::rc::Rc;
use FormatError::*;
-pub fn try_parse_mapping_key(str: &str) -> Result<(&str, &str), FormatError> {
+type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;
+
+pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -84,7 +85,7 @@
pub sign: bool,
}
-pub fn try_parse_cflags(str: &str) -> Result<(CFlags, &str), FormatError> {
+pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -113,7 +114,7 @@
Star,
Fixed(usize),
}
-pub fn try_parse_field_width(str: &str) -> Result<(Width, &str), FormatError> {
+pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -134,7 +135,7 @@
Ok((Width::Fixed(out), &str[digits..]))
}
-pub fn try_parse_precision(str: &str) -> Result<(Option<Width>, &str), FormatError> {
+pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -147,7 +148,7 @@
}
// Only skips
-pub fn try_parse_length_modifier(str: &str) -> Result<&str, FormatError> {
+pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -159,10 +160,10 @@
return Err(TruncatedFormatCode);
}
}
- Ok(&str[idx..])
+ Ok(((), &str[idx..]))
}
-#[derive(Debug)]
+#[derive(Debug, PartialEq)]
pub enum ConvTypeV {
Decimal,
Octal,
@@ -179,7 +180,7 @@
caps: bool,
}
-pub fn parse_conversion_type(str: &str) -> Result<(ConvType, &str), FormatError> {
+pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -214,7 +215,7 @@
convtype: ConvTypeV,
caps: bool,
}
-pub fn parse_code(str: &str) -> Result<(Code, &str), FormatError> {
+pub fn parse_code(str: &str) -> ParseResult<Code> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -222,7 +223,7 @@
let (cflags, str) = try_parse_cflags(str)?;
let (width, str) = try_parse_field_width(str)?;
let (precision, str) = try_parse_precision(str)?;
- let str = try_parse_length_modifier(str)?;
+ let (_, str) = try_parse_length_modifier(str)?;
let (convtype, str) = parse_conversion_type(str)?;
Ok((
@@ -243,7 +244,7 @@
String(&'s str),
Code(Code<'s>),
}
-pub fn parse_codes(mut str: &str) -> Result<Vec<Element>, FormatError> {
+pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {
let mut bytes = str.as_bytes();
let mut out = vec![];
let mut offset = 0;
@@ -453,7 +454,7 @@
code: &Code,
width: usize,
precision: Option<usize>,
-) -> Result<(), FormatError> {
+) -> Result<()> {
let clfags = &code.cflags;
let (fpprec, iprec) = match precision {
Some(v) => (v, v),
@@ -565,22 +566,22 @@
ConvTypeV::Char => match value.clone().unwrap_if_lazy()? {
Val::Num(n) => tmp_out.push(
std::char::from_u32(n as u32)
- .ok_or_else(|| create_error(Error::InvalidUnicodeCodepointGot(n as u32)))?,
+ .ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
),
Val::Str(s) => {
if s.chars().count() != 1 {
- create_error_result(Error::RuntimeError(
+ throw!(RuntimeError(
format!("%c expected 1 char string, got {}", s.chars().count()).into(),
- ))?;
+ ));
}
tmp_out.push_str(&s);
}
_ => {
- create_error_result(Error::TypeMismatch(
+ throw!(TypeMismatch(
"%c requires number/string",
vec![ValType::Num, ValType::Str],
value.value_type()?,
- ))?;
+ ));
}
},
ConvTypeV::Percent => tmp_out.push('%'),
@@ -603,7 +604,7 @@
Ok(())
}
-pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String, FormatError> {
+pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {
let codes = parse_codes(&str)?;
let mut out = String::new();
@@ -616,7 +617,7 @@
let width = match c.width {
Width::Star => {
if values.is_empty() {
- return Err(FormatError::NotEnoughValues);
+ throw!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -627,7 +628,7 @@
let precision = match c.precision {
Some(Width::Star) => {
if values.is_empty() {
- return Err(FormatError::NotEnoughValues);
+ throw!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -642,7 +643,7 @@
&Val::Null
} else {
if values.is_empty() {
- return Err(FormatError::NotEnoughValues);
+ throw!(NotEnoughValues);
}
let value = &values[0];
values = &values[1..];
@@ -657,7 +658,7 @@
Ok(out)
}
-pub fn format_obj(str: &str, values: &ObjValue) -> Result<String, FormatError> {
+pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
let codes = parse_codes(&str)?;
let mut out = String::new();
@@ -670,17 +671,17 @@
// TODO: Operate on ref
let f: Rc<str> = c.mkey.into();
if f.is_empty() {
- return Err(FormatError::MappingKeysRequired);
+ throw!(MappingKeysRequired);
}
let width = match c.width {
Width::Star => {
- return Err(FormatError::CannotUseStarWidthWithObject);
+ throw!(CannotUseStarWidthWithObject);
}
Width::Fixed(n) => n,
};
let precision = match c.precision {
Some(Width::Star) => {
- return Err(FormatError::CannotUseStarWidthWithObject);
+ throw!(CannotUseStarWidthWithObject);
}
Some(Width::Fixed(n)) => Some(n),
None => None,
@@ -688,7 +689,7 @@
let value = if let Some(v) = values.get(f.clone())? {
v
} else {
- return Err(FormatError::NoSuchField(f));
+ throw!(NoSuchFormatField(f));
};
format_code(&mut out, &value, &c, width, precision)?;
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -1,5 +1,5 @@
use crate::{
- create_error, future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val, Error,
+ error::Error::*, future_wrapper, map::LayeredHashMap, rc_fn_helper, resolved_lazy_val,
LazyBinding, LazyVal, ObjValue, Result, Val,
};
use std::{
@@ -61,11 +61,12 @@
}
pub fn binding(&self, name: Rc<str>) -> Result<LazyVal> {
- self.0
+ Ok(self
+ .0
.bindings
.get(&name)
.cloned()
- .ok_or_else(|| create_error(Error::UnknownVariable(name)))
+ .ok_or_else(|| UnknownVariable(name))?)
}
pub fn into_future(self, ctx: FutureContext) -> Context {
{
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,4 +1,4 @@
-use crate::{Val, ValType};
+use crate::{builtin::format::FormatError, Val, ValType};
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use std::{path::PathBuf, rc::Rc};
@@ -61,7 +61,14 @@
ImportCallbackError(String),
InvalidUnicodeCodepointGot(u32),
+
+ Format(FormatError),
}
+impl From<Error> for LocError {
+ fn from(e: Error) -> Self {
+ Self(e, StackTrace(vec![]))
+ }
+}
#[derive(Clone, Debug)]
pub struct StackTraceElement {
@@ -73,4 +80,17 @@
#[derive(Debug, Clone)]
pub struct LocError(pub Error, pub StackTrace);
+impl LocError {
+ pub fn new(e: Error) -> Self {
+ Self(e, StackTrace(vec![]))
+ }
+}
+
pub type Result<V> = std::result::Result<V, LocError>;
+
+#[macro_export]
+macro_rules! throw {
+ ($e: expr) => {
+ return Err($e.into());
+ };
+}
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -1,9 +1,10 @@
use crate::{
builtin::format::{format_arr, format_obj},
- context_creator, create_error, create_error_result, equals, escape_string_json, future_wrapper,
- lazy_val, manifest_json_ex, parse_args, primitive_equals, push, with_state, Context,
- ContextCreator, Error, FuncDesc, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,
- ValType,
+ context_creator, equals,
+ error::Error::*,
+ escape_string_json, future_wrapper, lazy_val, manifest_json_ex, parse_args, primitive_equals,
+ push, throw, with_state, Context, ContextCreator, FuncDesc, LazyBinding, LazyVal, LocError,
+ ObjMember, ObjValue, Result, Val, ValType,
};
use closure::closure;
use jrsonnet_parser::{
@@ -11,7 +12,7 @@
ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,
Visibility,
};
-use std::{cmp::Ordering, collections::HashMap, rc::Rc};
+use std::{cmp::Ordering, collections::HashMap, path::PathBuf, rc::Rc};
pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {
let b = b.clone();
@@ -79,10 +80,7 @@
(UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),
(UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),
(UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),
- (op, o) => create_error_result(Error::UnaryOperatorDoesNotOperateOnType(
- op,
- o.value_type()?,
- ))?,
+ (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),
})
}
@@ -100,11 +98,11 @@
(Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),
(Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),
(Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,
- _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(
+ _ => throw!(BinaryOperatorDoesNotOperateOnValues(
BinaryOpType::Add,
a.value_type()?,
b.value_type()?,
- ))?,
+ )),
})
}
@@ -145,7 +143,7 @@
(Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,
(Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {
if *v2 <= f64::EPSILON {
- create_error_result(crate::Error::DivisionByZero)?
+ throw!(DivisionByZero)
}
Val::new_checked_num(v1 / v2)?
}
@@ -168,22 +166,22 @@
}
(Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {
if *v2 < 0.0 {
- create_error_result(Error::RuntimeError("shift by negative exponent".into()))?
+ throw!(RuntimeError("shift by negative exponent".into()))
}
Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)
}
(Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {
if *v2 < 0.0 {
- create_error_result(Error::RuntimeError("shift by negative exponent".into()))?
+ throw!(RuntimeError("shift by negative exponent".into()))
}
Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)
}
- _ => create_error_result(Error::BinaryOperatorDoesNotOperateOnValues(
+ _ => throw!(BinaryOperatorDoesNotOperateOnValues(
op,
a.value_type()?,
b.value_type()?,
- ))?,
+ )),
})
}
@@ -218,7 +216,7 @@
}
Some(out.into_iter().flatten().flatten().collect())
}
- _ => create_error_result(Error::InComprehensionCanOnlyIterateOverArray)?,
+ _ => throw!(InComprehensionCanOnlyIterateOverArray),
}
}
})
@@ -379,7 +377,7 @@
},
);
}
- v => create_error_result(Error::FieldMustBeStringGot(v.value_type()?))?,
+ v => throw!(FieldMustBeStringGot(v.value_type()?)),
}
}
@@ -409,7 +407,7 @@
Ok(match value {
Val::Intristic(ns, name) => match (&ns as &str, &name as &str) {
// arr/string/function
- ("std", "length") => noinline!(parse_args!(context, "std.length", args, 1, [
+ ("std", "length") => parse_args!(context, "std.length", args, 1, [
0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];
], {
Ok(match x {
@@ -423,20 +421,20 @@
),
_ => unreachable!(),
})
- }))?,
+ })?,
// any
("std", "type") => parse_args!(context, "std.type", args, 1, [
0, x, vec![];
], {
- Val::Str(x.value_type()?.name().into())
- }),
+ Ok(Val::Str(x.value_type()?.name().into()))
+ })?,
// length, idx=>any
("std", "makeArray") => noinline!(parse_args!(context, "std.makeArray", args, 2, [
0, sz: [Val::Num]!!Val::Num, vec![ValType::Num];
1, func: [Val::Func]!!Val::Func, vec![ValType::Func];
], {
if sz < 0.0 {
- create_error_result(crate::error::Error::RuntimeError(format!("makeArray requires size >= 0, got {}", sz).into()))?;
+ throw!(RuntimeError(format!("makeArray requires size >= 0, got {}", sz).into()));
}
let mut out = Vec::with_capacity(sz as usize);
for i in 0..sz as usize {
@@ -455,8 +453,8 @@
str.chars().count() == 1,
"std.codepoint should receive single char string"
);
- Val::Num(str.chars().take(1).next().unwrap() as u32 as f64)
- }),
+ Ok(Val::Num(str.chars().take(1).next().unwrap() as u32 as f64))
+ })?,
// object, includeHidden
("std", "objectFieldsEx") => {
noinline!(parse_args!(context, "std.objectFieldsEx",args, 2, [
@@ -478,42 +476,42 @@
1, f: [Val::Str]!!Val::Str, vec![ValType::Str];
2, inc_hidden: [Val::Bool]!!Val::Bool, vec![ValType::Bool];
], {
- Val::Bool(
+ Ok(Val::Bool(
obj.fields_visibility()
.into_iter()
.filter(|(_k, v)| *v || inc_hidden)
.any(|(k, _v)| *k == *f),
- )
- }),
+ ))
+ })?,
("std", "primitiveEquals") => parse_args!(context, "std.primitiveEquals", args, 2, [
0, a, vec![];
1, b, vec![];
], {
- Val::Bool(primitive_equals(&a, &b)?)
- }),
+ Ok(Val::Bool(primitive_equals(&a, &b)?))
+ })?,
// faster
("std", "equals") => parse_args!(context, "std.equals", args, 2, [
0, a, vec![];
1, b, vec![];
], {
- Val::Bool(equals(&a, &b)?)
- }),
+ Ok(Val::Bool(equals(&a, &b)?))
+ })?,
("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [
0, a: [Val::Num]!!Val::Num, vec![ValType::Num];
1, b: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
- Val::Num(a % b)
- }),
+ Ok(Val::Num(a % b))
+ })?,
("std", "floor") => parse_args!(context, "std.floor", args, 1, [
0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
- Val::Num(x.floor())
- }),
+ Ok(Val::Num(x.floor()))
+ })?,
("std", "log") => parse_args!(context, "std.log", args, 2, [
0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
- Val::Num(n.ln())
- }),
+ Ok(Val::Num(n.ln()))
+ })?,
("std", "trace") => parse_args!(context, "std.trace", args, 2, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
1, rest, vec![];
@@ -526,21 +524,21 @@
});
}
eprintln!(" {}", str);
- rest
- }),
+ Ok(rest)
+ })?,
("std", "pow") => parse_args!(context, "std.modulo", args, 2, [
0, x: [Val::Num]!!Val::Num, vec![ValType::Num];
1, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
- Val::Num(x.powf(n))
- }),
+ Ok(Val::Num(x.powf(n)))
+ })?,
("std", "extVar") => parse_args!(context, "std.extVar", args, 2, [
0, x: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
- with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(
- || create_error(crate::Error::UndefinedExternalVariable(x)),
- )?
- }),
+ Ok(with_state(|s| s.settings().ext_vars.get(&x).cloned()).ok_or_else(
+ || UndefinedExternalVariable(x),
+ )?)
+ })?,
("std", "filter") => noinline!(parse_args!(context, "std.filter", args, 2, [
0, func: [Val::Func]!!Val::Func, vec![ValType::Func];
1, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
@@ -583,6 +581,7 @@
Ok(acc)
}))?,
// faster
+ #[allow(non_snake_case)]
("std", "sortImpl") => noinline!(parse_args!(context, "std.sort", args, 2, [
0, arr: [Val::Arr]!!Val::Arr, vec![ValType::Arr];
1, keyF: [Val::Func]!!Val::Func, vec![ValType::Func];
@@ -598,7 +597,7 @@
match keyF.evaluate_values(context.clone(), &[k.clone()]) {
Ok(Val::Str(v)) => v,
Ok(_) => {
- err = Some(create_error(crate::error::Error::RuntimeError("types of all array elements should equal".into())));
+ err = Some(LocError::new(RuntimeError("types of all array elements should equal".into())));
"".into()
}
Err(e) => {
@@ -617,7 +616,7 @@
match (keyF.evaluate_values(context.clone(), &[a.clone()]), keyF.evaluate_values(context.clone(), &[b.clone()])) {
(Ok(Val::Num(a)), Ok(Val::Num(b))) => a.partial_cmp(&b).unwrap(),
(Ok(_a), Ok(_b)) => {
- err = Some(create_error(crate::error::Error::RuntimeError("types of all array elements should equal".into())));
+ err = Some(RuntimeError("types of all array elements should equal".into()).into());
Ordering::Equal
}
(Err(e), _) | (_, Err(e)) => {
@@ -630,21 +629,23 @@
return Err(e);
}
},
- _ => return Err(create_error(crate::error::Error::RuntimeError("keys should be number or string".into())))
+ _ => throw!(RuntimeError("keys should be number or string".into()))
}
Ok(Val::Arr(Rc::new(new_arr)))
}))?,
// faster
("std", "format") => parse_args!(context, "std.format", args, 2, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
- 1, vals: [Val::Arr|Val::Obj], vec![ValType::Arr, ValType::Obj];
+ 1, vals, vec![]
], {
- match vals {
- Val::Arr(vals) => Val::Str(format_arr(&str, &vals).unwrap().into()),
- Val::Obj(obj) => Val::Str(format_obj(&str, &obj).unwrap().into()),
- _ => unreachable!()
- }
- }),
+ push(&Some(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)?.into()),
+ Val::Obj(obj) => Val::Str(format_obj(&str, &obj)?.into()),
+ o => Val::Str(format_arr(&str, &[o])?.into()),
+ })
+ })
+ })?,
// faster
("std", "range") => parse_args!(context, "std.range", args, 2, [
0, from: [Val::Num]!!Val::Num, vec![ValType::Num];
@@ -654,22 +655,22 @@
for i in from as usize..=to as usize {
out.push(Val::Num(i as f64));
}
- Val::Arr(Rc::new(out))
- }),
+ Ok(Val::Arr(Rc::new(out)))
+ })?,
("std", "char") => parse_args!(context, "std.char", args, 1, [
0, n: [Val::Num]!!Val::Num, vec![ValType::Num];
], {
let mut out = String::new();
out.push(std::char::from_u32(n as u32).ok_or_else(||
- create_error(crate::error::Error::InvalidUnicodeCodepointGot(n as u32))
+ InvalidUnicodeCodepointGot(n as u32)
)?);
Ok(Val::Str(out.into()))
})?,
("std", "encodeUTF8") => parse_args!(context, "std.encodeUtf8", args, 1, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
- Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect()))
- }),
+ Ok(Val::Arr(Rc::new(str.bytes().map(|b| Val::Num(b as f64)).collect())))
+ })?,
("std", "md5") => noinline!(parse_args!(context, "std.md5", args, 1, [
0, str: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
@@ -679,7 +680,7 @@
("std", "base64") => parse_args!(context, "std.base64", args, 1, [
0, input: [Val::Str | Val::Arr], vec![ValType::Arr, ValType::Str];
], {
- Val::Str(match input {
+ Ok(Val::Str(match input {
Val::Str(s) => {
base64::encode(s.bytes().collect::<Vec<_>>()).into()
},
@@ -689,8 +690,8 @@
}).collect::<Result<Vec<_>>>()?).into()
},
_ => unreachable!()
- })
- }),
+ }))
+ })?,
// faster
("std", "join") => noinline!(parse_args!(context, "std.join", args, 2, [
0, sep: [Val::Str|Val::Arr], vec![ValType::Str, ValType::Arr];
@@ -711,7 +712,7 @@
out.reserve(items.len());
out.extend(items.iter().cloned());
} else {
- create_error_result(crate::Error::RuntimeError("in std.join all items should be arrays".into()))?;
+ throw!(RuntimeError("in std.join all items should be arrays".into()));
}
}
@@ -729,7 +730,7 @@
first = false;
out += &item;
} else {
- create_error_result(crate::Error::RuntimeError("in std.join all items should be strings".into()))?;
+ throw!(RuntimeError("in std.join all items should be strings".into()));
}
}
@@ -742,18 +743,16 @@
("std", "escapeStringJson") => parse_args!(context, "std.escapeStringJson", args, 1, [
0, str_: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
- Val::Str(escape_string_json(&str_).into())
- }),
+ Ok(Val::Str(escape_string_json(&str_).into()))
+ })?,
// Faster
("std", "manifestJsonEx") => parse_args!(context, "std.manifestJsonEx", args, 2, [
0, value, vec![];
1, indent: [Val::Str]!!Val::Str, vec![ValType::Str];
], {
- Val::Str(manifest_json_ex(&value, &indent)?.into())
- }),
- (ns, name) => {
- create_error_result(crate::Error::IntristicNotFound(ns.into(), name.into()))?
- }
+ Ok(Val::Str(manifest_json_ex(&value, &indent)?.into()))
+ })?,
+ (ns, name) => throw!(IntristicNotFound(ns.into(), name.into())),
},
Val::Func(f) => {
let body = || f.evaluate(context, args, tailstrict);
@@ -763,7 +762,7 @@
push(loc, || format!("function <{}> call", f.name), body)?
}
}
- v => create_error_result(crate::Error::OnlyFunctionsCanBeCalledGot(v.value_type()?))?,
+ v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),
})
}
@@ -784,13 +783,13 @@
context
.this()
.clone()
- .ok_or_else(|| create_error(crate::Error::CantUseSelfOutsideOfObject))?,
+ .ok_or_else(|| CantUseSelfOutsideOfObject)?,
),
Literal(LiteralType::Dollar) => Val::Obj(
context
.dollar()
.clone()
- .ok_or_else(|| create_error(crate::Error::NoTopLevelObjectFound))?,
+ .ok_or_else(|| NoTopLevelObjectFound)?,
),
Literal(LiteralType::True) => Val::Bool(true),
Literal(LiteralType::False) => Val::Bool(false),
@@ -825,34 +824,30 @@
} else if let Some(Val::Str(n)) = v.get("__intristic_namespace__".into())? {
Val::Intristic(n, s)
} else {
- create_error_result(crate::Error::NoSuchField(s))?
+ throw!(NoSuchField(s))
}
}
- (Val::Obj(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(
+ (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
ValType::Obj,
ValType::Str,
n.value_type()?,
- ))?,
+ )),
(Val::Arr(v), Val::Num(n)) => {
if n.fract() > f64::EPSILON {
- create_error_result(crate::Error::FractionalIndex)?
+ throw!(FractionalIndex)
}
v.get(n as usize)
- .ok_or_else(|| {
- create_error(crate::Error::ArrayBoundsError(n as usize, v.len()))
- })?
+ .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
.clone()
.unwrap_if_lazy()?
- }
- (Val::Arr(_), Val::Str(n)) => {
- create_error_result(crate::Error::AttemptedIndexAnArrayWithString(n))?
}
- (Val::Arr(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(
+ (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
+ (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
ValType::Arr,
ValType::Num,
n.value_type()?,
- ))?,
+ )),
(Val::Str(s), Val::Num(n)) => Val::Str(
s.chars()
@@ -861,13 +856,13 @@
.collect::<String>()
.into(),
),
- (Val::Str(_), n) => create_error_result(crate::Error::ValueIndexMustBeTypeGot(
+ (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
ValType::Str,
ValType::Num,
n.value_type()?,
- ))?,
+ )),
- (v, _) => create_error_result(crate::Error::CantIndexInto(v.value_type()?))?,
+ (v, _) => throw!(CantIndexInto(v.value_type()?)),
}
}
LocalExpr(bindings, returned) => {
@@ -926,18 +921,18 @@
if assertion_result {
evaluate(context, returned)?
} else if let Some(msg) = msg {
- create_error_result(crate::Error::AssertionFailed(evaluate(context, msg)?))?
+ throw!(AssertionFailed(evaluate(context, msg)?));
} else {
- create_error_result(crate::Error::AssertionFailed(Val::Null))?
+ throw!(AssertionFailed(Val::Null));
}
}
- Error(e) => push(
+ ErrorStmt(e) => push(
&loc,
|| "error statement".to_owned(),
|| {
- create_error_result(crate::Error::RuntimeError(
+ throw!(RuntimeError(
evaluate(context, e)?.try_cast_str("error text should be string")?,
- ))?
+ ))
},
)?,
IfElse {
@@ -978,6 +973,6 @@
import_location.pop();
Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
}
- Literal(LiteralType::Super) => return create_error_result(crate::Error::StandaloneSuper),
+ Literal(LiteralType::Super) => throw!(StandaloneSuper),
})
}
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -1,7 +1,4 @@
-use crate::{
- create_error, create_error_result, evaluate, lazy_val, resolved_lazy_val, Context, Error,
- Result, Val,
-};
+use crate::{error::Error::*, evaluate, lazy_val, resolved_lazy_val, throw, Context, Result, Val};
use closure::closure;
use jrsonnet_parser::{ArgsDesc, ParamsDesc};
use std::{collections::HashMap, rc::Rc};
@@ -30,16 +27,16 @@
params
.iter()
.position(|p| *p.0 == *name)
- .ok_or_else(|| create_error(Error::UnknownFunctionParameter(name.clone())))?
+ .ok_or_else(|| UnknownFunctionParameter(name.clone()))?
} else {
id
};
if idx >= params.len() {
- create_error_result(Error::TooManyArgsFunctionHas(params.len()))?;
+ throw!(TooManyArgsFunctionHas(params.len()));
}
if positioned_args[idx].is_some() {
- create_error_result(Error::BindingParameterASecondTime(params[idx].0.clone()))?;
+ throw!(BindingParameterASecondTime(params[idx].0.clone()));
}
positioned_args[idx] = Some(arg.1.clone());
}
@@ -50,8 +47,7 @@
} else if let Some(default) = &p.1 {
(body_ctx.clone().expect(NO_DEFAULT_CONTEXT), default)
} else {
- create_error_result(Error::FunctionParameterNotBoundInCall(p.0.clone()))?;
- unreachable!()
+ throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
let val = if tailstrict {
resolved_lazy_val!(evaluate(ctx, expr)?)
@@ -74,15 +70,16 @@
let mut out = HashMap::new();
let mut positioned_args = vec![None; params.0.len()];
for (name, val) in args.iter() {
- let idx = params.iter().position(|p| *p.0 == **name).ok_or_else(|| {
- create_error(Error::UnknownFunctionParameter((&name as &str).to_owned()))
- })?;
+ let idx = params
+ .iter()
+ .position(|p| *p.0 == **name)
+ .ok_or_else(|| UnknownFunctionParameter((&name as &str).to_owned()))?;
if idx >= params.len() {
- create_error_result(Error::TooManyArgsFunctionHas(params.len()))?;
+ throw!(TooManyArgsFunctionHas(params.len()));
}
if positioned_args[idx].is_some() {
- create_error_result(Error::BindingParameterASecondTime(params[idx].0.clone()))?;
+ throw!(BindingParameterASecondTime(params[idx].0.clone()));
}
positioned_args[idx] = Some(val.clone());
}
@@ -104,8 +101,7 @@
})
}
} else {
- create_error_result(Error::FunctionParameterNotBoundInCall(p.0.clone()))?;
- unreachable!()
+ throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
out.insert(p.0.clone(), val);
}
@@ -123,7 +119,7 @@
let mut positioned_args = vec![None; params.0.len()];
for (id, arg) in args.iter().enumerate() {
if id >= params.len() {
- create_error_result(Error::TooManyArgsFunctionHas(params.len()))?;
+ throw!(TooManyArgsFunctionHas(params.len()));
}
positioned_args[id] = Some(arg);
}
@@ -134,8 +130,7 @@
} else if let Some(default) = &p.1 {
evaluate(ctx.clone(), default)?
} else {
- create_error_result(Error::FunctionParameterNotBoundInCall(p.0.clone()))?;
- unreachable!()
+ throw!(FunctionParameterNotBoundInCall(p.0.clone()));
};
out.insert(p.0.clone(), resolved_lazy_val!(val));
}
@@ -148,36 +143,39 @@
($ctx: expr, $fn_name: expr, $args: expr, $total_args: expr, [
$($id: expr, $name: ident $(: [$($p: path)|+] $(!! $a: path)?)?, $nt: expr);+ $(;)?
], $handler:block) => {{
- use crate::Error;
+ use crate::{throw, error::Error::*};
let args = $args;
if args.len() > $total_args {
- create_error_result(Error::TooManyArgsFunctionHas($total_args))?;
+ throw!(TooManyArgsFunctionHas($total_args));
}
$(
if args.len() <= $id {
- create_error_result(Error::FunctionParameterNotBoundInCall(stringify!($name).into()))?;
+ throw!(FunctionParameterNotBoundInCall(stringify!($name).into()));
}
let $name = &args[$id];
if $name.0.is_some() {
if $name.0.as_ref().unwrap() != stringify!($name) {
- create_error_result(Error::IntristicArgumentReorderingIsNotSupportedYet)?;
+ throw!(IntristicArgumentReorderingIsNotSupportedYet);
}
}
let $name = evaluate($ctx.clone(), &$name.1)?;
$(
match $name {
$($p(_))|+ => {},
- _ => create_error_result(Error::TypeMismatch(concat!($fn_name, " ", stringify!($id), "nd (", stringify!($name), ") argument"), $nt, $name.value_type()?))?,
+ _ => throw!(TypeMismatch(
+ concat!($fn_name, " ", stringify!($id), "nd (", stringify!($name), ") argument"),
+ $nt, $name.value_type()?
+ )),
};
$(
let $name = match $name {
$a(v) => v,
- _ => create_error_result(Error::TypeMismatch(concat!($fn_name, " ", stringify!($id), "nd (", stringify!($name), ") argument"), $nt, $name.value_type()?))?,
+ _ =>throw!(TypeMismatch(concat!($fn_name, " ", stringify!($id), "nd (", stringify!($name), ") argument"), $nt, $name.value_type()?)),
};
)*
)*
)+
- $handler
+ ($handler as crate::Result<_>)
}};
}
@@ -198,7 +196,9 @@
], {
assert!((a - 2.0).abs() <= f64::EPSILON);
assert!((b - 1.0).abs() <= f64::EPSILON);
- });
+ Ok(())
+ })
+ .unwrap();
Ok(())
})
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,7 +1,6 @@
-use crate::create_error_result;
use crate::{
- create_error,
- error::{Error, Result},
+ error::{Error::*, Result},
+ throw,
};
use fs::File;
use std::fs;
@@ -28,7 +27,7 @@
pub struct DummyImportResolver;
impl ImportResolver for DummyImportResolver {
fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
- create_error_result(Error::ImportNotSupported(from.clone(), path.clone()))
+ throw!(ImportNotSupported(from.clone(), path.clone()))
}
fn load_file_contents(&self, _resolved: &PathBuf) -> Result<Rc<str>> {
// Can be only caused by library direct consumer, not by supplied jsonnet
@@ -65,15 +64,14 @@
return Ok(Rc::new(cloned));
}
}
- create_error_result(Error::ImportFileNotFound(from.clone(), path.clone()))
+ throw!(ImportFileNotFound(from.clone(), path.clone()))
}
}
fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {
- let mut file =
- File::open(id).map_err(|_e| create_error(Error::ResolvedFileNotFound(id.clone())))?;
+ let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
let mut out = String::new();
file.read_to_string(&mut out)
- .map_err(|_e| create_error(Error::ImportBadFileUtf8(id.clone())))?;
+ .map_err(|_e| ImportBadFileUtf8(id.clone()))?;
Ok(out.into())
}
unsafe fn as_any(&self) -> &dyn Any {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -10,7 +10,7 @@
mod builtin;
mod ctx;
mod dynamic;
-mod error;
+pub mod error;
mod evaluate;
mod function;
mod import;
@@ -21,7 +21,7 @@
pub use ctx::*;
pub use dynamic::*;
-pub use error::*;
+use error::{Error::*, LocError, Result, StackTraceElement};
pub use evaluate::*;
pub use function::parse_function_call;
pub use import::*;
@@ -131,13 +131,7 @@
}
pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
-}
-pub fn create_error(err: Error) -> LocError {
- LocError(err, StackTrace(vec![]))
}
-pub fn create_error_result<T>(err: Error) -> Result<T> {
- Err(LocError(err, StackTrace(vec![])))
-}
pub(crate) fn push<T>(
e: &Option<ExprLocation>,
frame_desc: impl FnOnce() -> String,
@@ -167,12 +161,10 @@
loc_data: true,
},
)
- .map_err(|error| {
- create_error(Error::ImportSyntaxError {
- error,
- path,
- source_code,
- })
+ .map_err(|error| ImportSyntaxError {
+ error,
+ path,
+ source_code,
})?,
)?;
@@ -292,7 +284,7 @@
if *stack_depth > self.max_stack() {
// Error creation uses data, so i drop guard here
drop(data);
- return Err(create_error(Error::StackOverflow));
+ throw!(StackOverflow);
} else {
*stack_depth += 1;
}
@@ -340,7 +332,7 @@
ManifestFormat::Json(padding) => val.into_json(padding)?,
ManifestFormat::None => match val {
Val::Str(s) => s,
- _ => return Err(create_error(Error::StringManifestOutputIsNotAString)),
+ _ => throw!(StringManifestOutputIsNotAString),
},
})
})
@@ -476,7 +468,7 @@
#[cfg(test)]
pub mod tests {
use super::Val;
- use crate::{create_error, primitive_equals, EvaluationState};
+ use crate::{error::Error::*, primitive_equals, EvaluationState};
use jrsonnet_parser::*;
use std::{path::PathBuf, rc::Rc};
@@ -493,7 +485,7 @@
state.push(
&ExprLocation(Rc::new(PathBuf::from("test2.jsonnet")), 30, 40),
|| "inner".to_owned(),
- || Err(create_error(crate::error::Error::RuntimeError("".into()))),
+ || Err(RuntimeError("".into()).into()),
)?;
Ok(())
},
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -11,11 +11,13 @@
pub location: Option<ExprLocation>,
}
+// Field => This
+type CacheKey = (Rc<str>, usize);
#[derive(Debug)]
pub struct ObjValueInternals {
super_obj: Option<ObjValue>,
this_entries: Rc<HashMap<Rc<str>, ObjMember>>,
- value_cache: RefCell<HashMap<(Rc<str>, usize), Option<Val>>>,
+ value_cache: RefCell<HashMap<CacheKey, Option<Val>>>,
}
#[derive(Clone)]
pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,7 +1,8 @@
use crate::{
- create_error_result, evaluate,
+ error::Error::*,
+ evaluate,
function::{parse_function_call, parse_function_call_map, place_args},
- with_state, Context, Error, ObjValue, Result,
+ throw, with_state, Context, ObjValue, Result,
};
use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, LocExpr, ParamsDesc};
use std::{
@@ -157,14 +158,14 @@
if num.is_finite() {
Ok(Val::Num(num))
} else {
- create_error_result(Error::RuntimeError("overflow".into()))
+ throw!(RuntimeError("overflow".into()))
}
}
pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {
let this_type = self.value_type()?;
if this_type != val_type {
- create_error_result(Error::TypeMismatch(context, vec![val_type], this_type))
+ throw!(TypeMismatch(context, vec![val_type], this_type))
} else {
Ok(())
}
@@ -263,15 +264,15 @@
(Val::Null, Val::Null) => true,
(Val::Str(a), Val::Str(b)) => a == b,
(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,
- (Val::Arr(_), Val::Arr(_)) => create_error_result(Error::RuntimeError(
+ (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(
"primitiveEquals operates on primitive types, got array".into(),
- ))?,
- (Val::Obj(_), Val::Obj(_)) => create_error_result(Error::RuntimeError(
+ )),
+ (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(
"primitiveEquals operates on primitive types, got object".into(),
- ))?,
- (a, b) if is_function_like(&a) && is_function_like(&b) => create_error_result(
- Error::RuntimeError("cannot test equality of functions".into()),
- )?,
+ )),
+ (a, b) if is_function_like(&a) && is_function_like(&b) => {
+ throw!(RuntimeError("cannot test equality of functions".into()))
+ }
(_, _) => false,
})
}
@@ -376,7 +377,7 @@
buf.push('}');
}
Val::Func(_) | Val::Intristic(_, _) => {
- create_error_result(Error::RuntimeError("tried to manifest function".into()))?
+ throw!(RuntimeError("tried to manifest function".into()))
}
Val::Lazy(_) => unreachable!(),
};
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -258,7 +258,7 @@
/// importStr "file.txt"
ImportStr(PathBuf),
/// error "I'm broken"
- Error(LocExpr),
+ ErrorStmt(LocExpr),
/// a(b, c)
Apply(LocExpr, ArgsDesc, bool),
/// a[b]
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth1#![feature(box_syntax)]2#![feature(test)]34extern crate test;56use peg::parser;7use std::{path::PathBuf, rc::Rc};8mod expr;9pub use expr::*;10pub use peg;1112#[derive(Default)]13pub struct ParserSettings {14 pub loc_data: bool,15 pub file_name: Rc<PathBuf>,16}1718parser! {19 grammar jsonnet_parser() for str {20 use peg::ParseLiteral;2122 /// Standard C-like comments23 rule comment()24 = "//" (!['\n'][_])* "\n"25 / "/*" ("\\*/" / "\\\\" / (!("*/")[_]))* "*/"26 / "#" (!['\n'][_])* "\n"2728 rule single_whitespace() = quiet!{([' ' | '\r' | '\n' | '\t'] / comment())} / expected!("<whitespace>")29 rule _() = single_whitespace()*3031 /// For comma-delimited elements32 rule comma() = quiet!{_ "," _} / expected!("<comma>")33 rule alpha() -> char = c:$(['_' | 'a'..='z' | 'A'..='Z']) {c.chars().next().unwrap()}34 rule digit() -> char = d:$(['0'..='9']) {d.chars().next().unwrap()}35 rule end_of_ident() = !['0'..='9' | '_' | 'a'..='z' | 'A'..='Z']36 /// Sequence of digits37 rule uint() -> u64 = a:$(digit()+) { a.parse().unwrap() }38 /// Number in scientific notation format39 rule number() -> f64 = quiet!{a:$(uint() ("." uint())? (['e'|'E'] (s:['+'|'-'])? uint())?) { a.parse().unwrap() }} / expected!("<number>")4041 /// Reserved word followed by any non-alphanumberic42 rule reserved() = ("assert" / "else" / "error" / "false" / "for" / "function" / "if" / "import" / "importstr" / "in" / "local" / "null" / "tailstrict" / "then" / "self" / "super" / "true") end_of_ident()43 rule id() = quiet!{ !reserved() alpha() (alpha() / digit())*} / expected!("<identifier>")4445 rule keyword(id: &'static str)46 = ##parse_string_literal(id) end_of_ident()47 // Adds location data information to existing expression48 rule l(s: &ParserSettings, x: rule<Expr>) -> LocExpr49 = start:position!() v:x() end:position!() {loc_expr!(v, s.loc_data, (s.file_name.clone(), start, end))}5051 pub rule param(s: &ParserSettings) -> expr::Param = name:$(id()) expr:(_ "=" _ expr:expr(s){expr})? { expr::Param(name.into(), expr) }52 pub rule params(s: &ParserSettings) -> expr::ParamsDesc53 = params:param(s) ** comma() comma()? {54 let mut defaults_started = false;55 for param in ¶ms {56 defaults_started = defaults_started || param.1.is_some();57 assert_eq!(defaults_started, param.1.is_some(), "defauld parameters should be used after all positionals");58 }59 expr::ParamsDesc(Rc::new(params))60 }61 / { expr::ParamsDesc(Rc::new(Vec::new())) }6263 pub rule arg(s: &ParserSettings) -> expr::Arg64 = name:$(id()) _ "=" _ expr:expr(s) {expr::Arg(Some(name.into()), expr)}65 / expr:expr(s) {expr::Arg(None, expr)}66 pub rule args(s: &ParserSettings) -> expr::ArgsDesc67 = args:arg(s) ** comma() comma()? {68 let mut named_started = false;69 for arg in &args {70 named_started = named_started || arg.0.is_some();71 assert_eq!(named_started, arg.0.is_some(), "named args should be used after all positionals");72 }73 expr::ArgsDesc(args)74 }75 / { expr::ArgsDesc(Vec::new()) }7677 pub rule bind(s: &ParserSettings) -> expr::BindSpec78 = name:$(id()) _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: None, value: expr}}79 / name:$(id()) _ "(" _ params:params(s) _ ")" _ "=" _ expr:expr(s) {expr::BindSpec{name:name.into(), params: Some(params), value: expr}}80 pub rule assertion(s: &ParserSettings) -> expr::AssertStmt81 = keyword("assert") _ cond:expr(s) msg:(_ ":" _ e:expr(s) {e})? { expr::AssertStmt(cond, msg) }8283 pub rule whole_line() -> &'input str84 = str:$((!['\n'][_])* "\n") {str}85 pub rule string_block() -> String86 = "|||" (!['\n']single_whitespace())* "\n"87 prefix:[' ' | '\t']+ first_line:whole_line()88 lines:([' ' | '\t']*<{prefix.len()}> s:whole_line() {s})*89 [' ' | '\t']*<, {prefix.len() - 1}> "|||"90 {let mut l = first_line.to_owned(); l.extend(lines); l}91 pub rule string() -> String92 = "\"" str:$(("\\\"" / "\\\\" / (!['"'][_]))*) "\"" {unescape::unescape(str).unwrap()}93 / "'" str:$(("\\'" / "\\\\" / (!['\''][_]))*) "'" {unescape::unescape(str).unwrap()}94 / "@'" str:$(("''" / (!['\''][_]))*) "'" {str.replace("''", "'")}95 / "@\"" str:$(("\"\"" / (!['"'][_]))*) "\"" {str.replace("\"\"", "\"")}96 / string_block()9798 pub rule field_name(s: &ParserSettings) -> expr::FieldName99 = name:$(id()) {expr::FieldName::Fixed(name.into())}100 / name:string() {expr::FieldName::Fixed(name.into())}101 / "[" _ expr:expr(s) _ "]" {expr::FieldName::Dyn(expr)}102 pub rule visibility() -> expr::Visibility103 = ":::" {expr::Visibility::Unhide}104 / "::" {expr::Visibility::Hidden}105 / ":" {expr::Visibility::Normal}106 pub rule field(s: &ParserSettings) -> expr::FieldMember107 = name:field_name(s) _ plus:"+"? _ visibility:visibility() _ value:expr(s) {expr::FieldMember{108 name,109 plus: plus.is_some(),110 params: None,111 visibility,112 value,113 }}114 / name:field_name(s) _ "(" _ params:params(s) _ ")" _ visibility:visibility() _ value:expr(s) {expr::FieldMember{115 name,116 plus: false,117 params: Some(params),118 visibility,119 value,120 }}121 pub rule obj_local(s: &ParserSettings) -> BindSpec122 = keyword("local") _ bind:bind(s) {bind}123 pub rule member(s: &ParserSettings) -> expr::Member124 = bind:obj_local(s) {expr::Member::BindStmt(bind)}125 / assertion:assertion(s) {expr::Member::AssertStmt(assertion)}126 / field:field(s) {expr::Member::Field(field)}127 pub rule objinside(s: &ParserSettings) -> expr::ObjBody128 = pre_locals:(b: obj_local(s) comma() {b})* "[" _ key:expr(s) _ "]" _ ":" _ value:expr(s) post_locals:(comma() b:obj_local(s) {b})* _ forspec:forspec(s) others:(_ rest:compspec(s) {rest})? {129 let mut compspecs = vec![CompSpec::ForSpec(forspec)];130 compspecs.extend(others.unwrap_or_default());131 expr::ObjBody::ObjComp(expr::ObjComp{132 pre_locals,133 key,134 value,135 post_locals,136 compspecs,137 })138 }139 / members:(member(s) ** comma()) comma()? {expr::ObjBody::MemberList(members)}140 pub rule ifspec(s: &ParserSettings) -> IfSpecData141 = keyword("if") _ expr:expr(s) {IfSpecData(expr)}142 pub rule forspec(s: &ParserSettings) -> ForSpecData143 = keyword("for") _ id:$(id()) _ keyword("in") _ cond:expr(s) {ForSpecData(id.into(), cond)}144 pub rule compspec(s: &ParserSettings) -> Vec<expr::CompSpec>145 = s:(i:ifspec(s) { expr::CompSpec::IfSpec(i) } / f:forspec(s) {expr::CompSpec::ForSpec(f)} ) ** _ {s}146 pub rule local_expr(s: &ParserSettings) -> LocExpr147 = l(s,<keyword("local") _ binds:bind(s) ** comma() _ ";" _ expr:expr(s) { Expr::LocalExpr(binds, expr) }>)148 pub rule string_expr(s: &ParserSettings) -> LocExpr149 = l(s, <s:string() {Expr::Str(s.into())}>)150 pub rule obj_expr(s: &ParserSettings) -> LocExpr151 = l(s,<"{" _ body:objinside(s) _ "}" {Expr::Obj(body)}>)152 pub rule array_expr(s: &ParserSettings) -> LocExpr153 = l(s,<"[" _ elems:(expr(s) ** comma()) _ comma()? "]" {Expr::Arr(elems)}>)154 pub rule array_comp_expr(s: &ParserSettings) -> LocExpr155 = l(s,<"[" _ expr:expr(s) _ comma()? _ forspec:forspec(s) _ others:(others: compspec(s) _ {others})? "]" {156 let mut specs = vec![CompSpec::ForSpec(forspec)];157 specs.extend(others.unwrap_or_default());158 Expr::ArrComp(expr, specs)159 }>)160 pub rule number_expr(s: &ParserSettings) -> LocExpr161 = l(s,<n:number() { expr::Expr::Num(n) }>)162 pub rule var_expr(s: &ParserSettings) -> LocExpr163 = l(s,<n:$(id()) { expr::Expr::Var(n.into()) }>)164 pub rule if_then_else_expr(s: &ParserSettings) -> LocExpr165 = l(s,<cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{166 cond,167 cond_then,168 cond_else,169 }}>)170171 pub rule literal(s: &ParserSettings) -> LocExpr172 = l(s,<v:(173 keyword("null") {LiteralType::Null}174 / keyword("true") {LiteralType::True}175 / keyword("false") {LiteralType::False}176 / keyword("self") {LiteralType::This}177 / keyword("$") {LiteralType::Dollar}178 / keyword("super") {LiteralType::Super}179 ) {Expr::Literal(v)}>)180181 pub rule expr_basic(s: &ParserSettings) -> LocExpr182 = literal(s)183184 / string_expr(s) / number_expr(s)185 / array_expr(s)186 / obj_expr(s)187 / array_expr(s)188 / array_comp_expr(s)189190 / l(s,<keyword("importstr") _ path:string() {Expr::ImportStr(PathBuf::from(path))}>)191 / l(s,<keyword("import") _ path:string() {Expr::Import(PathBuf::from(path))}>)192193 / var_expr(s)194 / local_expr(s)195 / if_then_else_expr(s)196197 / l(s,<keyword("function") _ "(" _ params:params(s) _ ")" _ expr:expr(s) {Expr::Function(params, expr)}>)198 / l(s,<assertion:assertion(s) _ ";" _ expr:expr(s) { Expr::AssertExpr(assertion, expr) }>)199200 / l(s,<keyword("error") _ expr:expr(s) { Expr::Error(expr) }>)201202 rule slice_part(s: &ParserSettings) -> Option<LocExpr>203 = e:(_ e:expr(s) _{e})? {e}204 pub rule slice_desc(s: &ParserSettings) -> SliceDesc205 = start:slice_part(s) ":" pair:(end:slice_part(s) step:(":" e:slice_part(s){e})? {(end, step.flatten())})? {206 let (end, step) = if let Some((end, step)) = pair {207 (end, step)208 }else{209 (None, None)210 };211212 SliceDesc { start, end, step }213 }214215 rule expr(s: &ParserSettings) -> LocExpr216 = start:position!() a:precedence! {217 a:(@) _ "||" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Or, b))}218 --219 a:(@) _ "&&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::And, b))}220 --221 a:(@) _ "|" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitOr, b))}222 --223 a:@ _ "^" _ b:(@) {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitXor, b))}224 --225 a:(@) _ "&" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::BitAnd, b))}226 --227 a:(@) _ "==" _ b:@ {loc_expr_todo!(Expr::Apply(228 el!(Expr::Index(229 el!(Expr::Var("std".into())),230 el!(Expr::Str("equals".into()))231 )),232 ArgsDesc(vec![Arg(None, a), Arg(None, b)]),233 true234 ))}235 a:(@) _ "!=" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, el!(Expr::Apply(236 el!(Expr::Index(237 el!(Expr::Var("std".into())),238 el!(Expr::Str("equals".into()))239 )),240 ArgsDesc(vec![Arg(None, a), Arg(None, b)]),241 true242 ))))}243 --244 a:(@) _ "<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lt, b))}245 a:(@) _ ">" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gt, b))}246 a:(@) _ "<=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lte, b))}247 a:(@) _ ">=" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Gte, b))}248 a:(@) _ keyword("in") _ b:@ {loc_expr_todo!(Expr::Apply(249 el!(Expr::Index(250 el!(Expr::Var("std".into())),251 el!(Expr::Str("objectHasEx".into()))252 )), ArgsDesc(vec![Arg(None, b), Arg(None, a), Arg(None, el!(Expr::Literal(LiteralType::True)))]),253 true254 ))}255 --256 a:(@) _ "<<" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Lhs, b))}257 a:(@) _ ">>" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Rhs, b))}258 --259 a:(@) _ "+" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Add, b))}260 a:(@) _ "-" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Sub, b))}261 --262 a:(@) _ "*" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Mul, b))}263 a:(@) _ "/" _ b:@ {loc_expr_todo!(Expr::BinaryOp(a, BinaryOpType::Div, b))}264 a:(@) _ "%" _ b:@ {loc_expr_todo!(Expr::Apply(265 el!(Expr::Index(266 el!(Expr::Var("std".into())),267 el!(Expr::Str("mod".into()))268 )), ArgsDesc(vec![Arg(None, a), Arg(None, b)]),269 true270 ))}271 --272 "-" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Minus, b))}273 "!" _ b:@ {loc_expr_todo!(Expr::UnaryOp(UnaryOpType::Not, b))}274 "~" _ b:@ { loc_expr_todo!(Expr::UnaryOp(UnaryOpType::BitNot, b)) }275 --276 a:(@) _ "[" _ s:slice_desc(s) _ "]" {loc_expr_todo!(Expr::Apply(277 el!(Expr::Index(278 el!(Expr::Var("std".into())),279 el!(Expr::Str("slice".into())),280 )),281 ArgsDesc(vec![282 Arg(None, a),283 Arg(None, s.start.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),284 Arg(None, s.end.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),285 Arg(None, s.step.unwrap_or_else(||el!(Expr::Literal(LiteralType::Null)))),286 ]),287 true,288 ))}289 a:(@) _ "." _ s:$(id()) {loc_expr_todo!(Expr::Index(a, el!(Expr::Str(s.into()))))}290 a:(@) _ "[" _ s:expr(s) _ "]" {loc_expr_todo!(Expr::Index(a, s))}291 a:(@) _ "(" _ args:args(s) _ ")" ts:(_ keyword("tailstrict"))? {loc_expr_todo!(Expr::Apply(a, args, ts.is_some()))}292 a:(@) _ "{" _ body:objinside(s) _ "}" {loc_expr_todo!(Expr::ObjExtend(a, body))}293 --294 e:expr_basic(s) {e}295 "(" _ e:expr(s) _ ")" {loc_expr_todo!(Expr::Parened(e))}296 } end:position!() {297 let LocExpr(e, _) = a;298 LocExpr(e, if s.loc_data {299 Some(ExprLocation(s.file_name.clone(), start, end))300 } else {301 None302 })303 }304 / e:expr_basic(s) {e}305306 pub rule jsonnet(s: &ParserSettings) -> LocExpr = _ e:expr(s) _ {e}307 }308}309310pub type ParseError = peg::error::ParseError<peg::str::LineCol>;311pub fn parse(str: &str, settings: &ParserSettings) -> Result<LocExpr, ParseError> {312 jsonnet_parser::jsonnet(str, settings)313}314315#[macro_export]316macro_rules! el {317 ($expr:expr) => {318 LocExpr(std::rc::Rc::new($expr), None)319 };320}321322#[cfg(test)]323pub mod tests {324 use super::{expr::*, parse};325 use crate::ParserSettings;326 use std::path::PathBuf;327 use std::rc::Rc;328329 macro_rules! parse {330 ($s:expr) => {331 parse(332 $s,333 &ParserSettings {334 loc_data: false,335 file_name: Rc::new(PathBuf::from("/test.jsonnet")),336 },337 )338 .unwrap()339 };340 }341342 mod expressions {343 use super::*;344345 pub fn basic_math() -> LocExpr {346 el!(Expr::BinaryOp(347 el!(Expr::Num(2.0)),348 BinaryOpType::Add,349 el!(Expr::BinaryOp(350 el!(Expr::Num(2.0)),351 BinaryOpType::Mul,352 el!(Expr::Num(2.0)),353 )),354 ))355 }356 }357358 #[test]359 fn multiline_string() {360 assert_eq!(361 parse!("|||\n Hello world!\n a\n|||"),362 el!(Expr::Str("Hello world!\n a\n".into())),363 );364 assert_eq!(365 parse!("|||\n Hello world!\n a\n|||"),366 el!(Expr::Str("Hello world!\n a\n".into())),367 );368 assert_eq!(369 parse!("|||\n\t\tHello world!\n\t\t\ta\n|||"),370 el!(Expr::Str("Hello world!\n\ta\n".into())),371 );372 assert_eq!(373 parse!("|||\n Hello world!\n a\n |||"),374 el!(Expr::Str("Hello world!\n a\n".into())),375 );376 }377378 #[test]379 fn slice() {380 parse!("a[1:]");381 parse!("a[1::]");382 parse!("a[:1:]");383 parse!("a[::1]");384 parse!("str[:len - 1]");385 }386387 #[test]388 fn string_escaping() {389 assert_eq!(390 parse!(r#""Hello, \"world\"!""#),391 el!(Expr::Str(r#"Hello, "world"!"#.into())),392 );393 assert_eq!(394 parse!(r#"'Hello \'world\'!'"#),395 el!(Expr::Str("Hello 'world'!".into())),396 );397 assert_eq!(parse!(r#"'\\\\'"#), el!(Expr::Str("\\\\".into())),);398 }399400 #[test]401 fn string_unescaping() {402 assert_eq!(403 parse!(r#""Hello\nWorld""#),404 el!(Expr::Str("Hello\nWorld".into())),405 );406 }407408 #[test]409 fn string_verbantim() {410 assert_eq!(411 parse!(r#"@"Hello\n""World""""#),412 el!(Expr::Str("Hello\\n\"World\"".into())),413 );414 }415416 #[test]417 fn imports() {418 assert_eq!(419 parse!("import \"hello\""),420 el!(Expr::Import(PathBuf::from("hello"))),421 );422 assert_eq!(423 parse!("importstr \"garnish.txt\""),424 el!(Expr::ImportStr(PathBuf::from("garnish.txt")))425 );426 }427428 #[test]429 fn empty_object() {430 assert_eq!(parse!("{}"), el!(Expr::Obj(ObjBody::MemberList(vec![]))));431 }432433 #[test]434 fn basic_math() {435 assert_eq!(436 parse!("2+2*2"),437 el!(Expr::BinaryOp(438 el!(Expr::Num(2.0)),439 BinaryOpType::Add,440 el!(Expr::BinaryOp(441 el!(Expr::Num(2.0)),442 BinaryOpType::Mul,443 el!(Expr::Num(2.0))444 ))445 ))446 );447 }448449 #[test]450 fn basic_math_with_indents() {451 assert_eq!(parse!("2 + 2 * 2 "), expressions::basic_math());452 }453454 #[test]455 fn basic_math_parened() {456 assert_eq!(457 parse!("2+(2+2*2)"),458 el!(Expr::BinaryOp(459 el!(Expr::Num(2.0)),460 BinaryOpType::Add,461 el!(Expr::Parened(expressions::basic_math())),462 ))463 );464 }465466 /// Comments should not affect parsing467 #[test]468 fn comments() {469 assert_eq!(470 parse!("2//comment\n+//comment\n3/*test*/*/*test*/4"),471 el!(Expr::BinaryOp(472 el!(Expr::Num(2.0)),473 BinaryOpType::Add,474 el!(Expr::BinaryOp(475 el!(Expr::Num(3.0)),476 BinaryOpType::Mul,477 el!(Expr::Num(4.0))478 ))479 ))480 );481 }482483 /// Comments should be able to be escaped484 #[test]485 fn comment_escaping() {486 assert_eq!(487 parse!("2/*\\*/+*/ - 22"),488 el!(Expr::BinaryOp(489 el!(Expr::Num(2.0)),490 BinaryOpType::Sub,491 el!(Expr::Num(22.0))492 ))493 );494 }495496 #[test]497 fn suffix() {498 // assert_eq!(parse!("std.test"), el!(Expr::Num(2.2)));499 // assert_eq!(parse!("std(2)"), el!(Expr::Num(2.2)));500 // assert_eq!(parse!("std.test(2)"), el!(Expr::Num(2.2)));501 // assert_eq!(parse!("a[b]"), el!(Expr::Num(2.2)))502 }503504 #[test]505 fn array_comp() {506 use Expr::*;507 assert_eq!(508 parse!("[std.deepJoin(x) for x in arr]"),509 el!(ArrComp(510 el!(Apply(511 el!(Index(el!(Var("std".into())), el!(Str("deepJoin".into())))),512 ArgsDesc(vec![Arg(None, el!(Var("x".into())))]),513 false,514 )),515 vec![CompSpec::ForSpec(ForSpecData(516 "x".into(),517 el!(Var("arr".into()))518 ))]519 )),520 )521 }522523 #[test]524 fn reserved() {525 use Expr::*;526 assert_eq!(parse!("null"), el!(Literal(LiteralType::Null)));527 assert_eq!(parse!("nulla"), el!(Var("nulla".into())));528 }529530 #[test]531 fn multiple_args_buf() {532 parse!("a(b, null_fields)");533 }534535 #[test]536 fn infix_precedence() {537 use Expr::*;538 assert_eq!(539 parse!("!a && !b"),540 el!(BinaryOp(541 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into())))),542 BinaryOpType::And,543 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()))))544 ))545 );546 }547548 #[test]549 fn infix_precedence_division() {550 use Expr::*;551 assert_eq!(552 parse!("!a / !b"),553 el!(BinaryOp(554 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into())))),555 BinaryOpType::Div,556 el!(UnaryOp(UnaryOpType::Not, el!(Var("b".into()))))557 ))558 );559 }560561 #[test]562 fn double_negation() {563 use Expr::*;564 assert_eq!(565 parse!("!!a"),566 el!(UnaryOp(567 UnaryOpType::Not,568 el!(UnaryOp(UnaryOpType::Not, el!(Var("a".into()))))569 ))570 )571 }572573 #[test]574 fn array_test_error() {575 parse!("[a for a in b if c for e in f]");576 // ^^^^ failed code577 }578579 #[test]580 fn can_parse_stdlib() {581 parse!(jrsonnet_stdlib::STDLIB_STR);582 }583584 use test::Bencher;585586 // From source code587 #[bench]588 fn bench_parse_peg(b: &mut Bencher) {589 b.iter(|| parse!(jrsonnet_stdlib::STDLIB_STR))590 }591}