git.delta.rocks / jrsonnet / refs/commits / c7e1571e1d28

difftreelog

fix std.native should return null if not found

Yaroslav Bolyukin2022-04-22parent: #94fa86f.patch.diff
in: master

2 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -375,13 +375,14 @@
 }
 
 #[jrsonnet_macros::builtin]
-fn builtin_native(s: State, name: IStr) -> Result<FuncVal> {
-	Ok(s.settings()
+fn builtin_native(s: State, name: IStr) -> Result<Any> {
+	Ok(Any(s
+		.settings()
 		.ext_natives
 		.get(&name)
 		.cloned()
-		.map(|v| FuncVal::Builtin(v.clone()))
-		.ok_or(UndefinedExternalFunction(name))?)
+		.map(|v| Val::Func(FuncVal::Builtin(v.clone())))
+		.unwrap_or(Val::Null)))
 }
 
 #[jrsonnet_macros::builtin]
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/error.rs
1use std::{2	fmt::Debug,3	path::{Path, PathBuf},4	rc::Rc,5};67use gcmodule::Trace;8use jrsonnet_interner::IStr;9use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};10use jrsonnet_types::ValType;11use thiserror::Error;1213use crate::{14	builtin::{format::FormatError, sort::SortError},15	typed::TypeLocError,16};1718#[derive(Error, Debug, Clone, Trace)]19pub enum Error {20	#[error("intrinsic not found: {0}")]21	IntrinsicNotFound(IStr),2223	#[error("operator {0} does not operate on type {1}")]24	UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),25	#[error("binary operation {1} {0} {2} is not implemented")]26	BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),2728	#[error("no top level object in this context")]29	NoTopLevelObjectFound,30	#[error("self is only usable inside objects")]31	CantUseSelfOutsideOfObject,32	#[error("no super found")]33	NoSuperFound,3435	#[error("for loop can only iterate over arrays")]36	InComprehensionCanOnlyIterateOverArray,3738	#[error("array out of bounds: {0} is not within [0,{1})")]39	ArrayBoundsError(usize, usize),40	#[error("string out of bounds: {0} is not within [0,{1})")]41	StringBoundsError(usize, usize),4243	#[error("assert failed: {0}")]44	AssertionFailed(IStr),4546	#[error("variable is not defined: {0}")]47	VariableIsNotDefined(IStr),48	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]49	TypeMismatch(&'static str, Vec<ValType>, ValType),50	#[error("no such field: {0}")]51	NoSuchField(IStr),5253	#[error("only functions can be called, got {0}")]54	OnlyFunctionsCanBeCalledGot(ValType),55	#[error("parameter {0} is not defined")]56	UnknownFunctionParameter(String),57	#[error("argument {0} is already bound")]58	BindingParameterASecondTime(IStr),59	#[error("too many args, function has {0}")]60	TooManyArgsFunctionHas(usize),61	#[error("function argument is not passed: {0}")]62	FunctionParameterNotBoundInCall(IStr),6364	#[error("external variable is not defined: {0}")]65	UndefinedExternalVariable(IStr),6667	#[error("field name should be string, got {0}")]68	FieldMustBeStringGot(ValType),69	#[error("duplicate field name: {0}")]70	DuplicateFieldName(IStr),7172	#[error("attempted to index array with string {0}")]73	AttemptedIndexAnArrayWithString(IStr),74	#[error("{0} index type should be {1}, got {2}")]75	ValueIndexMustBeTypeGot(ValType, ValType, ValType),76	#[error("cant index into {0}")]77	CantIndexInto(ValType),78	#[error("{0} is not indexable")]79	ValueIsNotIndexable(ValType),8081	#[error("super can't be used standalone")]82	StandaloneSuper,8384	#[error("can't resolve {1} from {0}")]85	ImportFileNotFound(PathBuf, PathBuf),86	#[error("resolved file not found: {0}")]87	ResolvedFileNotFound(PathBuf),88	#[error("imported file is not valid utf-8: {0:?}")]89	ImportBadFileUtf8(PathBuf),90	#[error("import io error: {0}")]91	ImportIo(String),92	#[error("tried to import {1} from {0}, but imports is not supported")]93	ImportNotSupported(PathBuf, PathBuf),94	#[error(95		"syntax error: expected {}, got {:?}",96		.error.expected,97		.source_code.chars().nth(error.location.offset)98		.map_or_else(|| "EOF".into(), |c| c.to_string())99	)]100	ImportSyntaxError {101		#[skip_trace]102		path: Rc<Path>,103		source_code: IStr,104		#[skip_trace]105		error: Box<jrsonnet_parser::ParseError>,106	},107108	#[error("runtime error: {0}")]109	RuntimeError(IStr),110	#[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]111	StackOverflow,112	#[error("infinite recursion detected")]113	InfiniteRecursionDetected,114	#[error("tried to index by fractional value")]115	FractionalIndex,116	#[error("attempted to divide by zero")]117	DivisionByZero,118119	#[error("string manifest output is not an string")]120	StringManifestOutputIsNotAString,121	#[error("stream manifest output is not an array")]122	StreamManifestOutputIsNotAArray,123	#[error("multi manifest output is not an object")]124	MultiManifestOutputIsNotAObject,125126	#[error("cant recurse stream manifest")]127	StreamManifestOutputCannotBeRecursed,128	#[error("stream manifest output cannot consist of raw strings")]129	StreamManifestCannotNestString,130131	#[error("{0}")]132	ImportCallbackError(String),133	#[error("invalid unicode codepoint: {0}")]134	InvalidUnicodeCodepointGot(u32),135136	#[error("format error: {0}")]137	Format(#[from] FormatError),138	#[error("type error: {0}")]139	TypeError(TypeLocError),140	#[error("sort error: {0}")]141	Sort(#[from] SortError),142143	#[cfg(feature = "anyhow-error")]144	#[error(transparent)]145	Other(Rc<anyhow::Error>),146}147148#[cfg(feature = "anyhow-error")]149impl From<anyhow::Error> for LocError {150	fn from(e: anyhow::Error) -> Self {151		Self::new(Error::Other(Rc::new(e)))152	}153}154155impl From<Error> for LocError {156	fn from(e: Error) -> Self {157		Self::new(e)158	}159}160161#[derive(Clone, Debug, Trace)]162pub struct StackTraceElement {163	pub location: Option<ExprLocation>,164	pub desc: String,165}166#[derive(Debug, Clone, Trace)]167pub struct StackTrace(pub Vec<StackTraceElement>);168169#[derive(Clone, Trace)]170pub struct LocError(Box<(Error, StackTrace)>);171impl LocError {172	pub fn new(e: Error) -> Self {173		Self(Box::new((e, StackTrace(vec![]))))174	}175176	pub const fn error(&self) -> &Error {177		&(self.0).0178	}179	pub fn error_mut(&mut self) -> &mut Error {180		&mut (self.0).0181	}182	pub const fn trace(&self) -> &StackTrace {183		&(self.0).1184	}185	pub fn trace_mut(&mut self) -> &mut StackTrace {186		&mut (self.0).1187	}188}189impl Debug for LocError {190	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {191		writeln!(f, "{}", self.0 .0)?;192		for el in &self.0 .1 .0 {193			writeln!(f, "\t{:?}", el)?;194		}195		Ok(())196	}197}198199pub type Result<V, E = LocError> = std::result::Result<V, E>;200201#[macro_export]202macro_rules! throw {203	($e: expr) => {204		return Err($e.into())205	};206}207208#[macro_export]209macro_rules! throw_runtime {210	($($tt:tt)*) => {211		return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())212	};213}