difftreelog
style fix clippy warnings
in: master
35 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -68,6 +68,15 @@
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
+name = "block-buffer"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
name = "cc"
version = "1.0.73"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -141,6 +150,45 @@
]
[[package]]
+name = "cpufeatures"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "adfbc57365a37acbd2ebf2b64d7e69bb766e2fea813521ed536f5d0520dcf86c"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
name = "getrandom"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -304,6 +352,7 @@
"serde",
"serde_json",
"serde_yaml_with_quirks",
+ "sha2",
"structdump",
]
@@ -550,6 +599,17 @@
]
[[package]]
+name = "sha2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
+dependencies = [
+ "cfg-if 1.0.0",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
name = "smallvec"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -640,6 +700,12 @@
]
[[package]]
+name = "typenum"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
+
+[[package]]
name = "unicode-ident"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -12,7 +12,7 @@
};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
throw, FileImportResolver, ImportResolver,
};
use jrsonnet_gcmodule::Trace;
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::box_default)]
+
#[cfg(feature = "interop")]
pub mod interop;
@@ -20,11 +22,11 @@
apply_tla,
function::TlaArg,
gc::GcHashMap,
+ manifest::{JsonFormat, ManifestFormat, ToStringFormat},
stack::set_stack_depth_limit,
- stdlib::manifest::{JsonFormat, ToStringFormat},
tb, throw,
trace::{CompactFormat, PathResolver, TraceFormat},
- FileImportResolver, IStr, ManifestFormat, Result, State, Val,
+ FileImportResolver, IStr, Result, State, Val,
};
/// WASM stub
@@ -193,7 +195,7 @@
let filename = parse_path(CStr::from_ptr(filename));
match vm
.state
- .import(&filename)
+ .import(filename)
.and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
.and_then(|val| val.manifest(&vm.manifest_format))
{
@@ -286,7 +288,7 @@
let filename = parse_path(CStr::from_ptr(filename));
match vm
.state
- .import(&filename)
+ .import(filename)
.and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
.and_then(|val| val_to_multi(val, &vm.manifest_format))
{
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -5,7 +5,7 @@
};
use jrsonnet_evaluator::{
- error::{Error, LocError},
+ error::{Error, ErrorKind},
function::builtin::{NativeCallback, NativeCallbackHandler},
tb,
typed::Typed,
@@ -38,7 +38,7 @@
cb: JsonnetNativeCallback,
}
impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
- fn call(&self, args: &[Val]) -> Result<Val, LocError> {
+ fn call(&self, args: &[Val]) -> Result<Val, Error> {
let mut n_args = Vec::new();
for a in args {
n_args.push(Some(Box::new(a.clone())));
@@ -57,7 +57,7 @@
Ok(v)
} else {
let e = IStr::from_untyped(v).expect("error msg should be a string");
- Err(Error::RuntimeError(e).into())
+ Err(ErrorKind::RuntimeError(e).into())
}
}
}
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -6,7 +6,11 @@
use clap::{CommandFactory, Parser};
use clap_complete::Shell;
use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
-use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};
+use jrsonnet_evaluator::{
+ apply_tla,
+ error::{Error as JrError, ErrorKind},
+ throw, ResultExt, State, Val,
+};
#[cfg(feature = "mimalloc")]
#[global_allocator]
@@ -96,7 +100,7 @@
enum Error {
// Handled differently
#[error("evaluation error")]
- Evaluation(LocError),
+ Evaluation(JrError),
#[error("io error")]
Io(#[from] std::io::Error),
#[error("input is not utf8 encoded")]
@@ -104,14 +108,14 @@
#[error("missing input argument")]
MissingInputArgument,
}
-impl From<LocError> for Error {
- fn from(e: LocError) -> Self {
+impl From<JrError> for Error {
+ fn from(e: JrError) -> Self {
Self::Evaluation(e)
}
}
-impl From<jrsonnet_evaluator::error::Error> for Error {
- fn from(e: jrsonnet_evaluator::error::Error) -> Self {
- Self::from(LocError::from(e))
+impl From<ErrorKind> for Error {
+ fn from(e: ErrorKind) -> Self {
+ Self::from(JrError::from(e))
}
}
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -3,9 +3,10 @@
use clap::{Parser, ValueEnum};
use jrsonnet_evaluator::{
error::Result,
- stdlib::manifest::{JsonFormat, StringFormat, ToStringFormat, YamlFormat, YamlStreamFormat},
- ManifestFormat, State,
+ manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat},
+ State,
};
+use jrsonnet_stdlib::YamlFormat;
use crate::ConfigureState;
crates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -1,6 +1,6 @@
use clap::Parser;
use jrsonnet_evaluator::{
- error::{Error, Result},
+ error::{ErrorKind, Result},
function::TlaArg,
gc::GcHashMap,
IStr, State,
@@ -51,15 +51,15 @@
{
let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
out.insert(
- (&name as &str).into(),
+ (name as &str).into(),
TlaArg::Code(
jrsonnet_parser::parse(
- &code,
+ code,
&ParserSettings {
source: source.clone(),
},
)
- .map_err(|e| Error::ImportSyntaxError {
+ .map_err(|e| ErrorKind::ImportSyntaxError {
path: source,
error: Box::new(e),
})?,
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -4,8 +4,8 @@
use jrsonnet_interner::IStr;
use crate::{
- error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State, Thunk,
- Val,
+ error::ErrorKind::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State,
+ Thunk, Val,
};
#[derive(Trace)]
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -74,7 +74,7 @@
#[allow(missing_docs)]
#[derive(Error, Debug, Clone, Trace)]
#[non_exhaustive]
-pub enum Error {
+pub enum ErrorKind {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -211,14 +211,14 @@
}
#[cfg(feature = "anyhow-error")]
-impl From<anyhow::Error> for LocError {
+impl From<anyhow::Error> for Error {
fn from(e: anyhow::Error) -> Self {
- Self::new(Error::Other(Rc::new(e)))
+ Self::new(ErrorKind::Other(Rc::new(e)))
}
}
-impl From<Error> for LocError {
- fn from(e: Error) -> Self {
+impl From<ErrorKind> for Error {
+ fn from(e: ErrorKind) -> Self {
Self::new(e)
}
}
@@ -236,16 +236,16 @@
pub struct StackTrace(pub Vec<StackTraceElement>);
#[derive(Clone, Trace)]
-pub struct LocError(Box<(Error, StackTrace)>);
-impl LocError {
- pub fn new(e: Error) -> Self {
+pub struct Error(Box<(ErrorKind, StackTrace)>);
+impl Error {
+ pub fn new(e: ErrorKind) -> Self {
Self(Box::new((e, StackTrace(vec![]))))
}
- pub const fn error(&self) -> &Error {
+ pub const fn error(&self) -> &ErrorKind {
&(self.0).0
}
- pub fn error_mut(&mut self) -> &mut Error {
+ pub fn error_mut(&mut self) -> &mut ErrorKind {
&mut (self.0).0
}
pub const fn trace(&self) -> &StackTrace {
@@ -255,7 +255,7 @@
&mut (self.0).1
}
}
-impl Display for LocError {
+impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.0 .0)?;
for el in &self.0 .1 .0 {
@@ -269,7 +269,7 @@
Ok(())
}
}
-impl Debug for LocError {
+impl Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("LocError").field(&self.0).finish()
}
@@ -294,7 +294,7 @@
}
}
-pub type Result<V, E = LocError> = std::result::Result<V, E>;
+pub type Result<V, E = Error> = std::result::Result<V, E>;
pub trait ResultExt: Sized {
#[must_use]
fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;
@@ -314,7 +314,7 @@
self.with_description_src(src, || msg)
}
}
-impl<T> ResultExt for Result<T, LocError> {
+impl<T> ResultExt for Result<T, Error> {
fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {
if let Err(e) = &mut self {
let trace = e.trace_mut();
@@ -348,9 +348,9 @@
return Err($w$(::$i)*$(($($tt)*))?.into())
};
($l:literal) => {
- return Err($crate::error::Error::RuntimeError($l.into()).into())
+ return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())
};
($l:literal, $($tt:tt)*) => {
- return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())
+ return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())
};
}
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -3,7 +3,7 @@
use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
use crate::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
evaluate, evaluate_method, evaluate_named,
gc::GcHashMap,
tb, throw,
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -11,14 +11,14 @@
use self::destructure::destruct;
use crate::{
destructure::evaluate_dest,
- error::Error::*,
+ error::ErrorKind::*,
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
tb, throw,
typed::Typed,
val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},
- Context, GcHashMap, LocError, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
- ResultExt, State, Unbound, Val,
+ Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,
+ Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -165,7 +165,7 @@
uctx: B,
field: &FieldMember,
) -> Result<()> {
- let name = evaluate_field_name(ctx.clone(), &field.name)?;
+ let name = evaluate_field_name(ctx, &field.name)?;
let Some(name) = name else {
return Ok(());
};
@@ -187,11 +187,7 @@
impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
type Bound = Val;
fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
- Ok(evaluate_named(
- self.uctx.bind(sup, this)?,
- &self.value,
- self.name.clone(),
- )?)
+ evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())
}
}
@@ -201,9 +197,9 @@
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(tb!(UnboundValue {
- uctx: uctx.clone(),
+ uctx,
value: value.clone(),
- name: name.clone()
+ name,
}))?;
}
FieldMember {
@@ -236,10 +232,10 @@
.with_visibility(*visibility)
.with_location(value.1.clone())
.bindable(tb!(UnboundMethod {
- uctx: uctx.clone(),
+ uctx,
value: value.clone(),
params: params.clone(),
- name: name.clone()
+ name,
}))?;
}
}
@@ -267,7 +263,7 @@
for member in members.iter() {
match member {
Member::Field(field) => {
- evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?
+ evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;
}
Member::AssertStmt(stmt) => {
#[derive(Trace)]
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,7 +3,7 @@
use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
use crate::{
- error::Error::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
+ error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
Result, Val,
};
crates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -180,8 +180,8 @@
}
}
-impl<A: ArgLike, S> sealed::Named for HashMap<IStr, A, S> {}
-impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {
+impl<V: ArgLike, S> sealed::Named for HashMap<IStr, V, S> {}
+impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {
fn unnamed_len(&self) -> usize {
0
}
@@ -213,7 +213,7 @@
}
}
}
-impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}
+impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}
impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
fn unnamed_len(&self) -> usize {
@@ -239,7 +239,7 @@
}
fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
- self.0.named_names(handler)
+ self.0.named_names(handler);
}
}
crates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -7,7 +7,7 @@
use super::{arglike::ArgsLike, builtin::BuiltinParam};
use crate::{
destructure::destruct,
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
evaluate_named,
gc::GcHashMap,
tb, throw,
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -12,10 +12,7 @@
use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
use crate::{
- error::{
- Error::{self, *},
- Result,
- },
+ error::{ErrorKind::*, Result},
throw,
};
@@ -94,7 +91,7 @@
} else if let Some(d) = from.downcast_ref::<SourceDirectory>() {
d.path().to_owned()
} else if from.is_default() {
- current_dir().map_err(|e| Error::ImportIo(e.to_string()))?
+ current_dir().map_err(|e| ImportIo(e.to_string()))?
} else {
unreachable!("resolver can't return this path")
};
@@ -122,7 +119,7 @@
Err(e) if e.kind() == ErrorKind::NotFound => {
throw!(AbsoluteImportFileNotFound(path.to_owned()))
}
- Err(e) => throw!(Error::ImportIo(e.to_string())),
+ Err(e) => throw!(ImportIo(e.to_string())),
};
if meta.is_file() {
Ok(SourcePath::new(SourceFile::new(
@@ -141,7 +138,7 @@
let path = if let Some(f) = id.downcast_ref::<SourceFile>() {
f.path()
} else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {
- throw!(Error::ImportIsADirectory(id.clone()))
+ throw!(ImportIsADirectory(id.clone()))
} else {
unreachable!("other types are not supported in resolve");
};
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -51,6 +51,7 @@
pub mod gc;
mod import;
mod integrations;
+pub mod manifest;
mod map;
mod obj;
pub mod stack;
@@ -69,7 +70,7 @@
pub use ctx::*;
pub use dynamic::*;
-pub use error::{Error::*, LocError, Result, ResultExt};
+pub use error::{Error, ErrorKind::*, Result, ResultExt};
pub use evaluate::*;
use function::CallLocation;
use gc::{GcHashMap, TraceBox};
@@ -82,7 +83,7 @@
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
-pub use val::{ManifestFormat, Thunk, Val};
+pub use val::{Thunk, Val};
/// Thunk without bound `super`/`this`
/// object inheritance may be overriden multiple times, and will be fixed only on field read
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -11,7 +11,7 @@
use rustc_hash::FxHashMap;
use crate::{
- error::{Error::*, LocError},
+ error::{Error, ErrorKind::*},
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
@@ -115,7 +115,7 @@
Cached(Val),
NotFound,
Pending,
- Errored(LocError),
+ Errored(Error),
}
#[allow(clippy::module_name_repetitions)]
crates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stack.rs
+++ b/crates/jrsonnet-evaluator/src/stack.rs
@@ -1,6 +1,6 @@
use std::{cell::Cell, marker::PhantomData};
-use crate::error::{Error, LocError};
+use crate::error::{Error, ErrorKind};
struct StackLimit {
max_stack_size: Cell<usize>,
@@ -22,14 +22,14 @@
}
pub struct StackOverflowError;
-impl From<StackOverflowError> for Error {
+impl From<StackOverflowError> for ErrorKind {
fn from(_: StackOverflowError) -> Self {
- Error::StackOverflow
+ ErrorKind::StackOverflow
}
}
-impl From<StackOverflowError> for LocError {
+impl From<StackOverflowError> for Error {
fn from(_: StackOverflowError) -> Self {
- Error::StackOverflow.into()
+ ErrorKind::StackOverflow.into()
}
}
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,7 @@
use jrsonnet_types::ValType;
use thiserror::Error;
-use crate::{error::Error::*, throw, typed::Typed, LocError, ObjValue, Result, Val};
+use crate::{error::ErrorKind::*, throw, typed::Typed, Error, ObjValue, Result, Val};
#[derive(Debug, Clone, Error, Trace)]
pub enum FormatError {
@@ -26,7 +26,7 @@
NoSuchFormatField(IStr),
}
-impl From<FormatError> for LocError {
+impl From<FormatError> for Error {
fn from(e: FormatError) -> Self {
Self::new(Format(e))
}
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -7,7 +7,6 @@
use crate::{error::Result, function::CallLocation, State, Val};
pub mod format;
-pub mod manifest;
pub fn std_format(str: IStr, vals: Val) -> Result<String> {
State::push(
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -6,7 +6,7 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{CodeLocation, Source};
-use crate::{error::Error, LocError};
+use crate::{error::ErrorKind, Error};
/// The way paths should be displayed
#[derive(Clone, Trace)]
@@ -51,9 +51,9 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error>;
- fn format(&self, error: &LocError) -> Result<String, std::fmt::Error> {
+ fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {
let mut out = String::new();
self.write_trace(&mut out, error)?;
Ok(out)
@@ -107,10 +107,10 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
- if let Error::ImportSyntaxError { path, error } = error.error() {
+ if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
use std::fmt::Write;
writeln!(out)?;
@@ -204,7 +204,7 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
for item in &error.trace().0 {
@@ -250,10 +250,10 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- error: &LocError,
+ error: &Error,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
- if let Error::ImportSyntaxError { path, error } = error.error() {
+ if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
writeln!(out)?;
let offset = error.location.offset;
let location = path
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -7,7 +7,7 @@
use thiserror::Error;
use crate::{
- error::{Error, LocError, Result},
+ error::{Error, ErrorKind, Result},
State, Val,
};
@@ -26,9 +26,9 @@
)]
BoundsFailed(f64, Option<f64>, Option<f64>),
}
-impl From<TypeError> for LocError {
+impl From<TypeError> for Error {
fn from(e: TypeError) -> Self {
- Error::TypeError(e.into()).into()
+ ErrorKind::TypeError(e.into()).into()
}
}
@@ -39,9 +39,9 @@
Self(Box::new(e), ValuePathStack(Vec::new()))
}
}
-impl From<TypeLocError> for LocError {
+impl From<TypeLocError> for Error {
fn from(e: TypeLocError) -> Self {
- Error::TypeError(e).into()
+ ErrorKind::TypeError(e).into()
}
}
impl Display for TypeLocError {
@@ -92,7 +92,7 @@
State::push_description(error_reason, || match item() {
Ok(_) => Ok(()),
Err(mut e) => {
- if let Error::TypeError(e) = &mut e.error_mut() {
+ if let ErrorKind::TypeError(e) = &mut e.error_mut() {
(e.1).0.push(path());
}
Err(e)
@@ -218,7 +218,7 @@
return Ok(());
}
Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
+ ErrorKind::TypeError(e) => errors.push(e.clone()),
_ => return Err(e),
},
}
@@ -233,7 +233,7 @@
return Ok(());
}
Err(e) => match e.error() {
- Error::TypeError(e) => errors.push(e.clone()),
+ ErrorKind::TypeError(e) => errors.push(e.clone()),
_ => return Err(e),
},
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{cell::RefCell, fmt::Debug};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8 error::{Error::*, LocError},9 function::FuncVal,10 gc::{GcHashMap, TraceBox},11 throw,12 typed::BoundedUsize,13 ObjValue, Result, Unbound, WeakObjValue,14};1516pub trait ThunkValue: Trace {17 type Output;18 fn get(self: Box<Self>) -> Result<Self::Output>;19}2021#[derive(Trace)]22enum ThunkInner<T: Trace> {23 Computed(T),24 Errored(LocError),25 Waiting(TraceBox<dyn ThunkValue<Output = T>>),26 Pending,27}2829#[allow(clippy::module_name_repetitions)]30#[derive(Clone, Trace)]31pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3233impl<T> Thunk<T>34where35 T: Clone + Trace,36{37 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {38 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))39 }40 pub fn evaluated(val: T) -> Self {41 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))42 }43 pub fn force(&self) -> Result<()> {44 self.evaluate()?;45 Ok(())46 }47 pub fn evaluate(&self) -> Result<T> {48 match &*self.0.borrow() {49 ThunkInner::Computed(v) => return Ok(v.clone()),50 ThunkInner::Errored(e) => return Err(e.clone()),51 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),52 ThunkInner::Waiting(..) => (),53 };54 let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {55 unreachable!();56 };57 let new_value = match value.0.get() {58 Ok(v) => v,59 Err(e) => {60 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());61 return Err(e);62 }63 };64 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());65 Ok(new_value)66 }67}6869type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7071#[derive(Trace, Clone)]72pub struct CachedUnbound<I, T>73where74 I: Unbound<Bound = T>,75 T: Trace,76{77 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,78 value: I,79}80impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {81 pub fn new(value: I) -> Self {82 Self {83 cache: Cc::new(RefCell::new(GcHashMap::new())),84 value,85 }86 }87}88impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {89 type Bound = T;90 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {91 let cache_key = (92 sup.as_ref().map(|s| s.clone().downgrade()),93 this.as_ref().map(|t| t.clone().downgrade()),94 );95 {96 if let Some(t) = self.cache.borrow().get(&cache_key) {97 return Ok(t.clone());98 }99 }100 let bound = self.value.bind(sup, this)?;101102 {103 let mut cache = self.cache.borrow_mut();104 cache.insert(cache_key, bound.clone());105 }106107 Ok(bound)108 }109}110111impl<T: Debug + Trace> Debug for Thunk<T> {112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {113 write!(f, "Lazy")114 }115}116impl<T: Trace> PartialEq for Thunk<T> {117 fn eq(&self, other: &Self) -> bool {118 Cc::ptr_eq(&self.0, &other.0)119 }120}121122pub trait ManifestFormat {123 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;124 fn manifest(&self, val: Val) -> Result<String> {125 let mut out = String::new();126 self.manifest_buf(val, &mut out)?;127 Ok(out)128 }129}130impl<T> ManifestFormat for Box<T>131where132 T: ManifestFormat + ?Sized,133{134 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {135 let inner = &**self;136 inner.manifest_buf(val, buf)137 }138}139impl<T> ManifestFormat for &'_ T140where141 T: ManifestFormat + ?Sized,142{143 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {144 let inner = &**self;145 inner.manifest_buf(val, buf)146 }147}148149#[derive(Debug, Clone, Trace)]150pub struct Slice {151 pub(crate) inner: ArrValue,152 pub(crate) from: u32,153 pub(crate) to: u32,154 pub(crate) step: u32,155}156impl Slice {157 const fn from(&self) -> usize {158 self.from as usize159 }160 const fn to(&self) -> usize {161 self.to as usize162 }163 const fn step(&self) -> usize {164 self.step as usize165 }166 const fn len(&self) -> usize {167 // TODO: use div_ceil168 let diff = self.to() - self.from();169 let rem = diff % self.step();170 let div = diff / self.step();171172 if rem == 0 {173 div174 } else {175 div + 1176 }177 }178}179180/// Represents a Jsonnet array value.181#[derive(Debug, Clone, Trace)]182// may contrain other ArrValue183#[trace(tracking(force))]184pub enum ArrValue {185 /// Layout optimized byte array.186 Bytes(#[trace(skip)] IBytes),187 /// Every element is lazy evaluated.188 Lazy(Cc<Vec<Thunk<Val>>>),189 /// Every field is already evaluated.190 Eager(Cc<Vec<Val>>),191 /// Concatenation of two arrays of any kind.192 Extended(Box<(Self, Self)>),193 /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.194 /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.195 Range(i32, i32),196 /// Sliced array view.197 Slice(Box<Slice>),198 /// Reversed array view.199 /// Returned by `std.reverse(other)` call200 Reversed(Box<Self>),201}202203#[cfg(target_pointer_width = "64")]204static_assertions::assert_eq_size!(ArrValue, [u8; 16]);205206impl ArrValue {207 pub fn new_eager() -> Self {208 Self::Eager(Cc::new(Vec::new()))209 }210 pub fn empty() -> Self {211 Self::new_range(0, 0)212 }213214 /// # Panics215 /// If a > b216 #[inline]217 pub fn new_range(a: i32, b: i32) -> Self {218 assert!(a <= b);219 Self::Range(a, b)220 }221222 /// # Panics223 /// If passed numbers are incorrect224 #[must_use]225 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {226 let len = self.len();227 let from = from.unwrap_or(0);228 let to = to.unwrap_or(len).min(len);229 let step = step.unwrap_or(1);230 assert!(from < to);231 assert!(step > 0);232233 Self::Slice(Box::new(Slice {234 inner: self,235 from: from as u32,236 to: to as u32,237 step: step as u32,238 }))239 }240241 /// Array length.242 pub fn len(&self) -> usize {243 match self {244 Self::Bytes(i) => i.len(),245 Self::Lazy(l) => l.len(),246 Self::Eager(e) => e.len(),247 Self::Extended(v) => v.0.len() + v.1.len(),248 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,249 Self::Reversed(i) => i.len(),250 Self::Slice(s) => s.len(),251 }252 }253254 /// Is array contains no elements?255 pub fn is_empty(&self) -> bool {256 self.len() == 0257 }258259 /// Get array element by index, evaluating it, if it is lazy.260 ///261 /// Returns `None` on out-of-bounds condition.262 pub fn get(&self, index: usize) -> Result<Option<Val>> {263 match self {264 Self::Bytes(i) => i265 .get(index)266 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),267 Self::Lazy(vec) => {268 if let Some(v) = vec.get(index) {269 Ok(Some(v.evaluate()?))270 } else {271 Ok(None)272 }273 }274 Self::Eager(vec) => Ok(vec.get(index).cloned()),275 Self::Extended(v) => {276 let a_len = v.0.len();277 if a_len > index {278 v.0.get(index)279 } else {280 v.1.get(index - a_len)281 }282 }283 Self::Range(a, _) => {284 if index >= self.len() {285 return Ok(None);286 }287 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))288 }289 Self::Reversed(v) => {290 let len = v.len();291 if index >= len {292 return Ok(None);293 }294 v.get(len - index - 1)295 }296 Self::Slice(v) => {297 let index = v.from() + index * v.step();298 if index >= v.to() {299 return Ok(None);300 }301 v.inner.get(index)302 }303 }304 }305306 /// Get array element by index, without evaluation.307 ///308 /// Returns `None` on out-of-bounds condition.309 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {310 match self {311 Self::Bytes(i) => i312 .get(index)313 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),314 Self::Lazy(vec) => vec.get(index).cloned(),315 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),316 Self::Extended(v) => {317 let a_len = v.0.len();318 if a_len > index {319 v.0.get_lazy(index)320 } else {321 v.1.get_lazy(index - a_len)322 }323 }324 Self::Range(a, _) => {325 if index >= self.len() {326 return None;327 }328 Some(Thunk::evaluated(Val::Num(329 ((*a as isize) + index as isize) as f64,330 )))331 }332 Self::Reversed(v) => {333 let len = v.len();334 if index >= len {335 return None;336 }337 v.get_lazy(len - index - 1)338 }339 Self::Slice(s) => {340 let index = s.from() + index * s.step();341 if index >= s.to() {342 return None;343 }344 s.inner.get_lazy(index)345 }346 }347 }348349 /// Evaluate all array elements, returning new array.350 pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {351 Ok(match self {352 Self::Bytes(i) => {353 let mut out = Vec::with_capacity(i.len());354 for v in i.iter() {355 out.push(Val::Num(f64::from(*v)));356 }357 Cc::new(out)358 }359 Self::Lazy(vec) => {360 let mut out = Vec::with_capacity(vec.len());361 for item in vec.iter() {362 out.push(item.evaluate()?);363 }364 Cc::new(out)365 }366 Self::Eager(vec) => vec.clone(),367 Self::Extended(_v) => {368 let mut out = Vec::with_capacity(self.len());369 for item in self.iter() {370 out.push(item?);371 }372 Cc::new(out)373 }374 Self::Range(a, b) => {375 let mut out = Vec::with_capacity(self.len());376 for i in *a..*b {377 out.push(Val::Num(f64::from(i)));378 }379 Cc::new(out)380 }381 Self::Reversed(r) => {382 let mut r = r.evaluated()?;383 Cc::update_with(&mut r, |v| v.reverse());384 r385 }386 Self::Slice(v) => {387 let mut out = Vec::with_capacity(v.inner.len());388 for v in v389 .inner390 .iter_lazy()391 .skip(v.from())392 .take(v.to() - v.from())393 .step_by(v.step())394 {395 out.push(v.evaluate()?);396 }397 Cc::new(out)398 }399 })400 }401402 /// Iterate over elements, evaluating them.403 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {404 (0..self.len()).map(move |idx| match self {405 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),406 Self::Lazy(l) => l[idx].evaluate(),407 Self::Eager(e) => Ok(e[idx].clone()),408 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {409 self.get(idx).map(|e| e.expect("idx < len"))410 }411 })412 }413414 /// Iterate over elements, returning lazy values.415 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {416 (0..self.len()).map(move |idx| match self {417 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),418 Self::Lazy(l) => l[idx].clone(),419 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),420 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {421 self.get_lazy(idx).expect("idx < len")422 }423 })424 }425426 /// Return a reversed view on current array.427 #[must_use]428 pub fn reversed(self) -> Self {429 Self::Reversed(Box::new(self))430 }431432 /// Return a new array, produced by passing every element of current array to specified callback function.433 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {434 let mut out = Vec::with_capacity(self.len());435436 for value in self.iter() {437 out.push(mapper(value?)?);438 }439440 Ok(Self::Eager(Cc::new(out)))441 }442443 /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.444 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {445 let mut out = Vec::with_capacity(self.len());446447 for value in self.iter() {448 let value = value?;449 if filter(&value)? {450 out.push(value);451 }452 }453454 Ok(Self::Eager(Cc::new(out)))455 }456457 pub fn ptr_eq(a: &Self, b: &Self) -> bool {458 match (a, b) {459 (Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),460 (Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),461 _ => false,462 }463 }464}465466impl From<Vec<Thunk<Val>>> for ArrValue {467 fn from(v: Vec<Thunk<Val>>) -> Self {468 Self::Lazy(Cc::new(v))469 }470}471472impl From<Vec<Val>> for ArrValue {473 fn from(v: Vec<Val>) -> Self {474 Self::Eager(Cc::new(v))475 }476}477478/// Represents a Jsonnet value, which can be spliced or indexed (string or array).479#[allow(clippy::module_name_repetitions)]480pub enum IndexableVal {481 /// String.482 Str(IStr),483 /// Array.484 Arr(ArrValue),485}486impl IndexableVal {487 /// Slice the value.488 ///489 /// # Implementation490 ///491 /// For strings, will create a copy of specified interval.492 ///493 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.494 pub fn slice(495 self,496 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,497 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,498 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,499 ) -> Result<Self> {500 match &self {501 IndexableVal::Str(s) => {502 let index = index.as_deref().copied().unwrap_or(0);503 let end = end.as_deref().copied().unwrap_or(usize::MAX);504 let step = step.as_deref().copied().unwrap_or(1);505506 if index >= end {507 return Ok(Self::Str("".into()));508 }509510 Ok(Self::Str(511 (s.chars()512 .skip(index)513 .take(end - index)514 .step_by(step)515 .collect::<String>())516 .into(),517 ))518 }519 IndexableVal::Arr(arr) => {520 let index = index.as_deref().copied().unwrap_or(0);521 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());522 let step = step.as_deref().copied().unwrap_or(1);523524 if index >= end {525 return Ok(Self::Arr(ArrValue::new_eager()));526 }527528 Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {529 inner: arr.clone(),530 from: index as u32,531 to: end as u32,532 step: step as u32,533 }))))534 }535 }536 }537}538539/// Represents any valid Jsonnet value.540#[derive(Debug, Clone, Trace)]541pub enum Val {542 /// Represents a Jsonnet boolean.543 Bool(bool),544 /// Represents a Jsonnet null value.545 Null,546 /// Represents a Jsonnet string.547 Str(IStr),548 /// Represents a Jsonnet number.549 /// Should be finite, and not NaN550 /// This restriction isn't enforced by enum, as enum field can't be marked as private551 Num(f64),552 /// Represents a Jsonnet array.553 Arr(ArrValue),554 /// Represents a Jsonnet object.555 Obj(ObjValue),556 /// Represents a Jsonnet function.557 Func(FuncVal),558}559560impl From<IndexableVal> for Val {561 fn from(v: IndexableVal) -> Self {562 match v {563 IndexableVal::Str(s) => Self::Str(s),564 IndexableVal::Arr(a) => Self::Arr(a),565 }566 }567}568569// Broken between stable and nightly, as there is new layout size optimization570// #[cfg(target_pointer_width = "64")]571// static_assertions::assert_eq_size!(Val, [u8; 24]);572573impl Val {574 pub const fn as_bool(&self) -> Option<bool> {575 match self {576 Self::Bool(v) => Some(*v),577 _ => None,578 }579 }580 pub const fn as_null(&self) -> Option<()> {581 match self {582 Self::Null => Some(()),583 _ => None,584 }585 }586 pub fn as_str(&self) -> Option<IStr> {587 match self {588 Self::Str(s) => Some(s.clone()),589 _ => None,590 }591 }592 pub const fn as_num(&self) -> Option<f64> {593 match self {594 Self::Num(n) => Some(*n),595 _ => None,596 }597 }598 pub fn as_arr(&self) -> Option<ArrValue> {599 match self {600 Self::Arr(a) => Some(a.clone()),601 _ => None,602 }603 }604 pub fn as_obj(&self) -> Option<ObjValue> {605 match self {606 Self::Obj(o) => Some(o.clone()),607 _ => None,608 }609 }610 pub fn as_func(&self) -> Option<FuncVal> {611 match self {612 Self::Func(f) => Some(f.clone()),613 _ => None,614 }615 }616617 /// Creates `Val::Num` after checking for numeric overflow.618 /// As numbers are `f64`, we can just check for their finity.619 pub fn new_checked_num(num: f64) -> Result<Self> {620 if num.is_finite() {621 Ok(Self::Num(num))622 } else {623 throw!("overflow")624 }625 }626627 pub const fn value_type(&self) -> ValType {628 match self {629 Self::Str(..) => ValType::Str,630 Self::Num(..) => ValType::Num,631 Self::Arr(..) => ValType::Arr,632 Self::Obj(..) => ValType::Obj,633 Self::Bool(_) => ValType::Bool,634 Self::Null => ValType::Null,635 Self::Func(..) => ValType::Func,636 }637 }638639 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {640 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {641 manifest.manifest(val.clone())642 }643 manifest_dyn(self, &format)644 }645646 pub fn to_string(&self) -> Result<IStr> {647 Ok(match self {648 Self::Bool(true) => "true".into(),649 Self::Bool(false) => "false".into(),650 Self::Null => "null".into(),651 Self::Str(s) => s.clone(),652 _ => self653 .manifest(crate::stdlib::manifest::ToStringFormat)654 .map(IStr::from)?,655 })656 }657658 pub fn into_indexable(self) -> Result<IndexableVal> {659 Ok(match self {660 Val::Str(s) => IndexableVal::Str(s),661 Val::Arr(arr) => IndexableVal::Arr(arr),662 _ => throw!(ValueIsNotIndexable(self.value_type())),663 })664 }665}666667const fn is_function_like(val: &Val) -> bool {668 matches!(val, Val::Func(_))669}670671/// Native implementation of `std.primitiveEquals`672pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {673 Ok(match (val_a, val_b) {674 (Val::Bool(a), Val::Bool(b)) => a == b,675 (Val::Null, Val::Null) => true,676 (Val::Str(a), Val::Str(b)) => a == b,677 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,678 (Val::Arr(_), Val::Arr(_)) => {679 throw!("primitiveEquals operates on primitive types, got array")680 }681 (Val::Obj(_), Val::Obj(_)) => {682 throw!("primitiveEquals operates on primitive types, got object")683 }684 (a, b) if is_function_like(a) && is_function_like(b) => {685 throw!("cannot test equality of functions")686 }687 (_, _) => false,688 })689}690691/// Native implementation of `std.equals`692pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {693 if val_a.value_type() != val_b.value_type() {694 return Ok(false);695 }696 match (val_a, val_b) {697 (Val::Arr(a), Val::Arr(b)) => {698 if ArrValue::ptr_eq(a, b) {699 return Ok(true);700 }701 if a.len() != b.len() {702 return Ok(false);703 }704 for (a, b) in a.iter().zip(b.iter()) {705 if !equals(&a?, &b?)? {706 return Ok(false);707 }708 }709 Ok(true)710 }711 (Val::Obj(a), Val::Obj(b)) => {712 if ObjValue::ptr_eq(a, b) {713 return Ok(true);714 }715 let fields = a.fields(716 #[cfg(feature = "exp-preserve-order")]717 false,718 );719 if fields720 != b.fields(721 #[cfg(feature = "exp-preserve-order")]722 false,723 ) {724 return Ok(false);725 }726 for field in fields {727 if !equals(728 &a.get(field.clone())?.expect("field exists"),729 &b.get(field)?.expect("field exists"),730 )? {731 return Ok(false);732 }733 }734 Ok(true)735 }736 (a, b) => Ok(primitive_equals(a, b)?),737 }738}1use std::{cell::RefCell, fmt::Debug};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8 error::{Error, ErrorKind::*},9 function::FuncVal,10 gc::{GcHashMap, TraceBox},11 manifest::{ManifestFormat, ToStringFormat},12 throw,13 typed::BoundedUsize,14 ObjValue, Result, Unbound, WeakObjValue,15};1617pub trait ThunkValue: Trace {18 type Output;19 fn get(self: Box<Self>) -> Result<Self::Output>;20}2122#[derive(Trace)]23enum ThunkInner<T: Trace> {24 Computed(T),25 Errored(Error),26 Waiting(TraceBox<dyn ThunkValue<Output = T>>),27 Pending,28}2930#[allow(clippy::module_name_repetitions)]31#[derive(Clone, Trace)]32pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3334impl<T> Thunk<T>35where36 T: Clone + Trace,37{38 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {39 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))40 }41 pub fn evaluated(val: T) -> Self {42 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))43 }44 pub fn force(&self) -> Result<()> {45 self.evaluate()?;46 Ok(())47 }48 pub fn evaluate(&self) -> Result<T> {49 match &*self.0.borrow() {50 ThunkInner::Computed(v) => return Ok(v.clone()),51 ThunkInner::Errored(e) => return Err(e.clone()),52 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),53 ThunkInner::Waiting(..) => (),54 };55 let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {56 unreachable!();57 };58 let new_value = match value.0.get() {59 Ok(v) => v,60 Err(e) => {61 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());62 return Err(e);63 }64 };65 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());66 Ok(new_value)67 }68}6970type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7172#[derive(Trace, Clone)]73pub struct CachedUnbound<I, T>74where75 I: Unbound<Bound = T>,76 T: Trace,77{78 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,79 value: I,80}81impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {82 pub fn new(value: I) -> Self {83 Self {84 cache: Cc::new(RefCell::new(GcHashMap::new())),85 value,86 }87 }88}89impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {90 type Bound = T;91 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {92 let cache_key = (93 sup.as_ref().map(|s| s.clone().downgrade()),94 this.as_ref().map(|t| t.clone().downgrade()),95 );96 {97 if let Some(t) = self.cache.borrow().get(&cache_key) {98 return Ok(t.clone());99 }100 }101 let bound = self.value.bind(sup, this)?;102103 {104 let mut cache = self.cache.borrow_mut();105 cache.insert(cache_key, bound.clone());106 }107108 Ok(bound)109 }110}111112impl<T: Debug + Trace> Debug for Thunk<T> {113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {114 write!(f, "Lazy")115 }116}117impl<T: Trace> PartialEq for Thunk<T> {118 fn eq(&self, other: &Self) -> bool {119 Cc::ptr_eq(&self.0, &other.0)120 }121}122123#[derive(Debug, Clone, Trace)]124pub struct Slice {125 pub(crate) inner: ArrValue,126 pub(crate) from: u32,127 pub(crate) to: u32,128 pub(crate) step: u32,129}130impl Slice {131 const fn from(&self) -> usize {132 self.from as usize133 }134 const fn to(&self) -> usize {135 self.to as usize136 }137 const fn step(&self) -> usize {138 self.step as usize139 }140 const fn len(&self) -> usize {141 // TODO: use div_ceil142 let diff = self.to() - self.from();143 let rem = diff % self.step();144 let div = diff / self.step();145146 if rem == 0 {147 div148 } else {149 div + 1150 }151 }152}153154/// Represents a Jsonnet array value.155#[derive(Debug, Clone, Trace)]156// may contrain other ArrValue157#[trace(tracking(force))]158pub enum ArrValue {159 /// Layout optimized byte array.160 Bytes(#[trace(skip)] IBytes),161 /// Every element is lazy evaluated.162 Lazy(Cc<Vec<Thunk<Val>>>),163 /// Every field is already evaluated.164 Eager(Cc<Vec<Val>>),165 /// Concatenation of two arrays of any kind.166 Extended(Box<(Self, Self)>),167 /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.168 /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.169 Range(i32, i32),170 /// Sliced array view.171 Slice(Box<Slice>),172 /// Reversed array view.173 /// Returned by `std.reverse(other)` call174 Reversed(Box<Self>),175}176177#[cfg(target_pointer_width = "64")]178static_assertions::assert_eq_size!(ArrValue, [u8; 16]);179180impl ArrValue {181 pub fn new_eager() -> Self {182 Self::Eager(Cc::new(Vec::new()))183 }184 pub fn empty() -> Self {185 Self::new_range(0, 0)186 }187188 /// # Panics189 /// If a > b190 #[inline]191 pub fn new_range(a: i32, b: i32) -> Self {192 assert!(a <= b);193 Self::Range(a, b)194 }195196 /// # Panics197 /// If passed numbers are incorrect198 #[must_use]199 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {200 let len = self.len();201 let from = from.unwrap_or(0);202 let to = to.unwrap_or(len).min(len);203 let step = step.unwrap_or(1);204 assert!(from < to);205 assert!(step > 0);206207 Self::Slice(Box::new(Slice {208 inner: self,209 from: from as u32,210 to: to as u32,211 step: step as u32,212 }))213 }214215 /// Array length.216 pub fn len(&self) -> usize {217 match self {218 Self::Bytes(i) => i.len(),219 Self::Lazy(l) => l.len(),220 Self::Eager(e) => e.len(),221 Self::Extended(v) => v.0.len() + v.1.len(),222 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,223 Self::Reversed(i) => i.len(),224 Self::Slice(s) => s.len(),225 }226 }227228 /// Is array contains no elements?229 pub fn is_empty(&self) -> bool {230 self.len() == 0231 }232233 /// Get array element by index, evaluating it, if it is lazy.234 ///235 /// Returns `None` on out-of-bounds condition.236 pub fn get(&self, index: usize) -> Result<Option<Val>> {237 match self {238 Self::Bytes(i) => i239 .get(index)240 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),241 Self::Lazy(vec) => {242 if let Some(v) = vec.get(index) {243 Ok(Some(v.evaluate()?))244 } else {245 Ok(None)246 }247 }248 Self::Eager(vec) => Ok(vec.get(index).cloned()),249 Self::Extended(v) => {250 let a_len = v.0.len();251 if a_len > index {252 v.0.get(index)253 } else {254 v.1.get(index - a_len)255 }256 }257 Self::Range(a, _) => {258 if index >= self.len() {259 return Ok(None);260 }261 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))262 }263 Self::Reversed(v) => {264 let len = v.len();265 if index >= len {266 return Ok(None);267 }268 v.get(len - index - 1)269 }270 Self::Slice(v) => {271 let index = v.from() + index * v.step();272 if index >= v.to() {273 return Ok(None);274 }275 v.inner.get(index)276 }277 }278 }279280 /// Get array element by index, without evaluation.281 ///282 /// Returns `None` on out-of-bounds condition.283 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {284 match self {285 Self::Bytes(i) => i286 .get(index)287 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),288 Self::Lazy(vec) => vec.get(index).cloned(),289 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),290 Self::Extended(v) => {291 let a_len = v.0.len();292 if a_len > index {293 v.0.get_lazy(index)294 } else {295 v.1.get_lazy(index - a_len)296 }297 }298 Self::Range(a, _) => {299 if index >= self.len() {300 return None;301 }302 Some(Thunk::evaluated(Val::Num(303 ((*a as isize) + index as isize) as f64,304 )))305 }306 Self::Reversed(v) => {307 let len = v.len();308 if index >= len {309 return None;310 }311 v.get_lazy(len - index - 1)312 }313 Self::Slice(s) => {314 let index = s.from() + index * s.step();315 if index >= s.to() {316 return None;317 }318 s.inner.get_lazy(index)319 }320 }321 }322323 /// Evaluate all array elements, returning new array.324 pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {325 Ok(match self {326 Self::Bytes(i) => {327 let mut out = Vec::with_capacity(i.len());328 for v in i.iter() {329 out.push(Val::Num(f64::from(*v)));330 }331 Cc::new(out)332 }333 Self::Lazy(vec) => {334 let mut out = Vec::with_capacity(vec.len());335 for item in vec.iter() {336 out.push(item.evaluate()?);337 }338 Cc::new(out)339 }340 Self::Eager(vec) => vec.clone(),341 Self::Extended(_v) => {342 let mut out = Vec::with_capacity(self.len());343 for item in self.iter() {344 out.push(item?);345 }346 Cc::new(out)347 }348 Self::Range(a, b) => {349 let mut out = Vec::with_capacity(self.len());350 for i in *a..*b {351 out.push(Val::Num(f64::from(i)));352 }353 Cc::new(out)354 }355 Self::Reversed(r) => {356 let mut r = r.evaluated()?;357 Cc::update_with(&mut r, |v| v.reverse());358 r359 }360 Self::Slice(v) => {361 let mut out = Vec::with_capacity(v.inner.len());362 for v in v363 .inner364 .iter_lazy()365 .skip(v.from())366 .take(v.to() - v.from())367 .step_by(v.step())368 {369 out.push(v.evaluate()?);370 }371 Cc::new(out)372 }373 })374 }375376 /// Iterate over elements, evaluating them.377 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {378 (0..self.len()).map(move |idx| match self {379 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),380 Self::Lazy(l) => l[idx].evaluate(),381 Self::Eager(e) => Ok(e[idx].clone()),382 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {383 self.get(idx).map(|e| e.expect("idx < len"))384 }385 })386 }387388 /// Iterate over elements, returning lazy values.389 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {390 (0..self.len()).map(move |idx| match self {391 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),392 Self::Lazy(l) => l[idx].clone(),393 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),394 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {395 self.get_lazy(idx).expect("idx < len")396 }397 })398 }399400 /// Return a reversed view on current array.401 #[must_use]402 pub fn reversed(self) -> Self {403 Self::Reversed(Box::new(self))404 }405406 /// Return a new array, produced by passing every element of current array to specified callback function.407 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {408 let mut out = Vec::with_capacity(self.len());409410 for value in self.iter() {411 out.push(mapper(value?)?);412 }413414 Ok(Self::Eager(Cc::new(out)))415 }416417 /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.418 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {419 let mut out = Vec::with_capacity(self.len());420421 for value in self.iter() {422 let value = value?;423 if filter(&value)? {424 out.push(value);425 }426 }427428 Ok(Self::Eager(Cc::new(out)))429 }430431 pub fn ptr_eq(a: &Self, b: &Self) -> bool {432 match (a, b) {433 (Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),434 (Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),435 _ => false,436 }437 }438}439440impl From<Vec<Thunk<Val>>> for ArrValue {441 fn from(v: Vec<Thunk<Val>>) -> Self {442 Self::Lazy(Cc::new(v))443 }444}445446impl From<Vec<Val>> for ArrValue {447 fn from(v: Vec<Val>) -> Self {448 Self::Eager(Cc::new(v))449 }450}451452/// Represents a Jsonnet value, which can be spliced or indexed (string or array).453#[allow(clippy::module_name_repetitions)]454pub enum IndexableVal {455 /// String.456 Str(IStr),457 /// Array.458 Arr(ArrValue),459}460impl IndexableVal {461 /// Slice the value.462 ///463 /// # Implementation464 ///465 /// For strings, will create a copy of specified interval.466 ///467 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.468 pub fn slice(469 self,470 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,471 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,472 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,473 ) -> Result<Self> {474 match &self {475 IndexableVal::Str(s) => {476 let index = index.as_deref().copied().unwrap_or(0);477 let end = end.as_deref().copied().unwrap_or(usize::MAX);478 let step = step.as_deref().copied().unwrap_or(1);479480 if index >= end {481 return Ok(Self::Str("".into()));482 }483484 Ok(Self::Str(485 (s.chars()486 .skip(index)487 .take(end - index)488 .step_by(step)489 .collect::<String>())490 .into(),491 ))492 }493 IndexableVal::Arr(arr) => {494 let index = index.as_deref().copied().unwrap_or(0);495 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());496 let step = step.as_deref().copied().unwrap_or(1);497498 if index >= end {499 return Ok(Self::Arr(ArrValue::new_eager()));500 }501502 Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {503 inner: arr.clone(),504 from: index as u32,505 to: end as u32,506 step: step as u32,507 }))))508 }509 }510 }511}512513/// Represents any valid Jsonnet value.514#[derive(Debug, Clone, Trace)]515pub enum Val {516 /// Represents a Jsonnet boolean.517 Bool(bool),518 /// Represents a Jsonnet null value.519 Null,520 /// Represents a Jsonnet string.521 Str(IStr),522 /// Represents a Jsonnet number.523 /// Should be finite, and not NaN524 /// This restriction isn't enforced by enum, as enum field can't be marked as private525 Num(f64),526 /// Represents a Jsonnet array.527 Arr(ArrValue),528 /// Represents a Jsonnet object.529 Obj(ObjValue),530 /// Represents a Jsonnet function.531 Func(FuncVal),532}533534impl From<IndexableVal> for Val {535 fn from(v: IndexableVal) -> Self {536 match v {537 IndexableVal::Str(s) => Self::Str(s),538 IndexableVal::Arr(a) => Self::Arr(a),539 }540 }541}542543// Broken between stable and nightly, as there is new layout size optimization544// #[cfg(target_pointer_width = "64")]545// static_assertions::assert_eq_size!(Val, [u8; 24]);546547impl Val {548 pub const fn as_bool(&self) -> Option<bool> {549 match self {550 Self::Bool(v) => Some(*v),551 _ => None,552 }553 }554 pub const fn as_null(&self) -> Option<()> {555 match self {556 Self::Null => Some(()),557 _ => None,558 }559 }560 pub fn as_str(&self) -> Option<IStr> {561 match self {562 Self::Str(s) => Some(s.clone()),563 _ => None,564 }565 }566 pub const fn as_num(&self) -> Option<f64> {567 match self {568 Self::Num(n) => Some(*n),569 _ => None,570 }571 }572 pub fn as_arr(&self) -> Option<ArrValue> {573 match self {574 Self::Arr(a) => Some(a.clone()),575 _ => None,576 }577 }578 pub fn as_obj(&self) -> Option<ObjValue> {579 match self {580 Self::Obj(o) => Some(o.clone()),581 _ => None,582 }583 }584 pub fn as_func(&self) -> Option<FuncVal> {585 match self {586 Self::Func(f) => Some(f.clone()),587 _ => None,588 }589 }590591 /// Creates `Val::Num` after checking for numeric overflow.592 /// As numbers are `f64`, we can just check for their finity.593 pub fn new_checked_num(num: f64) -> Result<Self> {594 if num.is_finite() {595 Ok(Self::Num(num))596 } else {597 throw!("overflow")598 }599 }600601 pub const fn value_type(&self) -> ValType {602 match self {603 Self::Str(..) => ValType::Str,604 Self::Num(..) => ValType::Num,605 Self::Arr(..) => ValType::Arr,606 Self::Obj(..) => ValType::Obj,607 Self::Bool(_) => ValType::Bool,608 Self::Null => ValType::Null,609 Self::Func(..) => ValType::Func,610 }611 }612613 pub fn manifest(&self, format: impl ManifestFormat) -> Result<String> {614 fn manifest_dyn(val: &Val, manifest: &dyn ManifestFormat) -> Result<String> {615 manifest.manifest(val.clone())616 }617 manifest_dyn(self, &format)618 }619620 pub fn to_string(&self) -> Result<IStr> {621 Ok(match self {622 Self::Bool(true) => "true".into(),623 Self::Bool(false) => "false".into(),624 Self::Null => "null".into(),625 Self::Str(s) => s.clone(),626 _ => self.manifest(ToStringFormat).map(IStr::from)?,627 })628 }629630 pub fn into_indexable(self) -> Result<IndexableVal> {631 Ok(match self {632 Val::Str(s) => IndexableVal::Str(s),633 Val::Arr(arr) => IndexableVal::Arr(arr),634 _ => throw!(ValueIsNotIndexable(self.value_type())),635 })636 }637}638639const fn is_function_like(val: &Val) -> bool {640 matches!(val, Val::Func(_))641}642643/// Native implementation of `std.primitiveEquals`644pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {645 Ok(match (val_a, val_b) {646 (Val::Bool(a), Val::Bool(b)) => a == b,647 (Val::Null, Val::Null) => true,648 (Val::Str(a), Val::Str(b)) => a == b,649 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,650 (Val::Arr(_), Val::Arr(_)) => {651 throw!("primitiveEquals operates on primitive types, got array")652 }653 (Val::Obj(_), Val::Obj(_)) => {654 throw!("primitiveEquals operates on primitive types, got object")655 }656 (a, b) if is_function_like(a) && is_function_like(b) => {657 throw!("cannot test equality of functions")658 }659 (_, _) => false,660 })661}662663/// Native implementation of `std.equals`664pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {665 if val_a.value_type() != val_b.value_type() {666 return Ok(false);667 }668 match (val_a, val_b) {669 (Val::Arr(a), Val::Arr(b)) => {670 if ArrValue::ptr_eq(a, b) {671 return Ok(true);672 }673 if a.len() != b.len() {674 return Ok(false);675 }676 for (a, b) in a.iter().zip(b.iter()) {677 if !equals(&a?, &b?)? {678 return Ok(false);679 }680 }681 Ok(true)682 }683 (Val::Obj(a), Val::Obj(b)) => {684 if ObjValue::ptr_eq(a, b) {685 return Ok(true);686 }687 let fields = a.fields(688 #[cfg(feature = "exp-preserve-order")]689 false,690 );691 if fields692 != b.fields(693 #[cfg(feature = "exp-preserve-order")]694 false,695 ) {696 return Ok(false);697 }698 for field in fields {699 if !equals(700 &a.get(field.clone())?.expect("field exists"),701 &b.get(field)?.expect("field exists"),702 )? {703 return Ok(false);704 }705 }706 Ok(true)707 }708 (a, b) => Ok(primitive_equals(a, b)?),709 }710}crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -540,7 +540,7 @@
}
} else {
quote! {
- <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| Error::NoSuchField(#name.into(), vec![]))?)?
+ <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?
}
};
@@ -638,19 +638,19 @@
use ::jrsonnet_evaluator::{
typed::{ComplexValType, Typed, TypedObj, CheckType},
Val, State,
- error::{LocError, Error, Result},
+ error::{ErrorKind, Result as JrResult},
ObjValueBuilder, ObjValue,
};
#typed
impl TypedObj for #ident {
- fn serialize(self, out: &mut ObjValueBuilder) -> Result<(), LocError> {
+ fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {
#(#fields_serialize)*
Ok(())
}
- fn parse(obj: &ObjValue) -> Result<Self, LocError> {
+ fn parse(obj: &ObjValue) -> JrResult<Self> {
Ok(Self {
#(#fields_parse)*
})
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -450,15 +450,23 @@
fn imports() {
assert_eq!(
parse!("import \"hello\""),
- el!(Expr::Import("hello".into()), 0, 14),
+ el!(Expr::Import(el!(Expr::Str("hello".into()), 7, 14)), 0, 14),
);
assert_eq!(
parse!("importstr \"garnish.txt\""),
- el!(Expr::ImportStr("garnish.txt".into()), 0, 23)
+ el!(
+ Expr::ImportStr(el!(Expr::Str("garnish.txt".into()), 10, 23)),
+ 0,
+ 23
+ )
);
assert_eq!(
parse!("importbin \"garnish.bin\""),
- el!(Expr::ImportBin("garnish.bin".into()), 0, 23)
+ el!(
+ Expr::ImportBin(el!(Expr::Str("garnish.bin".into()), 10, 23)),
+ 0,
+ 23
+ )
);
}
crates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-stdlib/Cargo.toml
+++ b/crates/jrsonnet-stdlib/Cargo.toml
@@ -7,7 +7,7 @@
edition = "2021"
[features]
-default = ["codegenerated-stdlib"]
+default = ["codegenerated-stdlib", "exp-more-hashes"]
# Speed-up initialization by generating code for parsed stdlib, instead
# of invoking parser for it
codegenerated-stdlib = ["jrsonnet-parser/structdump"]
@@ -15,6 +15,7 @@
legacy-this-file = []
# Add order preservation flag to some functions
exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
+exp-more-hashes = ["sha2"]
[dependencies]
jrsonnet-evaluator.workspace = true
@@ -36,6 +37,8 @@
# std.parseYaml, custom library fork is used for C++/golang compatibility
serde_yaml_with_quirks = "0.8.24"
+sha2 = { version = "0.10.6", optional = true }
+
[build-dependencies]
jrsonnet-parser.workspace = true
structdump = { version = "0.2.0", features = ["derive"] }
crates/jrsonnet-stdlib/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/build.rs
+++ b/crates/jrsonnet-stdlib/build.rs
@@ -19,7 +19,7 @@
{
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("stdlib.rs");
- let mut f = File::create(&dest_path).unwrap();
+ let mut f = File::create(dest_path).unwrap();
f.write_all(
("#[allow(clippy::redundant_clone)]".to_owned() + &v.to_string())
.replace(';', ";\n")
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::RuntimeError, Result},
+ error::{ErrorKind::RuntimeError, Result},
function::builtin,
typed::{Either, Either2},
IBytes, IStr,
crates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -4,3 +4,10 @@
pub fn builtin_md5(str: IStr) -> Result<String> {
Ok(format!("{:x}", md5::compute(str.as_bytes())))
}
+
+#[cfg(feature = "exp-more-hashes")]
+#[builtin]
+pub fn builtin_sha256(str: IStr) -> Result<String> {
+ use sha2::digest::Digest;
+ Ok(format!("{:?}", sha2::Sha256::digest(str.as_bytes())))
+}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -5,7 +5,7 @@
};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},
gc::{GcHashMap, TraceBox},
tb,
@@ -101,6 +101,8 @@
("sort", builtin_sort::INST),
// Hash
("md5", builtin_md5::INST),
+ #[cfg(feature = "exp-more-hashes")]
+ ("sha256", builtin_sha256::INST),
// Encoding
("encodeUTF8", builtin_encode_utf8::INST),
("decodeUTF8", builtin_decode_utf8::INST),
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -1,7 +1,7 @@
use std::{cell::RefCell, rc::Rc};
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::{builtin, ArgLike, CallLocation, FuncVal},
throw,
typed::{Any, Either2, Either4},
crates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::RuntimeError, Result},
+ error::{ErrorKind::RuntimeError, Result},
function::builtin,
typed::Any,
IStr, Val,
crates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/strings.rs
+++ b/crates/jrsonnet-stdlib/src/strings.rs
@@ -1,5 +1,5 @@
use jrsonnet_evaluator::{
- error::{Error::*, Result},
+ error::{ErrorKind::*, Result},
function::builtin,
typed::{Either2, VecVal, M1},
val::ArrValue,
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -29,7 +29,7 @@
macro_rules! ensure_val_eq {
($a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {
- use ::jrsonnet_evaluator::stdlib::manifest::JsonFormat;
+ use ::jrsonnet_evaluator::manifest::JsonFormat;
::jrsonnet_evaluator::throw!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
$a.manifest(JsonFormat::default())?,
tests/tests/golden.rsdiffbeforeafterboth--- a/tests/tests/golden.rs
+++ b/tests/tests/golden.rs
@@ -4,7 +4,7 @@
};
use jrsonnet_evaluator::{
- stdlib::manifest::JsonFormat,
+ manifest::JsonFormat,
trace::{CompactFormat, PathResolver, TraceFormat},
FileImportResolver, State,
};