difftreelog
feat(evaluator) function signature help
in: master
When calling functions with wrong arguments, evaluator will now suggest correct function signature
2 files 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::{stdlib::format::FormatError, typed::TypeLocError};1011fn format_found(list: &[IStr], what: &str) -> String {12 if list.is_empty() {13 return String::new();14 }15 let mut out = String::new();16 out.push_str("\nThere is ");17 out.push_str(what);18 if list.len() > 1 {19 out.push('s');20 }21 out.push_str(" with similar name");22 if list.len() > 1 {23 out.push('s');24 }25 out.push_str(" present: ");26 for (i, v) in list.iter().enumerate() {27 if i != 0 {28 out.push_str(", ");29 }30 out.push_str(v as &str);31 }32 out33}3435const fn format_empty_str(str: &str) -> &str {36 if str.is_empty() {37 "\"\" (empty string)"38 } else {39 str40 }41}4243#[derive(Error, Debug, Clone, Trace)]44pub enum Error {45 #[error("intrinsic not found: {0}")]46 IntrinsicNotFound(IStr),4748 #[error("operator {0} does not operate on type {1}")]49 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),50 #[error("binary operation {1} {0} {2} is not implemented")]51 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),5253 #[error("no top level object in this context")]54 NoTopLevelObjectFound,55 #[error("self is only usable inside objects")]56 CantUseSelfOutsideOfObject,57 #[error("no super found")]58 NoSuperFound,5960 #[error("for loop can only iterate over arrays")]61 InComprehensionCanOnlyIterateOverArray,6263 #[error("array out of bounds: {0} is not within [0,{1})")]64 ArrayBoundsError(usize, usize),65 #[error("string out of bounds: {0} is not within [0,{1})")]66 StringBoundsError(usize, usize),6768 #[error("assert failed: {}", format_empty_str(.0))]69 AssertionFailed(IStr),7071 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]72 VariableIsNotDefined(IStr, Vec<IStr>),73 #[error("duplicate local var: {0}")]74 DuplicateLocalVar(IStr),7576 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]77 TypeMismatch(&'static str, Vec<ValType>, ValType),78 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]79 NoSuchField(IStr, Vec<IStr>),8081 #[error("only functions can be called, got {0}")]82 OnlyFunctionsCanBeCalledGot(ValType),83 #[error("parameter {0} is not defined")]84 UnknownFunctionParameter(String),85 #[error("argument {0} is already bound")]86 BindingParameterASecondTime(IStr),87 #[error("too many args, function has {0}")]88 TooManyArgsFunctionHas(usize),89 #[error("function argument is not passed: {0}")]90 FunctionParameterNotBoundInCall(IStr),9192 #[error("external variable is not defined: {0}")]93 UndefinedExternalVariable(IStr),9495 #[error("field name should be string, got {0}")]96 FieldMustBeStringGot(ValType),97 #[error("duplicate field name: {}", format_empty_str(.0))]98 DuplicateFieldName(IStr),99100 #[error("attempted to index array with string {}", format_empty_str(.0))]101 AttemptedIndexAnArrayWithString(IStr),102 #[error("{0} index type should be {1}, got {2}")]103 ValueIndexMustBeTypeGot(ValType, ValType, ValType),104 #[error("cant index into {0}")]105 CantIndexInto(ValType),106 #[error("{0} is not indexable")]107 ValueIsNotIndexable(ValType),108109 #[error("super can't be used standalone")]110 StandaloneSuper,111112 #[error("can't resolve {1} from {0}")]113 ImportFileNotFound(PathBuf, String),114 #[error("resolved file not found: {0}")]115 ResolvedFileNotFound(PathBuf),116 #[error("imported file is not valid utf-8: {0:?}")]117 ImportBadFileUtf8(PathBuf),118 #[error("import io error: {0}")]119 ImportIo(String),120 #[error("tried to import {1} from {0}, but imports is not supported")]121 ImportNotSupported(PathBuf, PathBuf),122 #[error("can't import from virtual file")]123 CantImportFromVirtualFile,124 #[error(125 "syntax error: expected {}, got {:?}",126 .error.expected,127 .source_code.chars().nth(error.location.offset)128 .map_or_else(|| "EOF".into(), |c| c.to_string())129 )]130 ImportSyntaxError {131 path: Source,132 source_code: IStr,133 #[trace(skip)]134 error: Box<jrsonnet_parser::ParseError>,135 },136137 #[error("runtime error: {}", format_empty_str(.0))]138 RuntimeError(IStr),139 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]140 StackOverflow,141 #[error("infinite recursion detected")]142 InfiniteRecursionDetected,143 #[error("tried to index by fractional value")]144 FractionalIndex,145 #[error("attempted to divide by zero")]146 DivisionByZero,147148 #[error("string manifest output is not an string")]149 StringManifestOutputIsNotAString,150 #[error("stream manifest output is not an array")]151 StreamManifestOutputIsNotAArray,152 #[error("multi manifest output is not an object")]153 MultiManifestOutputIsNotAObject,154155 #[error("cant recurse stream manifest")]156 StreamManifestOutputCannotBeRecursed,157 #[error("stream manifest output cannot consist of raw strings")]158 StreamManifestCannotNestString,159160 #[error("{}", format_empty_str(.0))]161 ImportCallbackError(String),162 #[error("invalid unicode codepoint: {0}")]163 InvalidUnicodeCodepointGot(u32),164165 #[error("format error: {0}")]166 Format(#[from] FormatError),167 #[error("type error: {0}")]168 TypeError(TypeLocError),169170 #[cfg(feature = "anyhow-error")]171 #[error(transparent)]172 Other(Rc<anyhow::Error>),173}174175#[cfg(feature = "anyhow-error")]176impl From<anyhow::Error> for LocError {177 fn from(e: anyhow::Error) -> Self {178 Self::new(Error::Other(Rc::new(e)))179 }180}181182impl From<Error> for LocError {183 fn from(e: Error) -> Self {184 Self::new(e)185 }186}187188#[derive(Clone, Debug, Trace)]189pub struct StackTraceElement {190 pub location: Option<ExprLocation>,191 pub desc: String,192}193#[derive(Debug, Clone, Trace)]194pub struct StackTrace(pub Vec<StackTraceElement>);195196#[derive(Clone, Trace)]197pub struct LocError(Box<(Error, StackTrace)>);198impl LocError {199 pub fn new(e: Error) -> Self {200 Self(Box::new((e, StackTrace(vec![]))))201 }202203 pub const fn error(&self) -> &Error {204 &(self.0).0205 }206 pub fn error_mut(&mut self) -> &mut Error {207 &mut (self.0).0208 }209 pub const fn trace(&self) -> &StackTrace {210 &(self.0).1211 }212 pub fn trace_mut(&mut self) -> &mut StackTrace {213 &mut (self.0).1214 }215}216impl Debug for LocError {217 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {218 writeln!(f, "{}", self.0 .0)?;219 for el in &self.0 .1 .0 {220 writeln!(f, "\t{:?}", el)?;221 }222 Ok(())223 }224}225226pub type Result<V, E = LocError> = std::result::Result<V, E>;227228#[macro_export]229macro_rules! throw {230 ($e: expr) => {231 return Err($e.into())232 };233}234235#[macro_export]236macro_rules! throw_runtime {237 ($($tt:tt)*) => {238 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())239 };240}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::{stdlib::format::FormatError, typed::TypeLocError};1011fn format_found(list: &[IStr], what: &str) -> String {12 if list.is_empty() {13 return String::new();14 }15 let mut out = String::new();16 out.push_str("\nThere is ");17 out.push_str(what);18 if list.len() > 1 {19 out.push('s');20 }21 out.push_str(" with similar name");22 if list.len() > 1 {23 out.push('s');24 }25 out.push_str(" present: ");26 for (i, v) in list.iter().enumerate() {27 if i != 0 {28 out.push_str(", ");29 }30 out.push_str(v as &str);31 }32 out33}3435fn format_signature(sig: &FunctionSignature) -> String {36 let mut out = String::new();37 out.push_str("\nFunction has the following signature: ");38 out.push('(');39 if sig.is_empty() {40 out.push_str("/*no arguments*/");41 } else {42 for (i, (name, has_default)) in sig.iter().enumerate() {43 if i != 0 {44 out.push_str(", ");45 }46 if let Some(name) = name {47 out.push_str(name);48 } else {49 out.push_str("<unnamed>");50 }51 if *has_default {52 out.push_str(" = <default>");53 }54 }55 }56 out.push(')');57 out58}5960const fn format_empty_str(str: &str) -> &str {61 if str.is_empty() {62 "\"\" (empty string)"63 } else {64 str65 }66}6768type FunctionSignature = Vec<(Option<IStr>, bool)>;6970#[derive(Error, Debug, Clone, Trace)]71pub enum Error {72 #[error("intrinsic not found: {0}")]73 IntrinsicNotFound(IStr),7475 #[error("operator {0} does not operate on type {1}")]76 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),77 #[error("binary operation {1} {0} {2} is not implemented")]78 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),7980 #[error("no top level object in this context")]81 NoTopLevelObjectFound,82 #[error("self is only usable inside objects")]83 CantUseSelfOutsideOfObject,84 #[error("no super found")]85 NoSuperFound,8687 #[error("for loop can only iterate over arrays")]88 InComprehensionCanOnlyIterateOverArray,8990 #[error("array out of bounds: {0} is not within [0,{1})")]91 ArrayBoundsError(usize, usize),92 #[error("string out of bounds: {0} is not within [0,{1})")]93 StringBoundsError(usize, usize),9495 #[error("assert failed: {}", format_empty_str(.0))]96 AssertionFailed(IStr),9798 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]99 VariableIsNotDefined(IStr, Vec<IStr>),100 #[error("duplicate local var: {0}")]101 DuplicateLocalVar(IStr),102103 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]104 TypeMismatch(&'static str, Vec<ValType>, ValType),105 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]106 NoSuchField(IStr, Vec<IStr>),107108 #[error("only functions can be called, got {0}")]109 OnlyFunctionsCanBeCalledGot(ValType),110 #[error("parameter {0} is not defined")]111 UnknownFunctionParameter(String),112 #[error("argument {0} is already bound")]113 BindingParameterASecondTime(IStr),114 #[error("too many args, function has {0}{}", format_signature(.1))]115 TooManyArgsFunctionHas(usize, FunctionSignature),116 #[error("function argument is not passed: {0}{}", format_signature(.1))]117 FunctionParameterNotBoundInCall(IStr, FunctionSignature),118119 #[error("external variable is not defined: {0}")]120 UndefinedExternalVariable(IStr),121122 #[error("field name should be string, got {0}")]123 FieldMustBeStringGot(ValType),124 #[error("duplicate field name: {}", format_empty_str(.0))]125 DuplicateFieldName(IStr),126127 #[error("attempted to index array with string {}", format_empty_str(.0))]128 AttemptedIndexAnArrayWithString(IStr),129 #[error("{0} index type should be {1}, got {2}")]130 ValueIndexMustBeTypeGot(ValType, ValType, ValType),131 #[error("cant index into {0}")]132 CantIndexInto(ValType),133 #[error("{0} is not indexable")]134 ValueIsNotIndexable(ValType),135136 #[error("super can't be used standalone")]137 StandaloneSuper,138139 #[error("can't resolve {1} from {0}")]140 ImportFileNotFound(PathBuf, String),141 #[error("resolved file not found: {0}")]142 ResolvedFileNotFound(PathBuf),143 #[error("imported file is not valid utf-8: {0:?}")]144 ImportBadFileUtf8(PathBuf),145 #[error("import io error: {0}")]146 ImportIo(String),147 #[error("tried to import {1} from {0}, but imports is not supported")]148 ImportNotSupported(PathBuf, PathBuf),149 #[error("can't import from virtual file")]150 CantImportFromVirtualFile,151 #[error(152 "syntax error: expected {}, got {:?}",153 .error.expected,154 .source_code.chars().nth(error.location.offset)155 .map_or_else(|| "EOF".into(), |c| c.to_string())156 )]157 ImportSyntaxError {158 path: Source,159 source_code: IStr,160 #[trace(skip)]161 error: Box<jrsonnet_parser::ParseError>,162 },163164 #[error("runtime error: {}", format_empty_str(.0))]165 RuntimeError(IStr),166 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]167 StackOverflow,168 #[error("infinite recursion detected")]169 InfiniteRecursionDetected,170 #[error("tried to index by fractional value")]171 FractionalIndex,172 #[error("attempted to divide by zero")]173 DivisionByZero,174175 #[error("string manifest output is not an string")]176 StringManifestOutputIsNotAString,177 #[error("stream manifest output is not an array")]178 StreamManifestOutputIsNotAArray,179 #[error("multi manifest output is not an object")]180 MultiManifestOutputIsNotAObject,181182 #[error("cant recurse stream manifest")]183 StreamManifestOutputCannotBeRecursed,184 #[error("stream manifest output cannot consist of raw strings")]185 StreamManifestCannotNestString,186187 #[error("{}", format_empty_str(.0))]188 ImportCallbackError(String),189 #[error("invalid unicode codepoint: {0}")]190 InvalidUnicodeCodepointGot(u32),191192 #[error("format error: {0}")]193 Format(#[from] FormatError),194 #[error("type error: {0}")]195 TypeError(TypeLocError),196197 #[cfg(feature = "anyhow-error")]198 #[error(transparent)]199 Other(Rc<anyhow::Error>),200}201202#[cfg(feature = "anyhow-error")]203impl From<anyhow::Error> for LocError {204 fn from(e: anyhow::Error) -> Self {205 Self::new(Error::Other(Rc::new(e)))206 }207}208209impl From<Error> for LocError {210 fn from(e: Error) -> Self {211 Self::new(e)212 }213}214215#[derive(Clone, Debug, Trace)]216pub struct StackTraceElement {217 pub location: Option<ExprLocation>,218 pub desc: String,219}220#[derive(Debug, Clone, Trace)]221pub struct StackTrace(pub Vec<StackTraceElement>);222223#[derive(Clone, Trace)]224pub struct LocError(Box<(Error, StackTrace)>);225impl LocError {226 pub fn new(e: Error) -> Self {227 Self(Box::new((e, StackTrace(vec![]))))228 }229230 pub const fn error(&self) -> &Error {231 &(self.0).0232 }233 pub fn error_mut(&mut self) -> &mut Error {234 &mut (self.0).0235 }236 pub const fn trace(&self) -> &StackTrace {237 &(self.0).1238 }239 pub fn trace_mut(&mut self) -> &mut StackTrace {240 &mut (self.0).1241 }242}243impl Debug for LocError {244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {245 writeln!(f, "{}", self.0 .0)?;246 for el in &self.0 .1 .0 {247 writeln!(f, "\t{:?}", el)?;248 }249 Ok(())250 }251}252253pub type Result<V, E = LocError> = std::result::Result<V, E>;254255#[macro_export]256macro_rules! throw {257 ($e: expr) => {258 return Err($e.into())259 };260}261262#[macro_export]263macro_rules! throw_runtime {264 ($($tt:tt)*) => {265 return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())266 };267}crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -48,7 +48,10 @@
) -> Result<Context> {
let mut passed_args = GcHashMap::with_capacity(params.len());
if args.unnamed_len() > params.len() {
- throw!(TooManyArgsFunctionHas(params.len()))
+ throw!(TooManyArgsFunctionHas(
+ params.len(),
+ params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
+ ))
}
let mut filled_named = 0;
@@ -126,7 +129,8 @@
.0
.clone()
.name()
- .unwrap_or_else(|| "<destruct>".into())
+ .unwrap_or_else(|| "<destruct>".into()),
+ params.iter().map(|p| (p.0.name(), p.1.is_some())).collect()
));
}
}
@@ -159,7 +163,13 @@
) -> Result<GcHashMap<BuiltinParamName, Thunk<Val>>> {
let mut passed_args = GcHashMap::with_capacity(params.len());
if args.unnamed_len() > params.len() {
- throw!(TooManyArgsFunctionHas(params.len()))
+ throw!(TooManyArgsFunctionHas(
+ params.len(),
+ params
+ .iter()
+ .map(|p| (Some(p.name.as_ref().into()), p.has_default))
+ .collect()
+ ))
}
let mut filled_args = 0;
@@ -202,7 +212,13 @@
}
});
if !found {
- throw!(FunctionParameterNotBoundInCall(param.name.clone().into()));
+ throw!(FunctionParameterNotBoundInCall(
+ param.name.clone().into(),
+ params
+ .iter()
+ .map(|p| (Some(p.name.as_ref().into()), p.has_default))
+ .collect()
+ ));
}
}
unreachable!();
@@ -215,11 +231,15 @@
/// and with unbound values causing error to be returned
pub fn parse_default_function_call(body_ctx: Context, params: &ParamsDesc) -> Result<Context> {
#[derive(Trace)]
- struct DependsOnUnbound(IStr);
+ struct DependsOnUnbound(IStr, ParamsDesc);
impl ThunkValue for DependsOnUnbound {
type Output = Val;
fn get(self: Box<Self>, _: State) -> Result<Val> {
- Err(FunctionParameterNotBoundInCall(self.0.clone()).into())
+ Err(FunctionParameterNotBoundInCall(
+ self.0.clone(),
+ self.1.iter().map(|p| (p.0.name(), p.1.is_some())).collect(),
+ )
+ .into())
}
}
@@ -243,7 +263,8 @@
destruct(
¶m.0,
Thunk::new(tb!(DependsOnUnbound(
- param.0.name().unwrap_or_else(|| "<destruct>".into())
+ param.0.name().unwrap_or_else(|| "<destruct>".into()),
+ params.clone()
))),
fctx.clone(),
&mut bindings,