difftreelog
feat prettier error display for empty strings
in: master
1 file changed
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{fmt::Debug, path::PathBuf};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10 stdlib::{format::FormatError, sort::SortError},11 typed::TypeLocError,12};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}3738#[derive(Error, Debug, Clone, Trace)]39pub enum Error {40 #[error("intrinsic not found: {0}")]41 IntrinsicNotFound(IStr),4243 #[error("operator {0} does not operate on type {1}")]44 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),45 #[error("binary operation {1} {0} {2} is not implemented")]46 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),4748 #[error("no top level object in this context")]49 NoTopLevelObjectFound,50 #[error("self is only usable inside objects")]51 CantUseSelfOutsideOfObject,52 #[error("no super found")]53 NoSuperFound,5455 #[error("for loop can only iterate over arrays")]56 InComprehensionCanOnlyIterateOverArray,5758 #[error("array out of bounds: {0} is not within [0,{1})")]59 ArrayBoundsError(usize, usize),60 #[error("string out of bounds: {0} is not within [0,{1})")]61 StringBoundsError(usize, usize),6263 #[error("assert failed: {0}")]64 AssertionFailed(IStr),6566 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]67 VariableIsNotDefined(IStr, Vec<IStr>),68 #[error("duplicate local var: {0}")]69 DuplicateLocalVar(IStr),7071 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]72 TypeMismatch(&'static str, Vec<ValType>, ValType),73 #[error("no such field: {0}{}", format_found(.1, "field"))]74 NoSuchField(IStr, Vec<IStr>),7576 #[error("only functions can be called, got {0}")]77 OnlyFunctionsCanBeCalledGot(ValType),78 #[error("parameter {0} is not defined")]79 UnknownFunctionParameter(String),80 #[error("argument {0} is already bound")]81 BindingParameterASecondTime(IStr),82 #[error("too many args, function has {0}")]83 TooManyArgsFunctionHas(usize),84 #[error("function argument is not passed: {0}")]85 FunctionParameterNotBoundInCall(IStr),8687 #[error("external variable is not defined: {0}")]88 UndefinedExternalVariable(IStr),8990 #[error("field name should be string, got {0}")]91 FieldMustBeStringGot(ValType),92 #[error("duplicate field name: {0}")]93 DuplicateFieldName(IStr),9495 #[error("attempted to index array with string {0}")]96 AttemptedIndexAnArrayWithString(IStr),97 #[error("{0} index type should be {1}, got {2}")]98 ValueIndexMustBeTypeGot(ValType, ValType, ValType),99 #[error("cant index into {0}")]100 CantIndexInto(ValType),101 #[error("{0} is not indexable")]102 ValueIsNotIndexable(ValType),103104 #[error("super can't be used standalone")]105 StandaloneSuper,106107 #[error("can't resolve {1} from {0}")]108 ImportFileNotFound(PathBuf, String),109 #[error("resolved file not found: {0}")]110 ResolvedFileNotFound(PathBuf),111 #[error("imported file is not valid utf-8: {0:?}")]112 ImportBadFileUtf8(PathBuf),113 #[error("import io error: {0}")]114 ImportIo(String),115 #[error("tried to import {1} from {0}, but imports is not supported")]116 ImportNotSupported(PathBuf, PathBuf),117 #[error("can't import from virtual file")]118 CantImportFromVirtualFile,119 #[error(120 "syntax error: expected {}, got {:?}",121 .error.expected,122 .source_code.chars().nth(error.location.offset)123 .map_or_else(|| "EOF".into(), |c| c.to_string())124 )]125 ImportSyntaxError {126 path: Source,127 source_code: IStr,128 #[trace(skip)]129 error: Box<jrsonnet_parser::ParseError>,130 },131132 #[error("runtime error: {0}")]133 RuntimeError(IStr),134 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]135 StackOverflow,136 #[error("infinite recursion detected")]137 InfiniteRecursionDetected,138 #[error("tried to index by fractional value")]139 FractionalIndex,140 #[error("attempted to divide by zero")]141 DivisionByZero,142143 #[error("string manifest output is not an string")]144 StringManifestOutputIsNotAString,145 #[error("stream manifest output is not an array")]146 StreamManifestOutputIsNotAArray,147 #[error("multi manifest output is not an object")]148 MultiManifestOutputIsNotAObject,149150 #[error("cant recurse stream manifest")]151 StreamManifestOutputCannotBeRecursed,152 #[error("stream manifest output cannot consist of raw strings")]153 StreamManifestCannotNestString,154155 #[error("{0}")]156 ImportCallbackError(String),157 #[error("invalid unicode codepoint: {0}")]158 InvalidUnicodeCodepointGot(u32),159160 #[error("format error: {0}")]161 Format(#[from] FormatError),162 #[error("type error: {0}")]163 TypeError(TypeLocError),164 #[error("sort error: {0}")]165 Sort(#[from] SortError),166167 /// Thrown as error, as this is legacy feature, and error here168 /// is acceptable for defeating object field cache169 #[error("should not reach outside: std.thisFile")]170 MagicThisFileUsed,171172 #[cfg(feature = "anyhow-error")]173 #[error(transparent)]174 Other(Rc<anyhow::Error>),175}176177#[cfg(feature = "anyhow-error")]178impl From<anyhow::Error> for LocError {179 fn from(e: anyhow::Error) -> Self {180 Self::new(Error::Other(Rc::new(e)))181 }182}183184impl From<Error> for LocError {185 fn from(e: Error) -> Self {186 Self::new(e)187 }188}189190#[derive(Clone, Debug, Trace)]191pub struct StackTraceElement {192 pub location: Option<ExprLocation>,193 pub desc: String,194}195#[derive(Debug, Clone, Trace)]196pub struct StackTrace(pub Vec<StackTraceElement>);197198#[derive(Clone, Trace)]199pub struct LocError(Box<(Error, StackTrace)>);200impl LocError {201 pub fn new(e: Error) -> Self {202 Self(Box::new((e, StackTrace(vec![]))))203 }204205 pub const fn error(&self) -> &Error {206 &(self.0).0207 }208 pub fn error_mut(&mut self) -> &mut Error {209 &mut (self.0).0210 }211 pub const fn trace(&self) -> &StackTrace {212 &(self.0).1213 }214 pub fn trace_mut(&mut self) -> &mut StackTrace {215 &mut (self.0).1216 }217}218impl Debug for LocError {219 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {220 writeln!(f, "{}", self.0 .0)?;221 for el in &self.0 .1 .0 {222 writeln!(f, "\t{:?}", el)?;223 }224 Ok(())225 }226}227228pub type Result<V, E = LocError> = std::result::Result<V, E>;229230#[macro_export]231macro_rules! throw {232 ($e: expr) => {233 return Err($e.into())234 };235}236237#[macro_export]238macro_rules! throw_runtime {239 ($($tt:tt)*) => {240 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())241 };242}1use std::{fmt::Debug, path::PathBuf};23use jrsonnet_gcmodule::Trace;4use jrsonnet_interner::IStr;5use jrsonnet_parser::{BinaryOpType, ExprLocation, Source, UnaryOpType};6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10 stdlib::{format::FormatError, sort::SortError},11 typed::TypeLocError,12};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}3738const fn format_empty_str(str: &str) -> &str {39 if str.is_empty() {40 "\"\" (empty string)"41 } else {42 str43 }44}4546#[derive(Error, Debug, Clone, Trace)]47pub enum Error {48 #[error("intrinsic not found: {0}")]49 IntrinsicNotFound(IStr),5051 #[error("operator {0} does not operate on type {1}")]52 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),53 #[error("binary operation {1} {0} {2} is not implemented")]54 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),5556 #[error("no top level object in this context")]57 NoTopLevelObjectFound,58 #[error("self is only usable inside objects")]59 CantUseSelfOutsideOfObject,60 #[error("no super found")]61 NoSuperFound,6263 #[error("for loop can only iterate over arrays")]64 InComprehensionCanOnlyIterateOverArray,6566 #[error("array out of bounds: {0} is not within [0,{1})")]67 ArrayBoundsError(usize, usize),68 #[error("string out of bounds: {0} is not within [0,{1})")]69 StringBoundsError(usize, usize),7071 #[error("assert failed: {}", format_empty_str(.0))]72 AssertionFailed(IStr),7374 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]75 VariableIsNotDefined(IStr, Vec<IStr>),76 #[error("duplicate local var: {0}")]77 DuplicateLocalVar(IStr),7879 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]80 TypeMismatch(&'static str, Vec<ValType>, ValType),81 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]82 NoSuchField(IStr, Vec<IStr>),8384 #[error("only functions can be called, got {0}")]85 OnlyFunctionsCanBeCalledGot(ValType),86 #[error("parameter {0} is not defined")]87 UnknownFunctionParameter(String),88 #[error("argument {0} is already bound")]89 BindingParameterASecondTime(IStr),90 #[error("too many args, function has {0}")]91 TooManyArgsFunctionHas(usize),92 #[error("function argument is not passed: {0}")]93 FunctionParameterNotBoundInCall(IStr),9495 #[error("external variable is not defined: {0}")]96 UndefinedExternalVariable(IStr),9798 #[error("field name should be string, got {0}")]99 FieldMustBeStringGot(ValType),100 #[error("duplicate field name: {}", format_empty_str(.0))]101 DuplicateFieldName(IStr),102103 #[error("attempted to index array with string {}", format_empty_str(.0))]104 AttemptedIndexAnArrayWithString(IStr),105 #[error("{0} index type should be {1}, got {2}")]106 ValueIndexMustBeTypeGot(ValType, ValType, ValType),107 #[error("cant index into {0}")]108 CantIndexInto(ValType),109 #[error("{0} is not indexable")]110 ValueIsNotIndexable(ValType),111112 #[error("super can't be used standalone")]113 StandaloneSuper,114115 #[error("can't resolve {1} from {0}")]116 ImportFileNotFound(PathBuf, String),117 #[error("resolved file not found: {0}")]118 ResolvedFileNotFound(PathBuf),119 #[error("imported file is not valid utf-8: {0:?}")]120 ImportBadFileUtf8(PathBuf),121 #[error("import io error: {0}")]122 ImportIo(String),123 #[error("tried to import {1} from {0}, but imports is not supported")]124 ImportNotSupported(PathBuf, PathBuf),125 #[error("can't import from virtual file")]126 CantImportFromVirtualFile,127 #[error(128 "syntax error: expected {}, got {:?}",129 .error.expected,130 .source_code.chars().nth(error.location.offset)131 .map_or_else(|| "EOF".into(), |c| c.to_string())132 )]133 ImportSyntaxError {134 path: Source,135 source_code: IStr,136 #[trace(skip)]137 error: Box<jrsonnet_parser::ParseError>,138 },139140 #[error("runtime error: {}", format_empty_str(.0))]141 RuntimeError(IStr),142 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]143 StackOverflow,144 #[error("infinite recursion detected")]145 InfiniteRecursionDetected,146 #[error("tried to index by fractional value")]147 FractionalIndex,148 #[error("attempted to divide by zero")]149 DivisionByZero,150151 #[error("string manifest output is not an string")]152 StringManifestOutputIsNotAString,153 #[error("stream manifest output is not an array")]154 StreamManifestOutputIsNotAArray,155 #[error("multi manifest output is not an object")]156 MultiManifestOutputIsNotAObject,157158 #[error("cant recurse stream manifest")]159 StreamManifestOutputCannotBeRecursed,160 #[error("stream manifest output cannot consist of raw strings")]161 StreamManifestCannotNestString,162163 #[error("{}", format_empty_str(.0))]164 ImportCallbackError(String),165 #[error("invalid unicode codepoint: {0}")]166 InvalidUnicodeCodepointGot(u32),167168 #[error("format error: {0}")]169 Format(#[from] FormatError),170 #[error("type error: {0}")]171 TypeError(TypeLocError),172 #[error("sort error: {0}")]173 Sort(#[from] SortError),174175 /// Thrown as error, as this is legacy feature, and error here176 /// is acceptable for defeating object field cache177 #[error("should not reach outside: std.thisFile")]178 MagicThisFileUsed,179180 #[cfg(feature = "anyhow-error")]181 #[error(transparent)]182 Other(Rc<anyhow::Error>),183}184185#[cfg(feature = "anyhow-error")]186impl From<anyhow::Error> for LocError {187 fn from(e: anyhow::Error) -> Self {188 Self::new(Error::Other(Rc::new(e)))189 }190}191192impl From<Error> for LocError {193 fn from(e: Error) -> Self {194 Self::new(e)195 }196}197198#[derive(Clone, Debug, Trace)]199pub struct StackTraceElement {200 pub location: Option<ExprLocation>,201 pub desc: String,202}203#[derive(Debug, Clone, Trace)]204pub struct StackTrace(pub Vec<StackTraceElement>);205206#[derive(Clone, Trace)]207pub struct LocError(Box<(Error, StackTrace)>);208impl LocError {209 pub fn new(e: Error) -> Self {210 Self(Box::new((e, StackTrace(vec![]))))211 }212213 pub const fn error(&self) -> &Error {214 &(self.0).0215 }216 pub fn error_mut(&mut self) -> &mut Error {217 &mut (self.0).0218 }219 pub const fn trace(&self) -> &StackTrace {220 &(self.0).1221 }222 pub fn trace_mut(&mut self) -> &mut StackTrace {223 &mut (self.0).1224 }225}226impl Debug for LocError {227 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {228 writeln!(f, "{}", self.0 .0)?;229 for el in &self.0 .1 .0 {230 writeln!(f, "\t{:?}", el)?;231 }232 Ok(())233 }234}235236pub type Result<V, E = LocError> = std::result::Result<V, E>;237238#[macro_export]239macro_rules! throw {240 ($e: expr) => {241 return Err($e.into())242 };243}244245#[macro_export]246macro_rules! throw_runtime {247 ($($tt:tt)*) => {248 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())249 };250}