difftreelog
style increase clippy linting level
in: master
15 files changed
crates/jrsonnet-evaluator/src/builtin/format.rsdiffbeforeafterboth314 for _ in 0..zp2 {314 for _ in 0..zp2 {315 out.push('0');315 out.push('0');316 }316 }317 out.push_str(&prefix);317 out.push_str(prefix);318318319 for digit in digits.into_iter().rev() {319 for digit in digits.into_iter().rev() {320 let ch = NUMBERS[digit as usize] as char;320 let ch = NUMBERS[digit as usize] as char;399 }399 }400 return;400 return;401 }401 }402 let frac = (n.fract() * 10.0_f64.powf(precision as f64) + 0.5).floor();402 let frac = n403 .fract()404 .mul_add(10.0_f64.powf(precision as f64), 0.5)405 .floor();403 if trailing || frac > 0.0 {406 if trailing || frac > 0.0 {404 out.push('.');407 out.push('.');605}608}606609607pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {610pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {608 let codes = parse_codes(&str)?;611 let codes = parse_codes(str)?;609 let mut out = String::new();612 let mut out = String::new();610613611 for code in codes {614 for code in codes {659}662}660663661pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {664pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {662 let codes = parse_codes(&str)?;665 let codes = parse_codes(str)?;663 let mut out = String::new();666 let mut out = String::new();664667665 for code in codes {668 for code in codes {crates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth20 pub mtype: ManifestType,20 pub mtype: ManifestType,21}21}222223pub(crate) fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {23pub fn manifest_json_ex(val: &Val, options: &ManifestJsonOptions<'_>) -> Result<String> {24 let mut out = String::new();24 let mut out = String::new();25 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;25 manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;26 Ok(out)26 Ok(out)crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth16pub mod manifest;16pub mod manifest;17pub mod sort;17pub mod sort;181819#[allow(clippy::cognitive_complexity)]19pub fn call_builtin(20pub fn call_builtin(20 context: Context,21 context: Context,21 loc: &Option<ExprLocation>,22 loc: &Option<ExprLocation>,22 ns: &str,23 ns: &str,23 name: &str,24 name: &str,24 args: &ArgsDesc,25 args: &ArgsDesc,25) -> Result<Val> {26) -> Result<Val> {26 Ok(match (ns, &name as &str) {27 Ok(match (ns, name as &str) {27 // arr/string/function28 // arr/string/function28 ("std", "length") => parse_args!(context, "std.length", args, 1, [29 ("std", "length") => parse_args!(context, "std.length", args, 1, [29 0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];30 0, x: [Val::Str|Val::Arr|Val::Obj], vec![ValType::Str, ValType::Arr, ValType::Obj];crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth22 }22 }232324 jrsonnet_parser::parse(24 jrsonnet_parser::parse(25 &jrsonnet_stdlib::STDLIB_STR,25 jrsonnet_stdlib::STDLIB_STR,26 &ParserSettings {26 &ParserSettings {27 loc_data: true,27 loc_data: true,28 file_name: Rc::new(PathBuf::from("std.jsonnet")),28 file_name: Rc::new(PathBuf::from("std.jsonnet")),crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth48 &self.0.super_obj48 &self.0.super_obj49 }49 }505051 pub fn new() -> Context {51 pub fn new() -> Self {52 Context(Rc::new(ContextInternals {52 Self(Rc::new(ContextInternals {53 dollar: None,53 dollar: None,54 this: None,54 this: None,55 super_obj: None,55 super_obj: None,65 .cloned()65 .cloned()66 .ok_or_else(|| UnknownVariable(name))?)66 .ok_or_else(|| UnknownVariable(name))?)67 }67 }68 pub fn into_future(self, ctx: FutureContext) -> Context {68 pub fn into_future(self, ctx: FutureContext) -> Self {69 {69 {70 ctx.0.borrow_mut().replace(self);70 ctx.0.borrow_mut().replace(self);71 }71 }72 ctx.unwrap()72 ctx.unwrap()73 }73 }747475 pub fn with_var(self, name: Rc<str>, value: Val) -> Context {75 pub fn with_var(self, name: Rc<str>, value: Val) -> Self {76 let mut new_bindings =76 let mut new_bindings =77 FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());77 FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());78 new_bindings.insert(name, resolved_lazy_val!(value));78 new_bindings.insert(name, resolved_lazy_val!(value));85 new_dollar: Option<ObjValue>,85 new_dollar: Option<ObjValue>,86 new_this: Option<ObjValue>,86 new_this: Option<ObjValue>,87 new_super_obj: Option<ObjValue>,87 new_super_obj: Option<ObjValue>,88 ) -> Context {88 ) -> Self {89 match Rc::try_unwrap(self.0) {89 match Rc::try_unwrap(self.0) {90 Ok(mut ctx) => {90 Ok(mut ctx) => {91 // Extended context aren't used by anything else, we can freely mutate it without cloning91 // Extended context aren't used by anything else, we can freely mutate it without cloning101 if !new_bindings.is_empty() {101 if !new_bindings.is_empty() {102 ctx.bindings = ctx.bindings.extend(new_bindings);102 ctx.bindings = ctx.bindings.extend(new_bindings);103 }103 }104 Context(Rc::new(ctx))104 Self(Rc::new(ctx))105 }105 }106 Err(ctx) => {106 Err(ctx) => {107 let dollar = new_dollar.or_else(|| ctx.dollar.clone());107 let dollar = new_dollar.or_else(|| ctx.dollar.clone());112 } else {112 } else {113 ctx.bindings.clone().extend(new_bindings)113 ctx.bindings.clone().extend(new_bindings)114 };114 };115 Context(Rc::new(ContextInternals {115 Self(Rc::new(ContextInternals {116 dollar,116 dollar,117 this,117 this,118 super_obj,118 super_obj,127 new_dollar: Option<ObjValue>,127 new_dollar: Option<ObjValue>,128 new_this: Option<ObjValue>,128 new_this: Option<ObjValue>,129 new_super_obj: Option<ObjValue>,129 new_super_obj: Option<ObjValue>,130 ) -> Result<Context> {130 ) -> Result<Self> {131 let this = new_this.or_else(|| self.0.this.clone());131 let this = new_this.or_else(|| self.0.this.clone());132 let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());132 let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());133 let mut new =133 let mut new =crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth95 Self(Box::new((e, StackTrace(vec![]))))95 Self(Box::new((e, StackTrace(vec![]))))96 }96 }979798 pub fn error(&self) -> &Error {98 pub const fn error(&self) -> &Error {99 &(self.0).099 &(self.0).0100 }100 }101 pub fn trace(&self) -> &StackTrace {101 pub const fn trace(&self) -> &StackTrace {102 &(self.0).1102 &(self.0).1103 }103 }104 pub fn trace_mut(&mut self) -> &mut StackTrace {104 pub fn trace_mut(&mut self) -> &mut StackTrace {crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth82 })82 })83}83}848485pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {85pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {86 Ok(match (a, b) {86 Ok(match (a, b) {87 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),87 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),888889 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)89 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)90 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),90 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),111 b: &LocExpr,111 b: &LocExpr,112) -> Result<Val> {112) -> Result<Val> {113 Ok(113 Ok(114 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {114 match (evaluate(context.clone(), a)?.unwrap_if_lazy()?, op, b) {115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117 (a, op, eb) => {117 (a, op, eb) => {194 Ok(match specs.get(0) {194 Ok(match specs.get(0) {195 None => Some(vec![value(context)?]),195 None => Some(vec![value(context)?]),196 Some(CompSpec::IfSpec(IfSpecData(cond))) => {196 Some(CompSpec::IfSpec(IfSpecData(cond))) => {197 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {197 if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {198 evaluate_comp(context, value, &specs[1..])?198 evaluate_comp(context, value, &specs[1..])?199 } else {199 } else {200 None200 None201 }201 }202 }202 }203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {204 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {204 match evaluate(context.clone(), expr)?.unwrap_if_lazy()? {205 Val::Arr(list) => {205 Val::Arr(list) => {206 let mut out = Vec::new();206 let mut out = Vec::new();207 for item in list.iter() {207 for item in list.iter() {258 visibility,258 visibility,259 value,259 value,260 }) => {260 }) => {261 let name = evaluate_field_name(context.clone(), &name)?;261 let name = evaluate_field_name(context.clone(), name)?;262 if name.is_none() {262 if name.is_none() {263 continue;263 continue;264 }264 }286 value,286 value,287 ..287 ..288 }) => {288 }) => {289 let name = evaluate_field_name(context.clone(), &name)?;289 let name = evaluate_field_name(context.clone(), name)?;290 if name.is_none() {290 if name.is_none() {291 continue;291 continue;292 }292 }320320321pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {321pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,323 ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,324 ObjBody::ObjComp(obj) => {324 ObjBody::ObjComp(obj) => {325 let future_this = FutureObjValue::new();325 let future_this = FutureObjValue::new();326 let mut new_members = HashMap::new();326 let mut new_members = HashMap::new();437 Parened(e) => evaluate(context, e)?,437 Parened(e) => evaluate(context, e)?,438 Str(v) => Val::Str(v.clone()),438 Str(v) => Val::Str(v.clone()),439 Num(v) => Val::new_checked_num(*v)?,439 Num(v) => Val::new_checked_num(*v)?,440 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, &v1, *o, &v2)?,440 BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,442 Var(name) => push(442 Var(name) => push(443 loc,443 loc,461 (Val::Obj(v), Val::Str(s)) => {461 (Val::Obj(v), Val::Str(s)) => {462 let sn = s.clone();462 let sn = s.clone();463 push(463 push(464 &loc,464 loc,465 || format!("field <{}> access", sn),465 || format!("field <{}> access", sn),466 || {466 || {467 if let Some(v) = v.get(s.clone())? {467 if let Some(v) = v.get(s.clone())? {563 &value.1,563 &value.1,564 || "assertion condition".to_owned(),564 || "assertion condition".to_owned(),565 || {565 || {566 evaluate(context.clone(), &value)?566 evaluate(context.clone(), value)?567 .try_cast_bool("assertion condition should be of type `boolean`")567 .try_cast_bool("assertion condition should be of type `boolean`")568 },568 },569 )?;569 )?;576 }576 }577 }577 }578 ErrorStmt(e) => push(578 ErrorStmt(e) => push(579 &loc,579 loc,580 || "error statement".to_owned(),580 || "error statement".to_owned(),581 || {581 || {582 throw!(RuntimeError(582 throw!(RuntimeError(610 push(610 push(611 loc,611 loc,612 || format!("import {:?}", path),612 || format!("import {:?}", path),613 || with_state(|s| s.import_file(&import_location, path)),613 || with_state(|s| s.import_file(import_location, path)),614 )?614 )?615 }615 }616 ImportStr(path) => {616 ImportStr(path) => {620 .0;620 .0;621 let import_location = Rc::make_mut(&mut tmp);621 let import_location = Rc::make_mut(&mut tmp);622 import_location.pop();622 import_location.pop();623 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)623 Val::Str(with_state(|s| s.import_file_str(import_location, path))?)624 }624 }625 Literal(LiteralType::Super) => throw!(StandaloneSuper),625 Literal(LiteralType::Super) => throw!(StandaloneSuper),626 })626 })crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth75 let idx = params75 let idx = params76 .iter()76 .iter()77 .position(|p| *p.0 == **name)77 .position(|p| *p.0 == **name)78 .ok_or_else(|| UnknownFunctionParameter((&name as &str).to_owned()))?;78 .ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;797980 if idx >= params.len() {80 if idx >= params.len() {81 throw!(TooManyArgsFunctionHas(params.len()));81 throw!(TooManyArgsFunctionHas(params.len()));111 Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))111 Ok(body_ctx.unwrap_or(ctx).extend(out, None, None, None))112}112}113113114pub(crate) fn place_args(114pub fn place_args(115 ctx: Context,115 ctx: Context,116 body_ctx: Option<Context>,116 body_ctx: Option<Context>,117 params: &ParamsDesc,117 params: &ParamsDesc,crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth41 panic!("`as_any($self)` is not supported by dummy resolver")41 panic!("`as_any($self)` is not supported by dummy resolver")42 }42 }43}43}44#[allow(clippy::use_self)]44impl Default for Box<dyn ImportResolver> {45impl Default for Box<dyn ImportResolver> {45 fn default() -> Self {46 fn default() -> Self {46 Box::new(DummyImportResolver)47 Box::new(DummyImportResolver)crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth14 type Error = LocError;14 type Error = LocError;15 fn try_from(v: &Val) -> Result<Self> {15 fn try_from(v: &Val) -> Result<Self> {16 Ok(match v {16 Ok(match v {17 Val::Bool(b) => Value::Bool(*b),17 Val::Bool(b) => Self::Bool(*b),18 Val::Null => Value::Null,18 Val::Null => Self::Null,19 Val::Str(s) => Value::String((&s as &str).into()),19 Val::Str(s) => Self::String((s as &str).into()),20 Val::Num(n) => Value::Number(if n.fract() <= f64::EPSILON {20 Val::Num(n) => Self::Number(if n.fract() <= f64::EPSILON {21 (*n as i64).into()21 (*n as i64).into()22 } else {22 } else {23 Number::from_f64(*n).expect("to json number")23 Number::from_f64(*n).expect("to json number")28 for item in a.iter() {28 for item in a.iter() {29 out.push(item.try_into()?);29 out.push(item.try_into()?);30 }30 }31 Value::Array(out)31 Self::Array(out)32 }32 }33 Val::Obj(o) => {33 Val::Obj(o) => {34 let mut out = Map::new();34 let mut out = Map::new();38 (&o.get(key)?.expect("field exists")).try_into()?,38 (&o.get(key)?.expect("field exists")).try_into()?,39 );39 );40 }40 }41 Value::Object(out)41 Self::Object(out)42 }42 }43 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),43 Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),44 })44 })48impl From<&Value> for Val {48impl From<&Value> for Val {49 fn from(v: &Value) -> Self {49 fn from(v: &Value) -> Self {50 match v {50 match v {51 Value::Null => Val::Null,51 Value::Null => Self::Null,52 Value::Bool(v) => Val::Bool(*v),52 Value::Bool(v) => Self::Bool(*v),53 Value::Number(n) => Val::Num(n.as_f64().expect("as f64")),53 Value::Number(n) => Self::Num(n.as_f64().expect("as f64")),54 Value::String(s) => Val::Str((s as &str).into()),54 Value::String(s) => Self::Str((s as &str).into()),55 Value::Array(a) => {55 Value::Array(a) => {56 let mut out = Vec::with_capacity(a.len());56 let mut out = Vec::with_capacity(a.len());57 for v in a {57 for v in a {58 out.push(v.into());58 out.push(v.into());59 }59 }60 Val::Arr(Rc::new(out))60 Self::Arr(Rc::new(out))61 }61 }62 Value::Object(o) => {62 Value::Object(o) => {63 let mut entries = HashMap::with_capacity(o.len());63 let mut entries = HashMap::with_capacity(o.len());72 },72 },73 );73 );74 }74 }75 Val::Obj(ObjValue::new(None, Rc::new(entries)))75 Self::Obj(ObjValue::new(None, Rc::new(entries)))76 }76 }77 }77 }78 }78 }crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth1#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]1#![cfg_attr(feature = "unstable", feature(stmt_expr_attributes))]2#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]2#![allow(macro_expanded_macro_exports_accessed_by_absolute_paths)]3#![warn(clippy::all, clippy::nursery)]344mod builtin;5mod builtin;5mod ctx;6mod ctx;49impl LazyBinding {50impl LazyBinding {50 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {51 pub fn evaluate(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {51 match self {52 match self {52 LazyBinding::Bindable(v) => v(this, super_obj),53 Self::Bindable(v) => v(this, super_obj),53 LazyBinding::Bound(v) => Ok(v.clone()),54 Self::Bound(v) => Ok(v.clone()),54 }55 }55 }56 }56}57}77}78}78impl Default for EvaluationSettings {79impl Default for EvaluationSettings {79 fn default() -> Self {80 fn default() -> Self {80 EvaluationSettings {81 Self {81 max_stack: 200,82 max_stack: 200,82 max_trace: 20,83 max_trace: 20,83 globals: Default::default(),84 globals: Default::default(),130 f: impl FnOnce() -> Result<T>,131 f: impl FnOnce() -> Result<T>,131) -> Result<T> {132) -> Result<T> {132 if let Some(v) = e {133 if let Some(v) = e {133 with_state(|s| s.push(&v, frame_desc, f))134 with_state(|s| s.push(v, frame_desc, f))134 } else {135 } else {135 f()136 f()136 }137 }359/// Raw methods evaluate passed values but don't perform TLA execution360/// Raw methods evaluate passed values but don't perform TLA execution360impl EvaluationState {361impl EvaluationState {361 pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {362 pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {362 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))363 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))363 }364 }364 pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {365 pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {365 self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))366 self.run_in_state(|| self.import_file(&PathBuf::from("."), name))366 }367 }367 /// Parses and evaluates the given snippet368 /// Parses and evaluates the given snippet368 pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {369 pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {crates/jrsonnet-evaluator/src/map.rsdiffbeforeafterboth15 match Rc::try_unwrap(self.0) {15 match Rc::try_unwrap(self.0) {16 Ok(mut map) => {16 Ok(mut map) => {17 map.current.extend(new_layer);17 map.current.extend(new_layer);18 LayeredHashMap(Rc::new(map))18 Self(Rc::new(map))19 }19 }20 Err(this) => LayeredHashMap(Rc::new(LayeredHashMapInternals {20 Err(this) => Self(Rc::new(LayeredHashMapInternals {21 parent: Some(LayeredHashMap(this)),21 parent: Some(Self(this)),22 current: new_layer,22 current: new_layer,23 })),23 })),24 }24 }31 {31 {32 (self.0)32 (self.0)33 .current33 .current34 .get(&key)34 .get(key)35 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))35 .or_else(|| self.0.parent.as_ref().and_then(|p| p.get(key)))36 }36 }37}37}383839impl<K: Hash, V> Clone for LayeredHashMap<K, V> {39impl<K: Hash, V> Clone for LayeredHashMap<K, V> {40 fn clone(&self) -> Self {40 fn clone(&self) -> Self {41 LayeredHashMap(self.0.clone())41 Self(self.0.clone())42 }42 }43}43}444445impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {45impl<K: Hash + Eq, V> Default for LayeredHashMap<K, V> {46 fn default() -> Self {46 fn default() -> Self {47 LayeredHashMap(Rc::new(LayeredHashMapInternals {47 Self(Rc::new(LayeredHashMapInternals {48 parent: None,48 parent: None,49 current: FxHashMap::default(),49 current: FxHashMap::default(),50 }))50 }))crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth47}47}484849impl ObjValue {49impl ObjValue {50 pub fn new(50 pub fn new(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {51 super_obj: Option<ObjValue>,52 this_entries: Rc<HashMap<Rc<str>, ObjMember>>,53 ) -> ObjValue {54 ObjValue(Rc::new(ObjValueInternals {51 Self(Rc::new(ObjValueInternals {55 super_obj,52 super_obj,56 this_entries,53 this_entries,57 value_cache: RefCell::new(HashMap::new()),54 value_cache: RefCell::new(HashMap::new()),58 }))55 }))59 }56 }60 pub fn new_empty() -> ObjValue {57 pub fn new_empty() -> Self {61 Self::new(None, Rc::new(HashMap::new()))58 Self::new(None, Rc::new(HashMap::new()))62 }59 }63 pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {60 pub fn with_super(&self, super_obj: Self) -> Self {64 match &self.0.super_obj {61 match &self.0.super_obj {65 None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),62 None => Self::new(Some(super_obj), self.0.this_entries.clone()),66 Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),63 Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),67 }64 }68 }65 }69 pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {66 pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {70 if let Some(s) = &self.0.super_obj {67 if let Some(s) = &self.0.super_obj {71 s.enum_fields(handler);68 s.enum_fields(handler);72 }69 }73 for (name, member) in self.0.this_entries.iter() {70 for (name, member) in self.0.this_entries.iter() {74 handler(&name, &member.visibility);71 handler(name, &member.visibility);75 }72 }76 }73 }77 pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {74 pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {107 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {104 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {108 Ok(self.get_raw(key, self)?)105 Ok(self.get_raw(key, self)?)109 }106 }110 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {107 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {111 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);108 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);112109113 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {110 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {135 .insert(cache_key, value.clone());132 .insert(cache_key, value.clone());136 Ok(value)133 Ok(value)137 }134 }138 fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {135 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {139 Ok(v.invoke136 Ok(v.invoke140 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?137 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?141 .evaluate()?)138 .evaluate()?)crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth17impl PathResolver {17impl PathResolver {18 pub fn resolve(&self, from: &PathBuf) -> String {18 pub fn resolve(&self, from: &PathBuf) -> String {19 match self {19 match self {20 PathResolver::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),20 Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),21 PathResolver::Absolute => from.to_string_lossy().into_owned(),21 Self::Absolute => from.to_string_lossy().into_owned(),22 PathResolver::Relative(base) => {22 Self::Relative(base) => {23 if from.is_relative() {23 if from.is_relative() {24 return from.to_string_lossy().into_owned();24 return from.to_string_lossy().into_owned();25 }25 }crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {26impl LazyVal {27 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {27 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28 LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))28 Self(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29 }29 }30 pub fn new_resolved(val: Val) -> Self {30 pub fn new_resolved(val: Val) -> Self {31 LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))31 Self(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32 }32 }33 pub fn evaluate(&self) -> Result<Val> {33 pub fn evaluate(&self) -> Result<Val> {34 let new_value = match &*self.0.borrow() {34 let new_value = match &*self.0.borrow() {84impl PartialEq for FuncVal {84impl PartialEq for FuncVal {85 fn eq(&self, other: &Self) -> bool {85 fn eq(&self, other: &Self) -> bool {86 match (self, other) {86 match (self, other) {87 (FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,87 (Self::Normal(a), Self::Normal(b)) => a == b,88 (FuncVal::Intrinsic(ans, an), FuncVal::Intrinsic(bns, bn)) => ans == bns && an == bn,88 (Self::Intrinsic(ans, an), Self::Intrinsic(bns, bn)) => ans == bns && an == bn,89 (FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,89 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,90 (..) => false,90 (..) => false,91 }91 }92 }92 }93}93}94impl FuncVal {94impl FuncVal {95 pub fn is_ident(&self) -> bool {95 pub fn is_ident(&self) -> bool {96 matches!(&self, FuncVal::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")96 matches!(&self, Self::Intrinsic(ns, n) if ns as &str == "std" && n as &str == "id")97 }97 }98 pub fn name(&self) -> Rc<str> {98 pub fn name(&self) -> Rc<str> {99 match self {99 match self {100 FuncVal::Normal(normal) => normal.name.clone(),100 Self::Normal(normal) => normal.name.clone(),101 FuncVal::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),101 Self::Intrinsic(ns, name) => format!("intrinsic.{}.{}", ns, name).into(),102 FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),102 Self::NativeExt(n, _) => format!("native.{}", n).into(),103 }103 }104 }104 }105 pub fn evaluate(105 pub fn evaluate(110 tailstrict: bool,110 tailstrict: bool,111 ) -> Result<Val> {111 ) -> Result<Val> {112 match self {112 match self {113 FuncVal::Normal(func) => {113 Self::Normal(func) => {114 let ctx = parse_function_call(114 let ctx = parse_function_call(115 call_ctx,115 call_ctx,116 Some(func.ctx.clone()),116 Some(func.ctx.clone()),120 )?;120 )?;121 evaluate(ctx, &func.body)121 evaluate(ctx, &func.body)122 }122 }123 FuncVal::Intrinsic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),123 Self::Intrinsic(ns, name) => call_builtin(call_ctx, loc, ns, name, args),124 FuncVal::NativeExt(_name, handler) => {124 Self::NativeExt(_name, handler) => {125 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;125 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126 let mut out_args = Vec::with_capacity(handler.params.len());126 let mut out_args = Vec::with_capacity(handler.params.len());127 for p in handler.params.0.iter() {127 for p in handler.params.0.iter() {139 tailstrict: bool,139 tailstrict: bool,140 ) -> Result<Val> {140 ) -> Result<Val> {141 match self {141 match self {142 FuncVal::Normal(func) => {142 Self::Normal(func) => {143 let ctx = parse_function_call_map(143 let ctx = parse_function_call_map(144 call_ctx,144 call_ctx,145 Some(func.ctx.clone()),145 Some(func.ctx.clone()),149 )?;149 )?;150 evaluate(ctx, &func.body)150 evaluate(ctx, &func.body)151 }151 }152 FuncVal::Intrinsic(_, _) => todo!(),152 Self::Intrinsic(_, _) => todo!(),153 FuncVal::NativeExt(_, _) => todo!(),153 Self::NativeExt(_, _) => todo!(),154 }154 }155 }155 }156156157 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {157 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158 match self {158 match self {159 FuncVal::Normal(func) => {159 Self::Normal(func) => {160 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;160 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161 evaluate(ctx, &func.body)161 evaluate(ctx, &func.body)162 }162 }163 FuncVal::Intrinsic(_, _) => todo!(),163 Self::Intrinsic(_, _) => todo!(),164 FuncVal::NativeExt(_, _) => todo!(),164 Self::NativeExt(_, _) => todo!(),165 }165 }166 }166 }167}167}177 Func,177 Func,178}178}179impl ValType {179impl ValType {180 pub fn name(&self) -> &'static str {180 pub const fn name(&self) -> &'static str {181 use ValType::*;181 use ValType::*;182 match self {182 match self {183 Bool => "boolean",183 Bool => "boolean",227impl Val {227impl Val {228 /// Creates `Val::Num` after checking for numeric overflow.228 /// Creates `Val::Num` after checking for numeric overflow.229 /// As numbers are `f64`, we can just check for their finity.229 /// As numbers are `f64`, we can just check for their finity.230 pub fn new_checked_num(num: f64) -> Result<Val> {230 pub fn new_checked_num(num: f64) -> Result<Self> {231 if num.is_finite() {231 if num.is_finite() {232 Ok(Val::Num(num))232 Ok(Self::Num(num))233 } else {233 } else {234 throw!(RuntimeError("overflow".into()))234 throw!(RuntimeError("overflow".into()))235 }235 }245 }245 }246 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {246 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {247 self.assert_type(context, ValType::Bool)?;247 self.assert_type(context, ValType::Bool)?;248 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))248 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Bool(v), v))249 }249 }250 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {250 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {251 self.assert_type(context, ValType::Str)?;251 self.assert_type(context, ValType::Str)?;252 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))252 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Str(v), v))253 }253 }254 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {254 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {255 self.assert_type(context, ValType::Num)?;255 self.assert_type(context, ValType::Num)?;256 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))256 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Self::Num(v), v))257 }257 }258 pub fn inplace_unwrap(&mut self) -> Result<()> {258 pub fn inplace_unwrap(&mut self) -> Result<()> {259 while let Val::Lazy(lazy) = self {259 while let Self::Lazy(lazy) = self {260 *self = lazy.evaluate()?;260 *self = lazy.evaluate()?;261 }261 }262 Ok(())262 Ok(())263 }263 }264 pub fn unwrap_if_lazy(&self) -> Result<Self> {264 pub fn unwrap_if_lazy(&self) -> Result<Self> {265 Ok(if let Val::Lazy(v) = self {265 Ok(if let Self::Lazy(v) = self {266 v.evaluate()?.unwrap_if_lazy()?266 v.evaluate()?.unwrap_if_lazy()?267 } else {267 } else {268 self.clone()268 self.clone()269 })269 })270 }270 }271 pub fn value_type(&self) -> Result<ValType> {271 pub fn value_type(&self) -> Result<ValType> {272 Ok(match self {272 Ok(match self {273 Val::Str(..) => ValType::Str,273 Self::Str(..) => ValType::Str,274 Val::Num(..) => ValType::Num,274 Self::Num(..) => ValType::Num,275 Val::Arr(..) => ValType::Arr,275 Self::Arr(..) => ValType::Arr,276 Val::Obj(..) => ValType::Obj,276 Self::Obj(..) => ValType::Obj,277 Val::Bool(_) => ValType::Bool,277 Self::Bool(_) => ValType::Bool,278 Val::Null => ValType::Null,278 Self::Null => ValType::Null,279 Val::Func(..) => ValType::Func,279 Self::Func(..) => ValType::Func,280 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,280 Self::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,281 })281 })282 }282 }283283284 pub fn to_string(&self) -> Result<Rc<str>> {284 pub fn to_string(&self) -> Result<Rc<str>> {285 Ok(match self.unwrap_if_lazy()? {285 Ok(match self.unwrap_if_lazy()? {286 Val::Bool(true) => "true".into(),286 Self::Bool(true) => "true".into(),287 Val::Bool(false) => "false".into(),287 Self::Bool(false) => "false".into(),288 Val::Null => "null".into(),288 Self::Null => "null".into(),289 Val::Str(s) => s,289 Self::Str(s) => s,290 v => manifest_json_ex(290 v => manifest_json_ex(291 &v,291 &v,292 &ManifestJsonOptions {292 &ManifestJsonOptions {293 padding: &"",293 padding: "",294 mtype: ManifestType::ToString,294 mtype: ManifestType::ToString,295 },295 },296 )?296 )?301 /// Expects value to be object, outputs (key, manifested value) pairs301 /// Expects value to be object, outputs (key, manifested value) pairs302 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {302 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {303 let obj = match self {303 let obj = match self {304 Val::Obj(obj) => obj,304 Self::Obj(obj) => obj,305 _ => throw!(MultiManifestOutputIsNotAObject),305 _ => throw!(MultiManifestOutputIsNotAObject),306 };306 };307 let keys = obj.visible_fields();307 let keys = obj.visible_fields();319 /// Expects value to be array, outputs manifested values319 /// Expects value to be array, outputs manifested values320 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {320 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {321 let arr = match self {321 let arr = match self {322 Val::Arr(a) => a,322 Self::Arr(a) => a,323 _ => throw!(StreamManifestOutputIsNotAArray),323 _ => throw!(StreamManifestOutputIsNotAArray),324 };324 };325 let mut out = Vec::with_capacity(arr.len());325 let mut out = Vec::with_capacity(arr.len());333 Ok(match ty {333 Ok(match ty {334 ManifestFormat::YamlStream(format) => {334 ManifestFormat::YamlStream(format) => {335 let arr = match self {335 let arr = match self {336 Val::Arr(a) => a,336 Self::Arr(a) => a,337 _ => throw!(StreamManifestOutputIsNotAArray),337 _ => throw!(StreamManifestOutputIsNotAArray),338 };338 };339 let mut out = String::new();339 let mut out = String::new();358 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,358 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,359 ManifestFormat::Json(padding) => self.to_json(*padding)?,359 ManifestFormat::Json(padding) => self.to_json(*padding)?,360 ManifestFormat::String => match self {360 ManifestFormat::String => match self {361 Val::Str(s) => s.clone(),361 Self::Str(s) => s.clone(),362 _ => throw!(StringManifestOutputIsNotAString),362 _ => throw!(StringManifestOutputIsNotAString),363 },363 },364 })364 })384 #[cfg(feature = "faster")]384 #[cfg(feature = "faster")]385 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {385 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {386 manifest_json_ex(386 manifest_json_ex(387 &self,387 self,388 &ManifestJsonOptions {388 &ManifestJsonOptions {389 padding: &" ".repeat(padding),389 padding: &" ".repeat(padding),390 mtype: ManifestType::Std,390 mtype: ManifestType::Std,441 }441 }442}442}443443444fn is_function_like(val: &Val) -> bool {444const fn is_function_like(val: &Val) -> bool {445 matches!(val, Val::Func(_))445 matches!(val, Val::Func(_))446}446}447447