difftreelog
feat refer to subfields of objects in string formatting
in: master
Upstream issue: https://github.com/google/jsonnet/pull/1011
3 files changed
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{2 fmt::{Debug, Display},3 path::PathBuf,4};56use jrsonnet_gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError};1314fn format_found(list: &[IStr], what: &str) -> String {15 if list.is_empty() {16 return String::new();17 }18 let mut out = String::new();19 out.push_str("\nThere is ");20 out.push_str(what);21 if list.len() > 1 {22 out.push('s');23 }24 out.push_str(" with similar name");25 if list.len() > 1 {26 out.push('s');27 }28 out.push_str(" present: ");29 for (i, v) in list.iter().enumerate() {30 if i != 0 {31 out.push_str(", ");32 }33 out.push_str(v as &str);34 }35 out36}3738fn format_signature(sig: &FunctionSignature) -> String {39 let mut out = String::new();40 out.push_str("\nFunction has the following signature: ");41 out.push('(');42 if sig.is_empty() {43 out.push_str("/*no arguments*/");44 } else {45 for (i, (name, has_default)) in sig.iter().enumerate() {46 if i != 0 {47 out.push_str(", ");48 }49 if let Some(name) = name {50 out.push_str(name);51 } else {52 out.push_str("<unnamed>");53 }54 if *has_default {55 out.push_str(" = <default>");56 }57 }58 }59 out.push(')');60 out61}6263const fn format_empty_str(str: &str) -> &str {64 if str.is_empty() {65 "\"\" (empty string)"66 } else {67 str68 }69}7071type FunctionSignature = Vec<(Option<IStr>, bool)>;7273/// Possible errors74#[allow(missing_docs)]75#[derive(Error, Debug, Clone, Trace)]76#[non_exhaustive]77pub enum ErrorKind {78 #[error("intrinsic not found: {0}")]79 IntrinsicNotFound(IStr),8081 #[error("operator {0} does not operate on type {1}")]82 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),83 #[error("binary operation {1} {0} {2} is not implemented")]84 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8586 #[error("no top level object in this context")]87 NoTopLevelObjectFound,88 #[error("self is only usable inside objects")]89 CantUseSelfOutsideOfObject,90 #[error("no super found")]91 NoSuperFound,9293 #[error("for loop can only iterate over arrays")]94 InComprehensionCanOnlyIterateOverArray,9596 #[error("array out of bounds: {0} is not within [0,{1})")]97 ArrayBoundsError(usize, usize),98 #[error("string out of bounds: {0} is not within [0,{1})")]99 StringBoundsError(usize, usize),100101 #[error("assert failed: {}", format_empty_str(.0))]102 AssertionFailed(IStr),103104 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]105 VariableIsNotDefined(IStr, Vec<IStr>),106 #[error("duplicate local var: {0}")]107 DuplicateLocalVar(IStr),108109 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]110 TypeMismatch(&'static str, Vec<ValType>, ValType),111 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]112 NoSuchField(IStr, Vec<IStr>),113114 #[error("only functions can be called, got {0}")]115 OnlyFunctionsCanBeCalledGot(ValType),116 #[error("parameter {0} is not defined")]117 UnknownFunctionParameter(String),118 #[error("argument {0} is already bound")]119 BindingParameterASecondTime(IStr),120 #[error("too many args, function has {0}{}", format_signature(.1))]121 TooManyArgsFunctionHas(usize, FunctionSignature),122 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]123 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),124125 #[error("external variable is not defined: {0}")]126 UndefinedExternalVariable(IStr),127128 #[error("field name should be string, got {0}")]129 FieldMustBeStringGot(ValType),130 #[error("duplicate field name: {}", format_empty_str(.0))]131 DuplicateFieldName(IStr),132133 #[error("attempted to index array with string {}", format_empty_str(.0))]134 AttemptedIndexAnArrayWithString(IStr),135 #[error("{0} index type should be {1}, got {2}")]136 ValueIndexMustBeTypeGot(ValType, ValType, ValType),137 #[error("cant index into {0}")]138 CantIndexInto(ValType),139 #[error("{0} is not indexable")]140 ValueIsNotIndexable(ValType),141142 #[error("super can't be used standalone")]143 StandaloneSuper,144145 #[error("can't resolve {1} from {0}")]146 ImportFileNotFound(SourcePath, String),147 #[error("can't resolve absolute {0}")]148 AbsoluteImportFileNotFound(PathBuf),149 #[error("resolved file not found: {:?}", .0)]150 ResolvedFileNotFound(SourcePath),151 #[error("can't import {0}: is a directory")]152 ImportIsADirectory(SourcePath),153 #[error("imported file is not valid utf-8: {0:?}")]154 ImportBadFileUtf8(SourcePath),155 #[error("import io error: {0}")]156 ImportIo(String),157 #[error("tried to import {1} from {0}, but imports are not supported")]158 ImportNotSupported(SourcePath, String),159 #[error("tried to import {0}, but absolute imports are not supported")]160 AbsoluteImportNotSupported(PathBuf),161 #[error("can't import from virtual file")]162 CantImportFromVirtualFile,163 #[error(164 "syntax error: expected {}, got {:?}",165 .error.expected,166 .path.code().chars().nth(error.location.offset)167 .map_or_else(|| "EOF".into(), |c| c.to_string())168 )]169 ImportSyntaxError {170 path: Source,171 #[trace(skip)]172 error: Box<jrsonnet_parser::ParseError>,173 },174175 #[error("runtime error: {}", format_empty_str(.0))]176 RuntimeError(IStr),177 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]178 StackOverflow,179 #[error("infinite recursion detected")]180 InfiniteRecursionDetected,181 #[error("tried to index by fractional value")]182 FractionalIndex,183 #[error("attempted to divide by zero")]184 DivisionByZero,185186 #[error("string manifest output is not an string")]187 StringManifestOutputIsNotAString,188 #[error("stream manifest output is not an array")]189 StreamManifestOutputIsNotAArray,190 #[error("multi manifest output is not an object")]191 MultiManifestOutputIsNotAObject,192193 #[error("cant recurse stream manifest")]194 StreamManifestOutputCannotBeRecursed,195 #[error("stream manifest output cannot consist of raw strings")]196 StreamManifestCannotNestString,197198 #[error("{}", format_empty_str(.0))]199 ImportCallbackError(String),200 #[error("invalid unicode codepoint: {0}")]201 InvalidUnicodeCodepointGot(u32),202203 #[error("format error: {0}")]204 Format(#[from] FormatError),205 #[error("type error: {0}")]206 TypeError(TypeLocError),207208 #[cfg(feature = "anyhow-error")]209 #[error(transparent)]210 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),211}212213#[cfg(feature = "anyhow-error")]214impl From<anyhow::Error> for Error {215 fn from(e: anyhow::Error) -> Self {216 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))217 }218}219220impl From<ErrorKind> for Error {221 fn from(e: ErrorKind) -> Self {222 Self::new(e)223 }224}225226/// Single stack trace frame227#[derive(Clone, Debug, Trace)]228pub struct StackTraceElement {229 /// Source of this frame230 /// Some frames only act as description, without attached source231 pub location: Option<ExprLocation>,232 /// Frame description233 pub desc: String,234}235#[derive(Debug, Clone, Trace)]236pub struct StackTrace(pub Vec<StackTraceElement>);237238#[derive(Clone, Trace)]239pub struct Error(Box<(ErrorKind, StackTrace)>);240impl Error {241 pub fn new(e: ErrorKind) -> Self {242 Self(Box::new((e, StackTrace(vec![]))))243 }244245 pub const fn error(&self) -> &ErrorKind {246 &(self.0).0247 }248 pub fn error_mut(&mut self) -> &mut ErrorKind {249 &mut (self.0).0250 }251 pub const fn trace(&self) -> &StackTrace {252 &(self.0).1253 }254 pub fn trace_mut(&mut self) -> &mut StackTrace {255 &mut (self.0).1256 }257}258impl Display for Error {259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {260 writeln!(f, "{}", self.0 .0)?;261 for el in &self.0 .1 .0 {262 write!(f, "\t{}", el.desc)?;263 if let Some(loc) = &el.location {264 write!(f, "at {}", loc.0 .0 .0)?;265 loc.0.map_source_locations(&[loc.1, loc.2]);266 }267 writeln!(f)?;268 }269 Ok(())270 }271}272impl Debug for Error {273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {274 f.debug_tuple("LocError").field(&self.0).finish()275 }276}277impl std::error::Error for Error {}278279pub trait ErrorSource {280 fn to_location(self) -> Option<ExprLocation>;281}282impl ErrorSource for &LocExpr {283 fn to_location(self) -> Option<ExprLocation> {284 Some(self.1.clone())285 }286}287impl ErrorSource for &ExprLocation {288 fn to_location(self) -> Option<ExprLocation> {289 Some(self.clone())290 }291}292impl ErrorSource for CallLocation<'_> {293 fn to_location(self) -> Option<ExprLocation> {294 self.0.cloned()295 }296}297298pub type Result<V, E = Error> = std::result::Result<V, E>;299pub trait ResultExt: Sized {300 #[must_use]301 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;302 #[must_use]303 fn description(self, msg: &str) -> Self {304 self.with_description(|| msg)305 }306307 #[must_use]308 fn with_description_src<O: Into<String>>(309 self,310 src: impl ErrorSource,311 msg: impl FnOnce() -> O,312 ) -> Self;313 #[must_use]314 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {315 self.with_description_src(src, || msg)316 }317}318impl<T> ResultExt for Result<T, Error> {319 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {320 if let Err(e) = &mut self {321 let trace = e.trace_mut();322 trace.0.push(StackTraceElement {323 location: None,324 desc: msg().into(),325 });326 }327 self328 }329330 fn with_description_src<O: Into<String>>(331 mut self,332 src: impl ErrorSource,333 msg: impl FnOnce() -> O,334 ) -> Self {335 if let Err(e) = &mut self {336 let trace = e.trace_mut();337 trace.0.push(StackTraceElement {338 location: src.to_location(),339 desc: msg().into(),340 });341 }342 self343 }344}345346#[macro_export]347macro_rules! throw {348 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {349 return Err($w$(::$i)*$(($($tt)*))?.into())350 };351 ($l:literal) => {352 return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())353 };354 ($l:literal, $($tt:tt)*) => {355 return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())356 };357}1use std::{2 fmt::{Debug, Display},3 path::PathBuf, cmp::Ordering,4};56use jrsonnet_gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError, ObjValue};1314pub(crate) fn format_found(list: &[IStr], what: &str) -> String {15 if list.is_empty() {16 return String::new();17 }18 let mut out = String::new();19 out.push_str("\nThere is ");20 out.push_str(what);21 if list.len() > 1 {22 out.push('s');23 }24 out.push_str(" with similar name");25 if list.len() > 1 {26 out.push('s');27 }28 out.push_str(" present: ");29 for (i, v) in list.iter().enumerate() {30 if i != 0 {31 out.push_str(", ");32 }33 out.push_str(v as &str);34 }35 out36}3738fn format_signature(sig: &FunctionSignature) -> String {39 let mut out = String::new();40 out.push_str("\nFunction has the following signature: ");41 out.push('(');42 if sig.is_empty() {43 out.push_str("/*no arguments*/");44 } else {45 for (i, (name, has_default)) in sig.iter().enumerate() {46 if i != 0 {47 out.push_str(", ");48 }49 if let Some(name) = name {50 out.push_str(name);51 } else {52 out.push_str("<unnamed>");53 }54 if *has_default {55 out.push_str(" = <default>");56 }57 }58 }59 out.push(')');60 out61}6263const fn format_empty_str(str: &str) -> &str {64 if str.is_empty() {65 "\"\" (empty string)"66 } else {67 str68 }69}7071pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {72 let mut heap = Vec::new();73 for field in v.fields_ex(74 true,75 #[cfg(feature = "exp-preserve-order")]76 false,77 ) {78 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());79 if conf < 0.8 {80 continue;81 }82 if field.as_str() == key.as_str() {83 panic!("looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");84 }85 heap.push((conf, field));86 }87 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));88 heap.into_iter().map(|v| v.1).collect()89}9091type FunctionSignature = Vec<(Option<IStr>, bool)>;9293/// Possible errors94#[allow(missing_docs)]95#[derive(Error, Debug, Clone, Trace)]96#[non_exhaustive]97pub enum ErrorKind {98 #[error("intrinsic not found: {0}")]99 IntrinsicNotFound(IStr),100101 #[error("operator {0} does not operate on type {1}")]102 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),103 #[error("binary operation {1} {0} {2} is not implemented")]104 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),105106 #[error("no top level object in this context")]107 NoTopLevelObjectFound,108 #[error("self is only usable inside objects")]109 CantUseSelfOutsideOfObject,110 #[error("no super found")]111 NoSuperFound,112113 #[error("for loop can only iterate over arrays")]114 InComprehensionCanOnlyIterateOverArray,115116 #[error("array out of bounds: {0} is not within [0,{1})")]117 ArrayBoundsError(usize, usize),118 #[error("string out of bounds: {0} is not within [0,{1})")]119 StringBoundsError(usize, usize),120121 #[error("assert failed: {}", format_empty_str(.0))]122 AssertionFailed(IStr),123124 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]125 VariableIsNotDefined(IStr, Vec<IStr>),126 #[error("duplicate local var: {0}")]127 DuplicateLocalVar(IStr),128129 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]130 TypeMismatch(&'static str, Vec<ValType>, ValType),131 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]132 NoSuchField(IStr, Vec<IStr>),133134 #[error("only functions can be called, got {0}")]135 OnlyFunctionsCanBeCalledGot(ValType),136 #[error("parameter {0} is not defined")]137 UnknownFunctionParameter(String),138 #[error("argument {0} is already bound")]139 BindingParameterASecondTime(IStr),140 #[error("too many args, function has {0}{}", format_signature(.1))]141 TooManyArgsFunctionHas(usize, FunctionSignature),142 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]143 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),144145 #[error("external variable is not defined: {0}")]146 UndefinedExternalVariable(IStr),147148 #[error("field name should be string, got {0}")]149 FieldMustBeStringGot(ValType),150 #[error("duplicate field name: {}", format_empty_str(.0))]151 DuplicateFieldName(IStr),152153 #[error("attempted to index array with string {}", format_empty_str(.0))]154 AttemptedIndexAnArrayWithString(IStr),155 #[error("{0} index type should be {1}, got {2}")]156 ValueIndexMustBeTypeGot(ValType, ValType, ValType),157 #[error("cant index into {0}")]158 CantIndexInto(ValType),159 #[error("{0} is not indexable")]160 ValueIsNotIndexable(ValType),161162 #[error("super can't be used standalone")]163 StandaloneSuper,164165 #[error("can't resolve {1} from {0}")]166 ImportFileNotFound(SourcePath, String),167 #[error("can't resolve absolute {0}")]168 AbsoluteImportFileNotFound(PathBuf),169 #[error("resolved file not found: {:?}", .0)]170 ResolvedFileNotFound(SourcePath),171 #[error("can't import {0}: is a directory")]172 ImportIsADirectory(SourcePath),173 #[error("imported file is not valid utf-8: {0:?}")]174 ImportBadFileUtf8(SourcePath),175 #[error("import io error: {0}")]176 ImportIo(String),177 #[error("tried to import {1} from {0}, but imports are not supported")]178 ImportNotSupported(SourcePath, String),179 #[error("tried to import {0}, but absolute imports are not supported")]180 AbsoluteImportNotSupported(PathBuf),181 #[error("can't import from virtual file")]182 CantImportFromVirtualFile,183 #[error(184 "syntax error: expected {}, got {:?}",185 .error.expected,186 .path.code().chars().nth(error.location.offset)187 .map_or_else(|| "EOF".into(), |c| c.to_string())188 )]189 ImportSyntaxError {190 path: Source,191 #[trace(skip)]192 error: Box<jrsonnet_parser::ParseError>,193 },194195 #[error("runtime error: {}", format_empty_str(.0))]196 RuntimeError(IStr),197 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]198 StackOverflow,199 #[error("infinite recursion detected")]200 InfiniteRecursionDetected,201 #[error("tried to index by fractional value")]202 FractionalIndex,203 #[error("attempted to divide by zero")]204 DivisionByZero,205206 #[error("string manifest output is not an string")]207 StringManifestOutputIsNotAString,208 #[error("stream manifest output is not an array")]209 StreamManifestOutputIsNotAArray,210 #[error("multi manifest output is not an object")]211 MultiManifestOutputIsNotAObject,212213 #[error("cant recurse stream manifest")]214 StreamManifestOutputCannotBeRecursed,215 #[error("stream manifest output cannot consist of raw strings")]216 StreamManifestCannotNestString,217218 #[error("{}", format_empty_str(.0))]219 ImportCallbackError(String),220 #[error("invalid unicode codepoint: {0}")]221 InvalidUnicodeCodepointGot(u32),222223 #[error("format error: {0}")]224 Format(#[from] FormatError),225 #[error("type error: {0}")]226 TypeError(TypeLocError),227228 #[cfg(feature = "anyhow-error")]229 #[error(transparent)]230 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),231}232233#[cfg(feature = "anyhow-error")]234impl From<anyhow::Error> for Error {235 fn from(e: anyhow::Error) -> Self {236 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))237 }238}239240impl From<ErrorKind> for Error {241 fn from(e: ErrorKind) -> Self {242 Self::new(e)243 }244}245246/// Single stack trace frame247#[derive(Clone, Debug, Trace)]248pub struct StackTraceElement {249 /// Source of this frame250 /// Some frames only act as description, without attached source251 pub location: Option<ExprLocation>,252 /// Frame description253 pub desc: String,254}255#[derive(Debug, Clone, Trace)]256pub struct StackTrace(pub Vec<StackTraceElement>);257258#[derive(Clone, Trace)]259pub struct Error(Box<(ErrorKind, StackTrace)>);260impl Error {261 pub fn new(e: ErrorKind) -> Self {262 Self(Box::new((e, StackTrace(vec![]))))263 }264265 pub const fn error(&self) -> &ErrorKind {266 &(self.0).0267 }268 pub fn error_mut(&mut self) -> &mut ErrorKind {269 &mut (self.0).0270 }271 pub const fn trace(&self) -> &StackTrace {272 &(self.0).1273 }274 pub fn trace_mut(&mut self) -> &mut StackTrace {275 &mut (self.0).1276 }277}278impl Display for Error {279 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {280 writeln!(f, "{}", self.0 .0)?;281 for el in &self.0 .1 .0 {282 write!(f, "\t{}", el.desc)?;283 if let Some(loc) = &el.location {284 write!(f, "at {}", loc.0 .0 .0)?;285 loc.0.map_source_locations(&[loc.1, loc.2]);286 }287 writeln!(f)?;288 }289 Ok(())290 }291}292impl Debug for Error {293 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {294 f.debug_tuple("LocError").field(&self.0).finish()295 }296}297impl std::error::Error for Error {}298299pub trait ErrorSource {300 fn to_location(self) -> Option<ExprLocation>;301}302impl ErrorSource for &LocExpr {303 fn to_location(self) -> Option<ExprLocation> {304 Some(self.1.clone())305 }306}307impl ErrorSource for &ExprLocation {308 fn to_location(self) -> Option<ExprLocation> {309 Some(self.clone())310 }311}312impl ErrorSource for CallLocation<'_> {313 fn to_location(self) -> Option<ExprLocation> {314 self.0.cloned()315 }316}317318pub type Result<V, E = Error> = std::result::Result<V, E>;319pub trait ResultExt: Sized {320 #[must_use]321 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;322 #[must_use]323 fn description(self, msg: &str) -> Self {324 self.with_description(|| msg)325 }326327 #[must_use]328 fn with_description_src<O: Into<String>>(329 self,330 src: impl ErrorSource,331 msg: impl FnOnce() -> O,332 ) -> Self;333 #[must_use]334 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {335 self.with_description_src(src, || msg)336 }337}338impl<T> ResultExt for Result<T, Error> {339 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {340 if let Err(e) = &mut self {341 let trace = e.trace_mut();342 trace.0.push(StackTraceElement {343 location: None,344 desc: msg().into(),345 });346 }347 self348 }349350 fn with_description_src<O: Into<String>>(351 mut self,352 src: impl ErrorSource,353 msg: impl FnOnce() -> O,354 ) -> Self {355 if let Err(e) = &mut self {356 let trace = e.trace_mut();357 trace.0.push(StackTraceElement {358 location: src.to_location(),359 desc: msg().into(),360 });361 }362 self363 }364}365366#[macro_export]367macro_rules! throw {368 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {369 return Err($w$(::$i)*$(($($tt)*))?.into())370 };371 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {372 return Err($w$(::$i)*$({$($tt)*})?.into())373 };374 ($l:literal) => {375 return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())376 };377 ($l:literal, $($tt:tt)*) => {378 return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())379 };380}crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -12,7 +12,7 @@
use crate::{
arr::ArrValue,
destructure::evaluate_dest,
- error::ErrorKind::*,
+ error::{ErrorKind::*, suggest_object_fields},
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
throw,
@@ -466,31 +466,10 @@
|| format!("field <{key}> access"),
|| match v.get(key.clone().into_flat()) {
Ok(Some(v)) => Ok(v),
- #[cfg(not(feature = "friendly-errors"))]
- Ok(None) => throw!(NoSuchField(key.clone(), vec![])),
- #[cfg(feature = "friendly-errors")]
Ok(None) => {
- let mut heap = Vec::new();
- for field in v.fields_ex(
- true,
- #[cfg(feature = "exp-preserve-order")]
- false,
- ) {
- let conf = strsim::jaro_winkler(
- &field as &str,
- &key.clone().into_flat() as &str,
- );
- if conf < 0.8 {
- continue;
- }
- heap.push((conf, field));
- }
- heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
+ let suggestions = suggest_object_fields(&v, key.clone().into_flat());
- throw!(NoSuchField(
- key.clone().into_flat(),
- heap.into_iter().map(|(_, v)| v).collect()
- ))
+ throw!(NoSuchField(key.clone().into_flat(), suggestions))
}
Err(e) => Err(e),
},
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -6,7 +6,12 @@
use jrsonnet_types::ValType;
use thiserror::Error;
-use crate::{error::ErrorKind::*, throw, typed::Typed, Error, ObjValue, Result, Val};
+use crate::{
+ error::{format_found, suggest_object_fields, ErrorKind::*},
+ throw,
+ typed::Typed,
+ Error, ObjValue, Result, Val,
+};
#[derive(Debug, Clone, Error, Trace)]
pub enum FormatError {
@@ -24,6 +29,15 @@
MappingKeysRequired,
#[error("no such format field: {0}")]
NoSuchFormatField(IStr),
+
+ #[error("expected subfield <{0}> to be an object, got {1} instead")]
+ SubfieldDidntYieldAnObject(IStr, ValType),
+ #[error("subfield not found: <[{full}]{current}>{}", format_found(.found, "subfield"))]
+ SubfieldNotFound {
+ current: IStr,
+ full: IStr,
+ found: Box<Vec<IStr>>,
+ },
}
impl From<FormatError> for Error {
@@ -691,6 +705,37 @@
Ok(out)
}
+fn get_dotted_field(obj: ObjValue, field: &str) -> Result<Val> {
+ let mut current = Val::Obj(obj);
+ let mut name_offset = 0;
+ for component in field.split('.') {
+ let end_offset = name_offset + component.len();
+ current = if let Val::Obj(obj) = current {
+ if let Some(value) = obj.get(component.into())? {
+ value
+ } else {
+ let current = &field[name_offset..end_offset];
+ let full = &field[..name_offset];
+ let found = Box::new(suggest_object_fields(&obj, current.into()));
+ throw!(SubfieldNotFound {
+ current: current.into(),
+ full: full.into(),
+ found,
+ })
+ }
+ } else {
+ // No underflow may happen, initially we always start with an object
+ let subfield = &field[..name_offset - 1];
+ throw!(SubfieldDidntYieldAnObject(
+ subfield.into(),
+ current.value_type()
+ ));
+ };
+ name_offset = end_offset + 1;
+ }
+ Ok(current)
+}
+
pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {
let codes = parse_codes(str)?;
let mut out = String::new();
@@ -726,7 +771,7 @@
if let Some(v) = values.get(f.clone())? {
v
} else {
- throw!(NoSuchFormatField(f));
+ get_dotted_field(values.clone(), &f)?
}
};