difftreelog
style switch clippy to pedantic
in: master
25 files changed
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/format.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/format.rs
@@ -86,6 +86,7 @@
}
}
+#[allow(clippy::struct_excessive_bools)]
#[derive(Default, Debug)]
pub struct CFlags {
pub alt: bool,
@@ -270,12 +271,12 @@
return Ok(out);
}
str = &str[offset + 1..];
- let (code, nstr) = parse_code(str)?;
- str = nstr;
+ let code;
+ (code, str) = parse_code(str)?;
bytes = str.as_bytes();
offset = 0;
- out.push(Element::Code(code))
+ out.push(Element::Code(code));
}
}
@@ -313,7 +314,7 @@
.saturating_sub(prefix.len() + digits.len());
if neg {
- out.push('-')
+ out.push('-');
} else if sign {
out.push('+');
} else if blank {
@@ -340,7 +341,7 @@
blank: bool,
sign: bool,
) {
- render_integer(out, iv, padding, precision, blank, sign, 10, "", false)
+ render_integer(out, iv, padding, precision, blank, sign, 10, "", false);
}
pub fn render_octal(
out: &mut String,
@@ -361,8 +362,10 @@
8,
if alt && iv != 0 { "0" } else { "" },
false,
- )
+ );
}
+
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_hexadecimal(
out: &mut String,
iv: i64,
@@ -387,9 +390,10 @@
(false, _) => "",
},
caps,
- )
+ );
}
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_float(
out: &mut String,
n: f64,
@@ -431,6 +435,7 @@
}
}
+#[allow(clippy::fn_params_excessive_bools)]
pub fn render_float_sci(
out: &mut String,
n: f64,
@@ -461,6 +466,7 @@
out.push_str(&exponent_str);
}
+#[allow(clippy::too_many_lines)]
pub fn format_code(
s: State,
out: &mut String,
crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -158,7 +158,7 @@
'\r' => buf.push_str("\\r"),
'\t' => buf.push_str("\\t"),
c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {
- write!(buf, "\\u{:04x}", c as u32).unwrap()
+ write!(buf, "\\u{:04x}", c as u32).unwrap();
}
c => buf.push(c),
}
@@ -194,7 +194,7 @@
pub preserve_order: bool,
}
-/// From https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289
+/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>
/// With added date check
fn yaml_needs_quotes(string: &str) -> bool {
fn need_quotes_spaces(string: &str) -> bool {
@@ -227,6 +227,8 @@
manifest_yaml_ex_buf(s, val, &mut out, &mut String::new(), options)?;
Ok(out)
}
+
+#[allow(clippy::too_many_lines)]
fn manifest_yaml_ex_buf(
s: State,
val: &Val,
@@ -238,9 +240,9 @@
match val {
Val::Bool(v) => {
if *v {
- buf.push_str("true")
+ buf.push_str("true");
} else {
- buf.push_str("false")
+ buf.push_str("false");
}
}
Val::Null => buf.push_str("null"),
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -1,3 +1,6 @@
+// All builtins should return results
+#![allow(clippy::unnecessary_wraps)]
+
use std::collections::HashMap;
use format::{format_arr, format_obj};
@@ -173,7 +176,7 @@
fn builtin_make_array(s: State, sz: usize, func: FuncVal) -> Result<VecVal> {
let mut out = Vec::with_capacity(sz);
for i in 0..sz {
- out.push(func.evaluate_simple(s.clone(), &[i as f64].as_slice())?)
+ out.push(func.evaluate_simple(s.clone(), &[i as f64].as_slice())?);
}
Ok(VecVal(Cc::new(out)))
}
@@ -420,7 +423,7 @@
match func.evaluate_simple(s.clone(), &[Any(el)].as_slice())? {
Val::Arr(o) => {
for oe in o.iter(s.clone()) {
- out.push(oe?)
+ out.push(oe?);
}
}
_ => throw!(RuntimeError(
@@ -707,7 +710,7 @@
#[jrsonnet_macros::builtin]
fn builtin_count(s: State, arr: Vec<Any>, v: Any) -> Result<usize> {
let mut count = 0;
- for item in arr.iter() {
+ for item in &arr {
if equals(s.clone(), &item.0, &v.0)? {
count += 1;
}
crates/jrsonnet-evaluator/src/builtin/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/sort.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/sort.rs
@@ -53,10 +53,10 @@
match (i, sort_type) {
(Val::Str(_), SortKeyType::Unknown) => sort_type = SortKeyType::String,
(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
- (Val::Str(_), SortKeyType::String) => {}
- (Val::Str(_), _) => throw!(SortError::SortElementsShouldHaveEqualType),
- (Val::Num(_), SortKeyType::Number) => {}
- (Val::Num(_), _) => throw!(SortError::SortElementsShouldHaveEqualType),
+ (Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
+ (Val::Str(_) | Val::Num(_), _) => {
+ throw!(SortError::SortElementsShouldHaveEqualType)
+ }
_ => throw!(SortError::SortKeyShouldBeStringOrNumber),
}
}
@@ -91,19 +91,19 @@
Ok(Cc::new(vk.into_iter().map(|v| v.0).collect()))
} else {
// Fast path, identity key getter
- let mut mvalues = (*values).clone();
- let sort_type = get_sort_type(&mut mvalues, |k| k)?;
+ let mut values = (*values).clone();
+ let sort_type = get_sort_type(&mut values, |k| k)?;
match sort_type {
- SortKeyType::Number => mvalues.sort_unstable_by_key(|v| match v {
+ SortKeyType::Number => values.sort_unstable_by_key(|v| match v {
Val::Num(n) => NonNaNf64(*n),
_ => unreachable!(),
}),
- SortKeyType::String => mvalues.sort_unstable_by_key(|v| match v {
+ SortKeyType::String => values.sort_unstable_by_key(|v| match v {
Val::Str(s) => s.clone(),
_ => unreachable!(),
}),
SortKeyType::Unknown => unreachable!(),
};
- Ok(Cc::new(mvalues))
+ Ok(Cc::new(values))
}
}
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -24,5 +24,5 @@
}
pub fn get_parsed_stdlib() -> LocExpr {
- PARSED_STDLIB.with(|t| t.clone())
+ PARSED_STDLIB.with(Clone::clone)
}
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -79,6 +79,7 @@
pub fn contains_binding(&self, name: IStr) -> bool {
self.0.bindings.contains_key(&name)
}
+ #[must_use]
pub fn into_future(self, ctx: FutureWrapper<Self>) -> Self {
{
ctx.0.borrow_mut().replace(self);
@@ -86,16 +87,19 @@
ctx.unwrap()
}
+ #[must_use]
pub fn with_var(self, name: IStr, value: Val) -> Self {
let mut new_bindings = GcHashMap::with_capacity(1);
new_bindings.insert(name, LazyVal::new_resolved(value));
self.extend(new_bindings, None, None, None)
}
+ #[must_use]
pub fn with_this_super(self, new_this: ObjValue, new_super_obj: Option<ObjValue>) -> Self {
self.extend(GcHashMap::new(), None, Some(new_this), new_super_obj)
}
+ #[must_use]
pub fn extend(
self,
new_bindings: GcHashMap<IStr, LazyVal>,
@@ -119,6 +123,7 @@
bindings,
}))
}
+ #[must_use]
pub fn extend_bound(self, new_bindings: GcHashMap<IStr, LazyVal>) -> Self {
let new_this = self.0.this.clone();
let new_super_obj = self.0.super_obj.clone();
@@ -135,7 +140,7 @@
let this = new_this.or_else(|| self.0.this.clone());
let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());
let mut new = GcHashMap::with_capacity(new_bindings.len());
- for (k, v) in new_bindings.0.into_iter() {
+ for (k, v) in new_bindings.0 {
new.insert(k, v.evaluate(s.clone(), this.clone(), super_obj.clone())?);
}
Ok(self.extend(new, new_dollar, this, super_obj))
crates/jrsonnet-evaluator/src/dynamic.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/dynamic.rs
+++ b/crates/jrsonnet-evaluator/src/dynamic.rs
@@ -8,12 +8,16 @@
pub fn new() -> Self {
Self(Cc::new(RefCell::new(None)))
}
+ /// # Panics
+ /// If wrapper is filled already
pub fn fill(self, value: T) {
assert!(self.0.borrow().is_none(), "wrapper is filled already");
self.0.borrow_mut().replace(value);
}
}
impl<T: Clone + Trace + 'static> FutureWrapper<T> {
+ /// # Panics
+ /// If wrapper is not yet filled
pub fn unwrap(&self) -> T {
self.0.borrow().as_ref().cloned().unwrap()
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -96,7 +96,8 @@
#[error(
"syntax error: expected {}, got {:?}",
.error.expected,
- .source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
+ .source_code.chars().nth(error.location.offset)
+ .map_or_else(|| "EOF".into(), |c| c.to_string())
)]
ImportSyntaxError {
#[skip_trace]
@@ -190,7 +191,7 @@
impl Debug for LocError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.0 .0)?;
- for el in self.0 .1 .0.iter() {
+ for el in &self.0 .1 .0 {
writeln!(f, "\t{:?}", el)?;
}
Ok(())
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use gcmodule::{Cc, Trace};2use jrsonnet_interner::IStr;3use jrsonnet_parser::{4 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,5 LiteralType, LocExpr, Member, ObjBody, ParamsDesc,6};7use jrsonnet_types::ValType;89use crate::{10 builtin::{std_slice, BUILTINS},11 error::Error::*,12 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},13 function::CallLocation,14 gc::TraceBox,15 throw,16 typed::Typed,17 val::{ArrValue, FuncDesc, FuncVal, LazyValValue},18 Bindable, Context, ContextCreator, FutureWrapper, GcHashMap, LazyBinding, LazyVal, ObjValue,19 ObjValueBuilder, ObjectAssertion, Result, State, Val,20};21pub mod operator;2223pub fn evaluate_binding_in_future(b: &BindSpec, fctx: FutureWrapper<Context>) -> LazyVal {24 let b = b.clone();25 if let Some(params) = &b.params {26 #[derive(Trace)]27 struct LazyMethodBinding {28 fctx: FutureWrapper<Context>,29 name: IStr,30 params: ParamsDesc,31 value: LocExpr,32 }33 impl LazyValValue for LazyMethodBinding {34 fn get(self: Box<Self>, _: State) -> Result<Val> {35 Ok(evaluate_method(36 self.fctx.unwrap(),37 self.name,38 self.params,39 self.value,40 ))41 }42 }4344 let params = params.clone();4546 LazyVal::new(TraceBox(Box::new(LazyMethodBinding {47 fctx,48 name: b.name.clone(),49 params,50 value: b.value.clone(),51 })))52 } else {53 #[derive(Trace)]54 struct LazyNamedBinding {55 fctx: FutureWrapper<Context>,56 name: IStr,57 value: LocExpr,58 }59 impl LazyValValue for LazyNamedBinding {60 fn get(self: Box<Self>, s: State) -> Result<Val> {61 evaluate_named(s, self.fctx.unwrap(), &self.value, self.name)62 }63 }64 LazyVal::new(TraceBox(Box::new(LazyNamedBinding {65 fctx,66 name: b.name.clone(),67 value: b.value,68 })))69 }70}7172#[allow(clippy::too_many_lines)]73pub fn evaluate_binding(b: &BindSpec, cctx: ContextCreator) -> (IStr, LazyBinding) {74 let b = b.clone();75 if let Some(params) = &b.params {76 #[derive(Trace)]77 struct BindableMethodLazyVal {78 this: Option<ObjValue>,79 super_obj: Option<ObjValue>,8081 cctx: ContextCreator,82 name: IStr,83 params: ParamsDesc,84 value: LocExpr,85 }86 impl LazyValValue for BindableMethodLazyVal {87 fn get(self: Box<Self>, s: State) -> Result<Val> {88 Ok(evaluate_method(89 self.cctx.create(s, self.this, self.super_obj)?,90 self.name,91 self.params,92 self.value,93 ))94 }95 }9697 #[derive(Trace)]98 struct BindableMethod {99 cctx: ContextCreator,100 name: IStr,101 params: ParamsDesc,102 value: LocExpr,103 }104 impl Bindable for BindableMethod {105 fn bind(106 &self,107 _: State,108 this: Option<ObjValue>,109 super_obj: Option<ObjValue>,110 ) -> Result<LazyVal> {111 Ok(LazyVal::new(TraceBox(Box::new(BindableMethodLazyVal {112 this,113 super_obj,114115 cctx: self.cctx.clone(),116 name: self.name.clone(),117 params: self.params.clone(),118 value: self.value.clone(),119 }))))120 }121 }122123 let params = params.clone();124125 (126 b.name.clone(),127 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableMethod {128 cctx,129 name: b.name.clone(),130 params,131 value: b.value.clone(),132 })))),133 )134 } else {135 #[derive(Trace)]136 struct BindableNamedLazyVal {137 this: Option<ObjValue>,138 super_obj: Option<ObjValue>,139140 cctx: ContextCreator,141 name: IStr,142 value: LocExpr,143 }144 impl LazyValValue for BindableNamedLazyVal {145 fn get(self: Box<Self>, s: State) -> Result<Val> {146 evaluate_named(147 s.clone(),148 self.cctx.create(s, self.this, self.super_obj)?,149 &self.value,150 self.name,151 )152 }153 }154155 #[derive(Trace)]156 struct BindableNamed {157 cctx: ContextCreator,158 name: IStr,159 value: LocExpr,160 }161 impl Bindable for BindableNamed {162 fn bind(163 &self,164 _: State,165 this: Option<ObjValue>,166 super_obj: Option<ObjValue>,167 ) -> Result<LazyVal> {168 Ok(LazyVal::new(TraceBox(Box::new(BindableNamedLazyVal {169 this,170 super_obj,171172 cctx: self.cctx.clone(),173 name: self.name.clone(),174 value: self.value.clone(),175 }))))176 }177 }178179 (180 b.name.clone(),181 LazyBinding::Bindable(Cc::new(TraceBox(Box::new(BindableNamed {182 cctx,183 name: b.name.clone(),184 value: b.value.clone(),185 })))),186 )187 }188}189190pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {191 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {192 name,193 ctx,194 params,195 body,196 })))197}198199pub fn evaluate_field_name(200 s: State,201 ctx: Context,202 field_name: &jrsonnet_parser::FieldName,203) -> Result<Option<IStr>> {204 Ok(match field_name {205 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),206 jrsonnet_parser::FieldName::Dyn(expr) => s.push(207 CallLocation::new(&expr.1),208 || "evaluating field name".to_string(),209 || {210 let value = evaluate(s.clone(), ctx, expr)?;211 if matches!(value, Val::Null) {212 Ok(None)213 } else {214 Ok(Some(IStr::from_untyped(value, s.clone())?))215 }216 },217 )?,218 })219}220221pub fn evaluate_comp(222 s: State,223 ctx: Context,224 specs: &[CompSpec],225 callback: &mut impl FnMut(Context) -> Result<()>,226) -> Result<()> {227 match specs.get(0) {228 None => callback(ctx)?,229 Some(CompSpec::IfSpec(IfSpecData(cond))) => {230 if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {231 evaluate_comp(s, ctx, &specs[1..], callback)?;232 }233 }234 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {235 match evaluate(s.clone(), ctx.clone(), expr)? {236 Val::Arr(list) => {237 for item in list.iter(s.clone()) {238 evaluate_comp(239 s.clone(),240 ctx.clone().with_var(var.clone(), item?.clone()),241 &specs[1..],242 callback,243 )?;244 }245 }246 _ => throw!(InComprehensionCanOnlyIterateOverArray),247 }248 }249 }250 Ok(())251}252253#[allow(clippy::too_many_lines)]254pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {255 let new_bindings = FutureWrapper::new();256 let future_this = FutureWrapper::new();257 let cctx = ContextCreator(ctx.clone(), new_bindings.clone());258 {259 let mut bindings: GcHashMap<IStr, LazyBinding> = GcHashMap::with_capacity(members.len());260 for (n, b) in members261 .iter()262 .filter_map(|m| match m {263 Member::BindStmt(b) => Some(b.clone()),264 _ => None,265 })266 .map(|b| evaluate_binding(&b, cctx.clone()))267 {268 bindings.insert(n, b);269 }270 new_bindings.fill(bindings);271 }272273 let mut builder = ObjValueBuilder::new();274 for member in members.iter() {275 match member {276 Member::Field(FieldMember {277 name,278 plus,279 params: None,280 visibility,281 value,282 }) => {283 #[derive(Trace)]284 struct ObjMemberBinding {285 cctx: ContextCreator,286 value: LocExpr,287 name: IStr,288 }289 impl Bindable for ObjMemberBinding {290 fn bind(291 &self,292 s: State,293 this: Option<ObjValue>,294 super_obj: Option<ObjValue>,295 ) -> Result<LazyVal> {296 Ok(LazyVal::new_resolved(evaluate_named(297 s.clone(),298 self.cctx.create(s, this, super_obj)?,299 &self.value,300 self.name.clone(),301 )?))302 }303 }304305 let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;306 let name = if let Some(name) = name {307 name308 } else {309 continue;310 };311312 builder313 .member(name.clone())314 .with_add(*plus)315 .with_visibility(*visibility)316 .with_location(value.1.clone())317 .bindable(318 s.clone(),319 TraceBox(Box::new(ObjMemberBinding {320 cctx: cctx.clone(),321 value: value.clone(),322 name,323 })),324 )?;325 }326 Member::Field(FieldMember {327 name,328 params: Some(params),329 value,330 ..331 }) => {332 #[derive(Trace)]333 struct ObjMemberBinding {334 cctx: ContextCreator,335 value: LocExpr,336 params: ParamsDesc,337 name: IStr,338 }339 impl Bindable for ObjMemberBinding {340 fn bind(341 &self,342 s: State,343 this: Option<ObjValue>,344 super_obj: Option<ObjValue>,345 ) -> Result<LazyVal> {346 Ok(LazyVal::new_resolved(evaluate_method(347 self.cctx.create(s, this, super_obj)?,348 self.name.clone(),349 self.params.clone(),350 self.value.clone(),351 )))352 }353 }354355 let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {356 name357 } else {358 continue;359 };360361 builder362 .member(name.clone())363 .hide()364 .with_location(value.1.clone())365 .bindable(366 s.clone(),367 TraceBox(Box::new(ObjMemberBinding {368 cctx: cctx.clone(),369 value: value.clone(),370 params: params.clone(),371 name,372 })),373 )?;374 }375 Member::BindStmt(_) => {}376 Member::AssertStmt(stmt) => {377 #[derive(Trace)]378 struct ObjectAssert {379 cctx: ContextCreator,380 assert: AssertStmt,381 }382 impl ObjectAssertion for ObjectAssert {383 fn run(384 &self,385 s: State,386 this: Option<ObjValue>,387 super_obj: Option<ObjValue>,388 ) -> Result<()> {389 let ctx = self.cctx.create(s.clone(), this, super_obj)?;390 evaluate_assert(s, ctx, &self.assert)391 }392 }393 builder.assert(TraceBox(Box::new(ObjectAssert {394 cctx: cctx.clone(),395 assert: stmt.clone(),396 })));397 }398 }399 }400 let this = builder.build();401 future_this.fill(this.clone());402 Ok(this)403}404405pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {406 Ok(match object {407 ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,408 ObjBody::ObjComp(obj) => {409 let future_this = FutureWrapper::new();410 let mut builder = ObjValueBuilder::new();411 evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {412 let new_bindings = FutureWrapper::new();413 let cctx = ContextCreator(ctx.clone(), new_bindings.clone());414 let mut bindings: GcHashMap<IStr, LazyBinding> =415 GcHashMap::with_capacity(obj.pre_locals.len() + obj.post_locals.len());416 for (n, b) in obj417 .pre_locals418 .iter()419 .chain(obj.post_locals.iter())420 .map(|b| evaluate_binding(b, cctx.clone()))421 {422 bindings.insert(n, b);423 }424 new_bindings.fill(bindings.clone());425 let ctx = ctx.extend_unbound(s.clone(), bindings, None, None, None)?;426 let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;427428 match key {429 Val::Null => {}430 Val::Str(n) => {431 #[derive(Trace)]432 struct ObjCompBinding {433 ctx: Context,434 value: LocExpr,435 }436 impl Bindable for ObjCompBinding {437 fn bind(438 &self,439 s: State,440 this: Option<ObjValue>,441 _super_obj: Option<ObjValue>,442 ) -> Result<LazyVal> {443 Ok(LazyVal::new_resolved(evaluate(444 s,445 self.ctx.clone().extend(GcHashMap::new(), None, this, None),446 &self.value,447 )?))448 }449 }450 builder451 .member(n)452 .with_location(obj.value.1.clone())453 .with_add(obj.plus)454 .bindable(455 s.clone(),456 TraceBox(Box::new(ObjCompBinding {457 ctx,458 value: obj.value.clone(),459 })),460 )?;461 }462 v => throw!(FieldMustBeStringGot(v.value_type())),463 }464465 Ok(())466 })?;467468 let this = builder.build();469 future_this.fill(this.clone());470 this471 }472 })473}474475pub fn evaluate_apply(476 s: State,477 ctx: Context,478 value: &LocExpr,479 args: &ArgsDesc,480 loc: CallLocation,481 tailstrict: bool,482) -> Result<Val> {483 let value = evaluate(s.clone(), ctx.clone(), value)?;484 Ok(match value {485 Val::Func(f) => {486 let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);487 if tailstrict {488 body()?489 } else {490 s.push(loc, || format!("function <{}> call", f.name()), body)?491 }492 }493 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),494 })495}496497pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {498 let value = &assertion.0;499 let msg = &assertion.1;500 let assertion_result = s.push(501 CallLocation::new(&value.1),502 || "assertion condition".to_owned(),503 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),504 )?;505 if !assertion_result {506 s.push(507 CallLocation::new(&value.1),508 || "assertion failure".to_owned(),509 || {510 if let Some(msg) = msg {511 throw!(AssertionFailed(512 evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?513 ));514 }515 throw!(AssertionFailed(Val::Null.to_string(s.clone())?));516 },517 )?;518 }519 Ok(())520}521522pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {523 use Expr::*;524 let LocExpr(raw_expr, _loc) = expr;525 Ok(match &**raw_expr {526 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),527 _ => evaluate(s, ctx, expr)?,528 })529}530531#[allow(clippy::too_many_lines)]532pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {533 use Expr::*;534 let LocExpr(expr, loc) = expr;535 // let bp = with_state(|s| s.0.stop_at.borrow().clone());536 Ok(match &**expr {537 Literal(LiteralType::This) => {538 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)539 }540 Literal(LiteralType::Super) => Val::Obj(541 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(542 ctx.this()543 .clone()544 .expect("if super exists - then this should to"),545 ),546 ),547 Literal(LiteralType::Dollar) => {548 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)549 }550 Literal(LiteralType::True) => Val::Bool(true),551 Literal(LiteralType::False) => Val::Bool(false),552 Literal(LiteralType::Null) => Val::Null,553 Parened(e) => evaluate(s, ctx, e)?,554 Str(v) => Val::Str(v.clone()),555 Num(v) => Val::new_checked_num(*v)?,556 BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,557 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,558 Var(name) => s.push(559 CallLocation::new(loc),560 || format!("variable <{}> access", name),561 || ctx.binding(name.clone())?.evaluate(s.clone()),562 )?,563 Index(value, index) => {564 match (565 evaluate(s.clone(), ctx.clone(), value)?,566 evaluate(s.clone(), ctx, index)?,567 ) {568 (Val::Obj(v), Val::Str(key)) => s.push(569 CallLocation::new(loc),570 || format!("field <{}> access", key),571 || {572 if let Some(v) = v.get(s.clone(), key.clone())? {573 Ok(v)574 } else {575 throw!(NoSuchField(key.clone()))576 }577 },578 )?,579 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(580 ValType::Obj,581 ValType::Str,582 n.value_type(),583 )),584585 (Val::Arr(v), Val::Num(n)) => {586 if n.fract() > f64::EPSILON {587 throw!(FractionalIndex)588 }589 v.get(s, n as usize)?590 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?591 }592 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),593 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(594 ValType::Arr,595 ValType::Num,596 n.value_type(),597 )),598599 (Val::Str(s), Val::Num(n)) => Val::Str({600 let v: IStr = s601 .chars()602 .skip(n as usize)603 .take(1)604 .collect::<String>()605 .into();606 if v.is_empty() {607 let size = s.chars().count();608 throw!(StringBoundsError(n as usize, size))609 }610 v611 }),612 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(613 ValType::Str,614 ValType::Num,615 n.value_type(),616 )),617618 (v, _) => throw!(CantIndexInto(v.value_type())),619 }620 }621 LocalExpr(bindings, returned) => {622 let mut new_bindings: GcHashMap<IStr, LazyVal> =623 GcHashMap::with_capacity(bindings.len());624 let fctx = Context::new_future();625 for b in bindings {626 new_bindings.insert(b.name.clone(), evaluate_binding_in_future(b, fctx.clone()));627 }628 let ctx = ctx.extend_bound(new_bindings).into_future(fctx);629 evaluate(s, ctx, &returned.clone())?630 }631 Arr(items) => {632 let mut out = Vec::with_capacity(items.len());633 for item in items {634 // TODO: Implement ArrValue::Lazy with same context for every element?635 #[derive(Trace)]636 struct ArrayElement {637 ctx: Context,638 item: LocExpr,639 }640 impl LazyValValue for ArrayElement {641 fn get(self: Box<Self>, s: State) -> Result<Val> {642 evaluate(s, self.ctx, &self.item)643 }644 }645 out.push(LazyVal::new(TraceBox(Box::new(ArrayElement {646 ctx: ctx.clone(),647 item: item.clone(),648 }))));649 }650 Val::Arr(out.into())651 }652 ArrComp(expr, comp_specs) => {653 let mut out = Vec::new();654 evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {655 out.push(evaluate(s.clone(), ctx, expr)?);656 Ok(())657 })?;658 Val::Arr(ArrValue::Eager(Cc::new(out)))659 }660 Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),661 ObjExtend(a, b) => evaluate_add_op(662 s.clone(),663 &evaluate(s.clone(), ctx.clone(), a)?,664 &Val::Obj(evaluate_object(s, ctx, b)?),665 )?,666 Apply(value, args, tailstrict) => {667 evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?668 }669 Function(params, body) => {670 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())671 }672 Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(673 BUILTINS674 .with(|b| b.get(name).copied())675 .ok_or_else(|| IntrinsicNotFound(name.clone()))?,676 )),677 AssertExpr(assert, returned) => {678 evaluate_assert(s.clone(), ctx.clone(), assert)?;679 evaluate(s, ctx, returned)?680 }681 ErrorStmt(e) => s.push(682 CallLocation::new(loc),683 || "error statement".to_owned(),684 || {685 throw!(RuntimeError(686 evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,687 ))688 },689 )?,690 IfElse {691 cond,692 cond_then,693 cond_else,694 } => {695 if s.push(696 CallLocation::new(loc),697 || "if condition".to_owned(),698 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),699 )? {700 evaluate(s, ctx, cond_then)?701 } else {702 match cond_else {703 Some(v) => evaluate(s, ctx, v)?,704 None => Val::Null,705 }706 }707 }708 Slice(value, desc) => {709 fn parse_idx<T: Typed>(710 loc: CallLocation,711 s: State,712 ctx: &Context,713 expr: &Option<LocExpr>,714 desc: &'static str,715 ) -> Result<Option<T>> {716 if let Some(value) = expr {717 Ok(Some(s.push(718 loc,719 || format!("slice {}", desc),720 || T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),721 )?))722 } else {723 Ok(None)724 }725 }726727 let indexable = evaluate(s.clone(), ctx.clone(), value)?;728 let loc = CallLocation::new(loc);729730 let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;731 let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;732 let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;733734 std_slice(indexable.into_indexable()?, start, end, step)?735 }736 Import(path) => {737 let tmp = loc.clone().0;738 let mut import_location = tmp.to_path_buf();739 import_location.pop();740 s.push(741 CallLocation::new(loc),742 || format!("import {:?}", path),743 || s.import_file(&import_location, path),744 )?745 }746 ImportStr(path) => {747 let tmp = loc.clone().0;748 let mut import_location = tmp.to_path_buf();749 import_location.pop();750 Val::Str(s.import_file_str(&import_location, path)?)751 }752 ImportBin(path) => {753 let tmp = loc.clone().0;754 let mut import_location = tmp.to_path_buf();755 import_location.pop();756 let bytes = s.import_file_bin(&import_location, path)?;757 Val::Arr(ArrValue::Bytes(bytes))758 }759 })760}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::cmp::Ordering;
+
use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
use crate::{
@@ -11,7 +13,7 @@
Ok(match (op, b) {
(Not, Bool(v)) => Bool(!v),
(Minus, Num(n)) => Num(-*n),
- (BitNot, Num(n)) => Num(!(*n as i32) as f64),
+ (BitNot, Num(n)) => Num(f64::from(!(*n as i32))),
(op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
})
}
@@ -22,8 +24,8 @@
(Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),
// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
- (Num(n), Str(o)) => Str(format!("{}{}", n, o).into()),
- (Str(o), Num(n)) => Str(format!("{}{}", o, n).into()),
+ (Num(a), Str(b)) => Str(format!("{a}{b}").into()),
+ (Str(a), Num(b)) => Str(format!("{a}{b}").into()),
(Str(a), o) => Str(format!("{}{}", a, o.clone().to_string(s)?).into()),
(o, Str(a)) => Str(format!("{}{}", o.clone().to_string(s)?, a).into()),
@@ -47,7 +49,12 @@
pub fn evaluate_mod_op(s: State, a: &Val, b: &Val) -> Result<Val> {
use Val::*;
match (a, b) {
- (Num(a), Num(b)) => Ok(Num(a % b)),
+ (Num(a), Num(b)) => {
+ if *b == 0.0 {
+ throw!(DivisionByZero)
+ }
+ Ok(Num(a % b))
+ }
(Str(str), vals) => {
String::into_untyped(std_format(s.clone(), str.clone(), vals.clone())?, s)
}
@@ -75,6 +82,32 @@
})
}
+pub fn evaluate_compare_op(s: State, a: &Val, op: BinaryOpType, b: &Val) -> Result<Ordering> {
+ use Val::*;
+ Ok(match (a, b) {
+ (Str(a), Str(b)) => a.cmp(b),
+ (Num(a), Num(b)) => a.partial_cmp(b).expect("jsonnet numbers are non NaN"),
+ (Arr(a), Arr(b)) => {
+ let ai = a.iter(s.clone());
+ let bi = b.iter(s.clone());
+
+ for (a, b) in ai.zip(bi) {
+ let ord = evaluate_compare_op(s.clone(), &a?, op, &b?)?;
+ if !ord.is_eq() {
+ return Ok(ord);
+ }
+ }
+
+ a.len().cmp(&b.len())
+ }
+ (_, _) => throw!(BinaryOperatorDoesNotOperateOnValues(
+ op,
+ a.value_type(),
+ b.value_type()
+ )),
+ })
+}
+
pub fn evaluate_binary_op_normal(s: State, a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
use BinaryOpType::*;
use Val::*;
@@ -84,6 +117,11 @@
(a, Eq, b) => Bool(equals(s, a, b)?),
(a, Neq, b) => Bool(!equals(s, a, b)?),
+ (a, Lt, b) => Bool(evaluate_compare_op(s, a, Lt, b)?.is_lt()),
+ (a, Gt, b) => Bool(evaluate_compare_op(s, a, Gt, b)?.is_gt()),
+ (a, Lte, b) => Bool(evaluate_compare_op(s, a, Lte, b)?.is_le()),
+ (a, Gte, b) => Bool(evaluate_compare_op(s, a, Gte, b)?.is_ge()),
+
(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
(a, Mod, b) => evaluate_mod_op(s, a, b)?,
@@ -92,17 +130,11 @@
// Bool X Bool
(Bool(a), And, Bool(b)) => Bool(*a && *b),
(Bool(a), Or, Bool(b)) => Bool(*a || *b),
-
- // Str X Str
- (Str(v1), Lt, Str(v2)) => Bool(v1 < v2),
- (Str(v1), Gt, Str(v2)) => Bool(v1 > v2),
- (Str(v1), Lte, Str(v2)) => Bool(v1 <= v2),
- (Str(v1), Gte, Str(v2)) => Bool(v1 >= v2),
// Num X Num
(Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
(Num(v1), Div, Num(v2)) => {
- if *v2 <= f64::EPSILON {
+ if *v2 == 0.0 {
throw!(DivisionByZero)
}
Val::new_checked_num(v1 / v2)?
@@ -110,25 +142,20 @@
(Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
- (Num(v1), Lt, Num(v2)) => Bool(v1 < v2),
- (Num(v1), Gt, Num(v2)) => Bool(v1 > v2),
- (Num(v1), Lte, Num(v2)) => Bool(v1 <= v2),
- (Num(v1), Gte, Num(v2)) => Bool(v1 >= v2),
-
- (Num(v1), BitAnd, Num(v2)) => Num(((*v1 as i32) & (*v2 as i32)) as f64),
- (Num(v1), BitOr, Num(v2)) => Num(((*v1 as i32) | (*v2 as i32)) as f64),
- (Num(v1), BitXor, Num(v2)) => Num(((*v1 as i32) ^ (*v2 as i32)) as f64),
+ (Num(v1), BitAnd, Num(v2)) => Num(f64::from((*v1 as i32) & (*v2 as i32))),
+ (Num(v1), BitOr, Num(v2)) => Num(f64::from((*v1 as i32) | (*v2 as i32))),
+ (Num(v1), BitXor, Num(v2)) => Num(f64::from((*v1 as i32) ^ (*v2 as i32))),
(Num(v1), Lhs, Num(v2)) => {
if *v2 < 0.0 {
throw!(RuntimeError("shift by negative exponent".into()))
}
- Num(((*v1 as i32) << (*v2 as i32)) as f64)
+ Num(f64::from((*v1 as i32) << (*v2 as i32)))
}
(Num(v1), Rhs, Num(v2)) => {
if *v2 < 0.0 {
throw!(RuntimeError("shift by negative exponent".into()))
}
- Num(((*v1 as i32) >> (*v2 as i32)) as f64)
+ Num(f64::from((*v1 as i32) >> (*v2 as i32)))
}
_ => throw!(BinaryOperatorDoesNotOperateOnValues(
crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -145,7 +145,7 @@
tailstrict: bool,
handler: &mut dyn FnMut(&IStr, LazyVal) -> Result<()>,
) -> Result<()> {
- for (name, arg) in self.named.iter() {
+ for (name, arg) in &self.named {
handler(
name,
if tailstrict {
@@ -162,8 +162,8 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- for (name, _) in self.named.iter() {
- handler(name)
+ for (name, _) in &self.named {
+ handler(name);
}
}
}
@@ -231,7 +231,7 @@
}
}
-impl<A: ArgLike> ArgsLike for HashMap<IStr, A> {
+impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {
fn unnamed_len(&self) -> usize {
0
}
@@ -325,7 +325,7 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- (*self).named_names(handler)
+ (*self).named_names(handler);
}
}
@@ -381,18 +381,13 @@
if passed_args.contains_key(¶m.0.clone()) {
continue;
}
- LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
- ctx: fctx.clone(),
- name: param.0.clone(),
- value: param.1.clone().unwrap(),
- })));
defaults.insert(
param.0.clone(),
LazyVal::new(TraceBox(Box::new(EvaluateNamedLazyVal {
ctx: fctx.clone(),
name: param.0.clone(),
- value: param.1.clone().unwrap(),
+ value: param.1.clone().expect("default exists"),
}))),
);
filled_args += 1;
@@ -447,7 +442,7 @@
// const INST: &'static Self;
}
-/// You shouldn't probally use this function, use jrsonnet_macros::builtin instead
+/// 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)
@@ -518,10 +513,6 @@
/// Creates Context, which has all argument default values applied
/// and with unbound values causing error to be returned
pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Context {
- let fctx = Context::new_future();
-
- let mut bindings = GcHashMap::new();
-
#[derive(Trace)]
struct DependsOnUnbound(IStr);
impl LazyValValue for DependsOnUnbound {
@@ -530,6 +521,10 @@
}
}
+ let fctx = Context::new_future();
+
+ let mut bindings = GcHashMap::new();
+
for param in params.iter() {
if let Some(v) = ¶m.1 {
bindings.insert(
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -1,6 +1,7 @@
/// Macros to help deal with Gc
use std::{
borrow::{Borrow, BorrowMut},
+ collections::{HashMap, HashSet},
hash::BuildHasherDefault,
ops::{Deref, DerefMut},
};
@@ -14,7 +15,7 @@
impl<T: ?Sized + Trace> Trace for TraceBox<T> {
fn trace(&self, tracer: &mut Tracer) {
- self.0.trace(tracer)
+ self.0.trace(tracer);
}
fn is_type_tracked() -> bool {
@@ -70,7 +71,7 @@
pub struct GcHashSet<V>(pub FxHashSet<V>);
impl<V> GcHashSet<V> {
pub fn new() -> Self {
- Self(Default::default())
+ Self(HashSet::default())
}
pub fn with_capacity(capacity: usize) -> Self {
Self(FxHashSet::with_capacity_and_hasher(
@@ -111,7 +112,7 @@
pub struct GcHashMap<K, V>(pub FxHashMap<K, V>);
impl<K, V> GcHashMap<K, V> {
pub fn new() -> Self {
- Self(Default::default())
+ Self(HashMap::default())
}
pub fn with_capacity(capacity: usize) -> Self {
Self(FxHashMap::with_capacity_and_hasher(
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -79,7 +79,7 @@
if direct.exists() {
Ok(direct.into())
} else {
- for library_path in self.library_paths.iter() {
+ for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if cloned.exists() {
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,7 +1,22 @@
-#![warn(clippy::all, clippy::nursery)]
+#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
#![allow(
macro_expanded_macro_exports_accessed_by_absolute_paths,
- clippy::ptr_arg
+ clippy::ptr_arg,
+ // Too verbose
+ clippy::must_use_candidate,
+ // A lot of functions pass around errors thrown by code
+ clippy::missing_errors_doc,
+ // A lot of pointers have interior Rc
+ clippy::needless_pass_by_value,
+ // Its fine
+ clippy::wildcard_imports,
+ clippy::enum_glob_use,
+ clippy::module_name_repetitions,
+ // TODO: fix individual issues, however this works as intended almost everywhere
+ clippy::cast_precision_loss,
+ clippy::cast_possible_wrap,
+ clippy::cast_possible_truncation,
+ clippy::cast_sign_loss,
)]
// For jrsonnet-macros
@@ -105,10 +120,10 @@
Self {
max_stack: 200,
max_trace: 20,
- globals: Default::default(),
- ext_vars: Default::default(),
- ext_natives: Default::default(),
- tla_vars: Default::default(),
+ globals: HashMap::default(),
+ ext_vars: HashMap::default(),
+ ext_natives: HashMap::default(),
+ tla_vars: HashMap::default(),
import_resolver: Box::new(DummyImportResolver),
manifest_format: ManifestFormat::Json {
padding: 4,
@@ -161,7 +176,7 @@
if self.0.is_empty() {
return result;
}
- for item in self.0.iter() {
+ for item in &self.0 {
if item.loc.belongs_to(loc) {
let mut collected = item.collected.borrow_mut();
let (depth, vals) = collected.entry(stack_generation).or_default();
@@ -198,7 +213,7 @@
)
.map_err(|error| ImportSyntaxError {
error: Box::new(error),
- path: path.to_owned(),
+ path: path.clone(),
source_code: source_code.clone(),
})?;
self.add_parsed_file(path, source_code, parsed.clone())?;
@@ -210,7 +225,7 @@
self.data_mut()
.files
.get_mut(name)
- .unwrap()
+ .expect("file not found")
.evaluated
.take();
}
@@ -246,7 +261,11 @@
line: usize,
column: usize,
) -> Option<usize> {
- location_to_offset(&self.get_source(file).unwrap(), line, column)
+ location_to_offset(
+ &self.get_source(file).expect("file not found"),
+ line,
+ column,
+ )
}
pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
let file_path = self.resolve_file(from, path)?;
@@ -312,8 +331,10 @@
STDLIB_STR.to_owned().into(),
builtin::get_parsed_stdlib(),
)
- .unwrap();
- let val = self.evaluate_loaded_file_raw(&std_path).unwrap();
+ .expect("stdlib is correct");
+ let val = self
+ .evaluate_loaded_file_raw(&std_path)
+ .expect("stdlib is correct");
self.settings_mut().globals.insert("std".into(), val);
self
}
@@ -342,9 +363,8 @@
// Error creation uses data, so i drop guard here
drop(data);
throw!(StackOverflow);
- } else {
- *stack_depth += 1;
}
+ *stack_depth += 1;
}
let result = f();
{
@@ -376,9 +396,8 @@
// Error creation uses data, so i drop guard here
drop(data);
throw!(StackOverflow);
- } else {
- *stack_depth += 1;
}
+ *stack_depth += 1;
}
let mut result = f();
{
@@ -411,9 +430,8 @@
// Error creation uses data, so i drop guard here
drop(data);
throw!(StackOverflow);
- } else {
- *stack_depth += 1;
}
+ *stack_depth += 1;
}
let result = f();
{
@@ -431,6 +449,8 @@
result
}
+ /// # Panics
+ /// In case of formatting failure
pub fn stringify_err(&self, e: &LocError) -> String {
let mut out = String::new();
self.settings()
@@ -1232,49 +1252,5 @@
assert_eval!(r#"std.assertEqual(std.count([], ""), 0)"#);
assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "d"), 0)"#);
assert_eval!(r#"std.assertEqual(std.count(["a", "b", "a"], "a"), 2)"#);
- }
-
- mod derive_typed {
- use std::path::PathBuf;
-
- use crate::{typed::Typed, State};
-
- #[derive(PartialEq, Debug, Typed)]
- struct MyTyped {
- a: u32,
- #[typed(rename = "b")]
- c: String,
- }
-
- #[test]
- fn test() {
- let es = State::default();
- let val = eval!("{a: 14, b: 'Hello, world!'}");
- let typed = MyTyped::try_from(val).unwrap();
-
- assert_eq!(
- typed,
- MyTyped {
- a: 14,
- c: "Hello, world!".to_string()
- }
- );
- es.settings_mut()
- .globals
- .insert("mytyped".into(), typed.try_into().unwrap());
-
- let v = es
- .evaluate_snippet_raw(
- PathBuf::from("raw.jsonnet").into(),
- "
- mytyped == {a: 14, b: 'Hello, world!'}
- "
- .into(),
- )
- .unwrap()
- .as_bool()
- .unwrap();
- assert!(v)
- }
}
}
crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/map.rs
+++ b/crates/jrsonnet-evaluator/src/map.rs
@@ -34,8 +34,7 @@
.0
.parent
.as_ref()
- .map(|p| p.contains_key(key))
- .unwrap_or(false)
+ .map_or(false, |p| p.contains_key(key))
}
}
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -37,7 +37,7 @@
fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
let mut out_args = Vec::with_capacity(self.params.len());
- for p in self.params.iter() {
+ for p in &self.params {
out_args.push(args[&p.name].evaluate(s.clone())?);
}
self.handler.call(s, loc.0.map(|l| l.0.clone()), &out_args)
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -2,6 +2,7 @@
cell::RefCell,
fmt::Debug,
hash::{Hash, Hasher},
+ ptr::addr_of,
};
use gcmodule::{Cc, Trace, Weak};
@@ -20,6 +21,11 @@
#[cfg(not(feature = "exp-preserve-order"))]
mod ordering {
+ #![allow(
+ // This module works as stub for preserve-order feature
+ clippy::unused_self,
+ )]
+
use gcmodule::Trace;
#[derive(Clone, Copy, Default, Debug, Trace)]
@@ -89,6 +95,7 @@
use ordering::*;
+#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Trace)]
pub struct ObjMember {
pub add: bool,
@@ -113,6 +120,7 @@
Errored(LocError),
}
+#[allow(clippy::module_name_repetitions)]
#[derive(Trace)]
#[force_tracking]
pub struct ObjValueInternals {
@@ -136,10 +144,11 @@
impl Eq for WeakObjValue {}
impl Hash for WeakObjValue {
fn hash<H: Hasher>(&self, hasher: &mut H) {
- hasher.write_usize(weak_raw(self.0.clone()) as usize)
+ hasher.write_usize(weak_raw(self.0.clone()) as usize);
}
}
+#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Trace)]
pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);
impl Debug for ObjValue {
@@ -178,6 +187,7 @@
pub fn new_empty() -> Self {
Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))
}
+ #[must_use]
pub fn extend_from(&self, super_obj: Self) -> Self {
match &self.0.super_obj {
None => Self::new(
@@ -200,6 +210,8 @@
pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
}
+
+ #[must_use]
pub fn with_this(&self, this_obj: Self) -> Self {
Self(Cc::new(ObjValueInternals {
super_obj: self.0.super_obj.clone(),
@@ -222,11 +234,7 @@
if !self.0.this_entries.is_empty() {
return false;
}
- self.0
- .super_obj
- .as_ref()
- .map(|s| s.is_empty())
- .unwrap_or(true)
+ self.0.super_obj.as_ref().map_or(true, Self::is_empty)
}
/// Run callback for every field found in object
@@ -254,15 +262,15 @@
let new_sort_key = FieldSortKey::new(depth, member.original_index);
match member.visibility {
Visibility::Normal => {
- let entry = out.entry(name.to_owned());
+ let entry = out.entry(name.clone());
let v = entry.or_insert((true, new_sort_key));
v.1 = new_sort_key;
}
Visibility::Hidden => {
- out.insert(name.to_owned(), (false, new_sort_key));
+ out.insert(name.clone(), (false, new_sort_key));
}
Visibility::Unhide => {
- out.insert(name.to_owned(), (true, new_sort_key));
+ out.insert(name.clone(), (true, new_sort_key));
}
};
false
@@ -356,8 +364,7 @@
}
pub fn has_field(&self, name: IStr) -> bool {
self.field_visibility(name)
- .map(|v| v.is_visible())
- .unwrap_or(false)
+ .map_or(false, |v| v.is_visible())
}
pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {
@@ -459,10 +466,11 @@
impl Eq for ObjValue {}
impl Hash for ObjValue {
fn hash<H: Hasher>(&self, hasher: &mut H) {
- hasher.write_usize(&*self.0 as *const _ as usize)
+ hasher.write_usize(addr_of!(*self.0) as usize);
}
}
+#[allow(clippy::module_name_repetitions)]
pub struct ObjValueBuilder {
super_obj: Option<ObjValue>,
map: GcHashMap<IStr, ObjMember>,
@@ -510,6 +518,7 @@
}
}
+#[allow(clippy::module_name_repetitions)]
#[must_use = "value not added unless binding() was called"]
pub struct ObjMemberBuilder<Kind> {
kind: Kind,
@@ -583,7 +592,7 @@
CallLocation(location.as_ref()),
|| format!("field <{}> initializtion", name.clone()),
|| throw!(DuplicateFieldName(name.clone())),
- )?
+ )?;
}
Ok(())
}
@@ -592,14 +601,14 @@
pub struct ExtendBuilder<'v>(&'v mut ObjValue);
impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
pub fn value(self, value: Val) {
- self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))
+ self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)));
}
pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {
- self.binding(LazyBinding::Bindable(Cc::new(bindable)))
+ self.binding(LazyBinding::Bindable(Cc::new(bindable)));
}
pub fn binding(self, binding: LazyBinding) {
let (receiver, name, member) = self.build_member(binding);
let new = receiver.0.clone();
- *receiver.0 = new.extend_with_raw_member(name, member)
+ *receiver.0 = new.extend_with_raw_member(name, member);
}
}
crates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/location.rs
+++ b/crates/jrsonnet-evaluator/src/trace/location.rs
@@ -1,3 +1,4 @@
+#[allow(clippy::module_name_repetitions)]
#[derive(Clone, PartialEq, Debug)]
pub struct CodeLocation {
pub offset: usize,
@@ -9,6 +10,7 @@
pub line_end_offset: usize,
}
+#[allow(clippy::module_name_repetitions)]
pub fn location_to_offset(mut file: &str, mut line: usize, column: usize) -> Option<usize> {
let mut offset = 0;
while line > 1 {
@@ -21,13 +23,14 @@
Some(offset)
}
+#[allow(clippy::module_name_repetitions)]
pub fn offset_to_location(file: &str, offsets: &[usize]) -> Vec<CodeLocation> {
if offsets.is_empty() {
return vec![];
}
let mut line = 1;
let mut column = 1;
- let max_offset = *offsets.iter().max().unwrap();
+ let max_offset = *offsets.iter().max().expect("offsets is not empty");
let mut offset_map = offsets
.iter()
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -19,14 +19,18 @@
impl PathResolver {
pub fn resolve(&self, from: &Path) -> String {
match self {
- Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
+ Self::FileName => from
+ .file_name()
+ .expect("file name exists")
+ .to_string_lossy()
+ .into_owned(),
Self::Absolute => from.to_string_lossy().into_owned(),
Self::Relative(base) => {
if from.is_relative() {
return from.to_string_lossy().into_owned();
}
pathdiff::diff_paths(from, base)
- .unwrap()
+ .expect("base is absolute")
.to_string_lossy()
.into_owned()
}
@@ -35,6 +39,7 @@
}
/// Implements pretty-printing of traces
+#[allow(clippy::module_name_repetitions)]
pub trait TraceFormat {
fn write_trace(
&self,
@@ -88,8 +93,9 @@
error,
} = error.error()
{
+ use std::fmt::Write;
+
writeln!(out)?;
- use std::fmt::Write;
let mut n = self.resolver.resolve(path);
let mut offset = error.location.offset;
let is_eof = if offset >= source_code.len() {
@@ -134,7 +140,7 @@
let align = file_names
.iter()
.flatten()
- .map(|e| e.len())
+ .map(String::len)
.max()
.unwrap_or(0);
for (el, file) in error.trace().0.iter().zip(file_names) {
@@ -166,7 +172,7 @@
error: &LocError,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
- for item in error.trace().0.iter() {
+ for item in &error.trace().0 {
writeln!(out)?;
let desc = &item.desc;
if let Some(source) = &item.location {
@@ -227,7 +233,7 @@
)?;
}
let trace = &error.trace();
- for item in trace.0.iter() {
+ for item in &trace.0 {
writeln!(out)?;
let desc = &item.desc;
if let Some(source) = &item.location {
@@ -273,7 +279,7 @@
let snippet = Snippet {
opt: FormatOptions {
color: true,
- ..Default::default()
+ ..FormatOptions::default()
},
title: None,
footer: vec![],
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -38,6 +38,7 @@
<Self as Typed>::TYPE.check(s, &value)?;
match value {
Val::Num(n) => {
+ #[allow(clippy::float_cmp)]
if n.trunc() != n {
throw!(RuntimeError(
format!(
@@ -95,6 +96,7 @@
<Self as Typed>::TYPE.check(s, &value)?;
match value {
Val::Num(n) => {
+ #[allow(clippy::float_cmp)]
if n.trunc() != n {
throw!(RuntimeError(
format!(
@@ -160,7 +162,7 @@
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));
+ &ComplexValType::BoundedNumber(Some(0.0), Some(u32::MAX as f64));
fn into_untyped(value: Self, _: State) -> Result<Val> {
if value > u32::MAX as Self {
@@ -173,6 +175,7 @@
<Self as Typed>::TYPE.check(s, &value)?;
match value {
Val::Num(n) => {
+ #[allow(clippy::float_cmp)]
if n.trunc() != n {
throw!(RuntimeError(
"cannot convert number with fractional part to usize".into()
@@ -263,7 +266,7 @@
}
/// To be used in Vec<Any>
-/// Regular Val can't be used here, because it has wrong TryFrom::Error type
+/// Regular Val can't be used here, because it has wrong `TryFrom::Error` type
#[derive(Clone)]
pub struct Any(pub Val);
@@ -279,7 +282,7 @@
}
}
-/// Specialization, provides faster TryFrom<VecVal> for Val
+/// Specialization, provides faster `TryFrom<VecVal>` for Val
pub struct VecVal(pub Cc<Vec<Val>>);
impl Typed for VecVal {
@@ -310,22 +313,20 @@
}
fn from_untyped(value: Val, s: State) -> Result<Self> {
+ if let Val::Arr(ArrValue::Bytes(bytes)) = value {
+ return Ok(Self(bytes));
+ }
+ <Self as Typed>::TYPE.check(s.clone(), &value)?;
match value {
- Val::Arr(ArrValue::Bytes(bytes)) => Ok(Self(bytes)),
- _ => {
- <Self as Typed>::TYPE.check(s.clone(), &value)?;
- match value {
- Val::Arr(a) => {
- let mut out = Vec::with_capacity(a.len());
- for e in a.iter(s.clone()) {
- let r = e?;
- out.push(u8::from_untyped(r, s.clone())?);
- }
- Ok(Self(out.into()))
- }
- _ => unreachable!(),
+ Val::Arr(a) => {
+ let mut out = Vec::with_capacity(a.len());
+ for e in a.iter(s.clone()) {
+ let r = e?;
+ out.push(u8::from_untyped(r, s.clone())?);
}
+ Ok(Self(out.into()))
}
+ _ => unreachable!(),
}
}
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -71,11 +71,11 @@
if line.trim().is_empty() {
continue;
}
- if i != 0 {
+ if i == 0 {
+ write!(f, " - ")?;
+ } else {
writeln!(f)?;
write!(f, " ")?;
- } else {
- write!(f, " - ")?;
}
write!(f, "{}", line)?;
}
@@ -94,7 +94,7 @@
Ok(_) => Ok(()),
Err(mut e) => {
if let Error::TypeError(e) = &mut e.error_mut() {
- (e.1).0.push(path())
+ (e.1).0.push(path());
}
Err(e)
}
@@ -145,6 +145,7 @@
}
impl CheckType for ComplexValType {
+ #[allow(clippy::too_many_lines)]
fn check(&self, s: State, value: &Val) -> Result<()> {
match self {
Self::Any => Ok(()),
@@ -202,7 +203,7 @@
|| format!("property {}", k),
|| ValuePathItem::Field((*k).into()),
|| v.check(s.clone(), &got_v),
- )?
+ )?;
} else {
return Err(
TypeError::MissingProperty((*k).into(), self.clone()).into()
@@ -245,13 +246,13 @@
}
Self::Sum(types) => {
for ty in types.iter() {
- ty.check(s.clone(), value)?
+ ty.check(s.clone(), value)?;
}
Ok(())
}
Self::SumRef(types) => {
for ty in types.iter() {
- ty.check(s.clone(), value)?
+ ty.check(s.clone(), value)?;
}
Ok(())
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -32,6 +32,7 @@
Pending,
}
+#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Trace)]
pub struct LazyVal(Cc<RefCell<LazyValInternals>>);
impl LazyVal {
@@ -50,7 +51,7 @@
LazyValInternals::Computed(v) => return Ok(v.clone()),
LazyValInternals::Errored(e) => return Err(e.clone()),
LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),
- _ => (),
+ LazyValInternals::Waiting(..) => (),
};
let value = if let LazyValInternals::Waiting(value) =
std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)
@@ -114,6 +115,7 @@
}
}
+#[allow(clippy::module_name_repetitions)]
#[derive(Trace, Clone)]
pub enum FuncVal {
/// Plain function implemented in jsonnet
@@ -225,10 +227,10 @@
let rem = diff % self.step();
let div = diff / self.step();
- if rem != 0 {
+ if rem == 0 {
+ div
+ } else {
div + 1
- } else {
- div
}
}
}
@@ -248,11 +250,17 @@
pub fn new_eager() -> Self {
Self::Eager(Cc::new(Vec::new()))
}
+
+ /// # Panics
+ /// If a > b
pub fn new_range(a: i32, b: i32) -> Self {
assert!(a <= b);
Self::Range(a, b)
}
+ /// # Panics
+ /// If passed numbers are incorrect
+ #[must_use]
pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {
let len = self.len();
let from = from.unwrap_or(0);
@@ -289,7 +297,7 @@
match self {
Self::Bytes(i) => i
.get(index)
- .map_or(Ok(None), |v| Ok(Some(Val::Num(*v as f64)))),
+ .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),
Self::Lazy(vec) => {
if let Some(v) = vec.get(index) {
Ok(Some(v.evaluate(s)?))
@@ -333,7 +341,7 @@
match self {
Self::Bytes(i) => i
.get(index)
- .map(|b| LazyVal::new_resolved(Val::Num(*b as f64))),
+ .map(|b| LazyVal::new_resolved(Val::Num(f64::from(*b)))),
Self::Lazy(vec) => vec.get(index).cloned(),
Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),
Self::Extended(v) => {
@@ -374,7 +382,7 @@
Self::Bytes(i) => {
let mut out = Vec::with_capacity(i.len());
for v in i.iter() {
- out.push(Val::Num(*v as f64));
+ out.push(Val::Num(f64::from(*v)));
}
Cc::new(out)
}
@@ -396,7 +404,7 @@
Self::Range(a, b) => {
let mut out = Vec::with_capacity(self.len());
for i in *a..*b {
- out.push(Val::Num(i as f64));
+ out.push(Val::Num(f64::from(i)));
}
Cc::new(out)
}
@@ -414,7 +422,7 @@
.take(v.to() - v.from())
.step_by(v.step())
{
- out.push(v.evaluate(s.clone())?)
+ out.push(v.evaluate(s.clone())?);
}
Cc::new(out)
}
@@ -423,28 +431,27 @@
pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
- Self::Bytes(b) => Ok(Val::Num(b[idx] as f64)),
+ Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),
Self::Lazy(l) => l[idx].evaluate(s.clone()),
Self::Eager(e) => Ok(e[idx].clone()),
- Self::Extended(_) => self.get(s.clone(), idx).map(|e| e.unwrap()),
- Self::Range(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),
- Self::Reversed(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),
- Self::Slice(..) => self.get(s.clone(), idx).map(|e| e.unwrap()),
+ Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {
+ self.get(s.clone(), idx).map(|e| e.expect("idx < len"))
+ }
})
}
pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {
(0..self.len()).map(move |idx| match self {
- Self::Bytes(b) => LazyVal::new_resolved(Val::Num(b[idx] as f64)),
+ Self::Bytes(b) => LazyVal::new_resolved(Val::Num(f64::from(b[idx]))),
Self::Lazy(l) => l[idx].clone(),
Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),
- Self::Extended(_) => self.get_lazy(idx).unwrap(),
- Self::Range(..) => self.get_lazy(idx).unwrap(),
- Self::Reversed(..) => self.get_lazy(idx).unwrap(),
- Self::Slice(..) => self.get_lazy(idx).unwrap(),
+ Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {
+ self.get_lazy(idx).expect("idx < len")
+ }
})
}
+ #[must_use]
pub fn reversed(self) -> Self {
Self::Reversed(Box::new(self))
}
@@ -493,6 +500,7 @@
}
}
+#[allow(clippy::module_name_repetitions)]
pub enum IndexableVal {
Str(IStr),
Arr(ArrValue),
@@ -708,7 +716,7 @@
preserve_order,
},
)
- .map(|s| s.into())
+ .map(Into::into)
}
/// Calls `std.manifestJson`
@@ -730,7 +738,7 @@
preserve_order,
},
)
- .map(|s| s.into())
+ .map(Into::into)
}
pub fn to_yaml(
@@ -751,7 +759,7 @@
preserve_order,
},
)
- .map(|s| s.into())
+ .map(Into::into)
}
pub fn into_indexable(self) -> Result<IndexableVal> {
Ok(match self {
@@ -824,8 +832,8 @@
for field in fields {
if !equals(
s.clone(),
- &a.get(s.clone(), field.clone())?.unwrap(),
- &b.get(s.clone(), field)?.unwrap(),
+ &a.get(s.clone(), field.clone())?.expect("field exists"),
+ &b.get(s.clone(), field)?.expect("field exists"),
)? {
return Ok(false);
}
crates/jrsonnet-evaluator/tests/common.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/tests/common.rs
+++ b/crates/jrsonnet-evaluator/tests/common.rs
@@ -12,6 +12,15 @@
}
#[macro_export]
+macro_rules! ensure {
+ ($v:expr $(,)?) => {
+ if !$v {
+ ::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+ }
+ };
+}
+
+#[macro_export]
macro_rules! ensure_val_eq {
($s:expr, $a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
crates/jrsonnet-evaluator/tests/sanity.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/tests/sanity.rs
@@ -0,0 +1,46 @@
+use std::path::PathBuf;
+
+use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+
+mod common;
+
+#[test]
+fn assert_positive() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+
+ let v = s.evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 1: 'fail'; null".into())?;
+ ensure_val_eq!(s.clone(), v, Val::Null);
+ let v = s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 1)".into())?;
+ ensure_val_eq!(s.clone(), v, Val::Bool(true));
+
+ Ok(())
+}
+
+#[test]
+fn assert_negative() -> Result<()> {
+ let s = State::default();
+ s.with_stdlib();
+
+ {
+ let e = match s
+ .evaluate_snippet_raw(PathBuf::new().into(), "assert 1 == 2: 'fail'; null".into())
+ {
+ Ok(_) => throw_runtime!("assertion should fail"),
+ Err(e) => e,
+ };
+ let e = s.stringify_err(&e);
+ ensure!(e.starts_with("assert failed: fail\n"));
+ }
+ {
+ let e = match s.evaluate_snippet_raw(PathBuf::new().into(), "std.assertEqual(1, 2)".into())
+ {
+ Ok(_) => throw_runtime!("assertion should fail"),
+ Err(e) => e,
+ };
+ let e = s.stringify_err(&e);
+ ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))
+ }
+
+ Ok(())
+}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -157,8 +157,8 @@
});
}
- match &ty as &Type {
- Type::Reference(r) if type_is_path(&r.elem, &name).is_some() => return Ok(Self::This),
+ match ty as &Type {
+ Type::Reference(r) if type_is_path(&r.elem, name).is_some() => return Ok(Self::This),
_ => {}
}
@@ -465,14 +465,13 @@
"strategy should be set when flattening Option",
));
}
- } else {
- if attr.flatten_ok {
- return Err(Error::new(
- field.span(),
- "flatten(ok) is only useable on optional fields",
- ));
- }
+ } else if attr.flatten_ok {
+ return Err(Error::new(
+ field.span(),
+ "flatten(ok) is only useable on optional fields",
+ ));
}
+
Ok(Self {
attr,
ident,