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.rsdiffbeforeafterboth1//! jsonnet interpreter implementation2#![cfg_attr(feature = "nightly", feature(thread_local))]3#![deny(unsafe_op_in_unsafe_fn)]4#![warn(5 clippy::all,6 clippy::nursery,7 clippy::pedantic,8 // missing_docs,9 elided_lifetimes_in_paths,10 explicit_outlives_requirements,11 noop_method_call,12 single_use_lifetimes,13 variant_size_differences,14 rustdoc::all15)]16#![allow(17 macro_expanded_macro_exports_accessed_by_absolute_paths,18 clippy::ptr_arg,19 // Too verbose20 clippy::must_use_candidate,21 // A lot of functions pass around errors thrown by code22 clippy::missing_errors_doc,23 // A lot of pointers have interior Rc24 clippy::needless_pass_by_value,25 // Its fine26 clippy::wildcard_imports,27 clippy::enum_glob_use,28 clippy::module_name_repetitions,29 // TODO: fix individual issues, however this works as intended almost everywhere30 clippy::cast_precision_loss,31 clippy::cast_possible_wrap,32 clippy::cast_possible_truncation,33 clippy::cast_sign_loss,34 // False positives35 // https://github.com/rust-lang/rust-clippy/issues/690236 clippy::use_self,37 // https://github.com/rust-lang/rust-clippy/issues/853938 clippy::iter_with_drain,39 // ci is being run with nightly, but library should work on stable40 clippy::missing_const_for_fn,41)]4243// For jrsonnet-macros44extern crate self as jrsonnet_evaluator;4546mod ctx;47mod dynamic;48pub mod error;49mod evaluate;50pub mod function;51pub mod gc;52mod import;53mod integrations;54mod map;55mod obj;56pub mod stack;57pub mod stdlib;58mod tla;59pub mod trace;60pub mod typed;61pub mod val;6263use std::{64 any::Any,65 cell::{Ref, RefCell, RefMut},66 fmt::{self, Debug},67 path::Path,68};6970pub use ctx::*;71pub use dynamic::*;72pub use error::{Error::*, LocError, Result, ResultExt};73pub use evaluate::*;74use function::CallLocation;75use gc::{GcHashMap, TraceBox};76use hashbrown::hash_map::RawEntryMut;77pub use import::*;78use jrsonnet_gcmodule::{Cc, Trace};79pub use jrsonnet_interner::{IBytes, IStr};80pub use jrsonnet_parser as parser;81use jrsonnet_parser::*;82pub use obj::*;83use stack::check_depth;84pub use tla::apply_tla;85pub use val::{ManifestFormat, Thunk, Val};8687/// Thunk without bound `super`/`this`88/// object inheritance may be overriden multiple times, and will be fixed only on field read89pub trait Unbound: Trace {90 /// Type of value after object context is bound91 type Bound;92 /// Create value bound to specified object context93 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;94}9596/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code97/// Standard jsonnet fields are always unbound98#[derive(Clone, Trace)]99pub enum MaybeUnbound {100 /// Value needs to be bound to `this`/`super`101 Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),102 /// Value is object-independent103 Bound(Thunk<Val>),104}105106impl Debug for MaybeUnbound {107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {108 write!(f, "MaybeUnbound")109 }110}111impl MaybeUnbound {112 /// Attach object context to value, if required113 pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {114 match self {115 Self::Unbound(v) => v.bind(sup, this),116 Self::Bound(v) => Ok(v.evaluate()?),117 }118 }119}120121/// During import, this trait will be called to create initial context for file.122/// It may initialize global variables, stdlib for example.123pub trait ContextInitializer: Trace {124 /// Initialize default file context.125 fn initialize(&self, state: State, for_file: Source) -> Context;126 /// Allows upcasting from abstract to concrete context initializer.127 /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.128 fn as_any(&self) -> &dyn Any;129}130131/// Context initializer which adds nothing.132#[derive(Trace)]133pub struct DummyContextInitializer;134impl ContextInitializer for DummyContextInitializer {135 fn initialize(&self, state: State, _for_file: Source) -> Context {136 ContextBuilder::new(state).build()137 }138 fn as_any(&self) -> &dyn Any {139 self140 }141}142143/// Dynamically reconfigurable evaluation settings144#[derive(Trace)]145pub struct EvaluationSettings {146 /// Context initializer, which will be used for imports and everything147 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`148 pub context_initializer: TraceBox<dyn ContextInitializer>,149 /// Used to resolve file locations/contents150 pub import_resolver: TraceBox<dyn ImportResolver>,151}152impl Default for EvaluationSettings {153 fn default() -> Self {154 Self {155 context_initializer: tb!(DummyContextInitializer),156 import_resolver: tb!(DummyImportResolver),157 }158 }159}160161#[derive(Trace)]162struct FileData {163 string: Option<IStr>,164 bytes: Option<IBytes>,165 parsed: Option<LocExpr>,166 evaluated: Option<Val>,167168 evaluating: bool,169}170impl FileData {171 fn new_string(data: IStr) -> Self {172 Self {173 string: Some(data),174 bytes: None,175 parsed: None,176 evaluated: None,177 evaluating: false,178 }179 }180 fn new_bytes(data: IBytes) -> Self {181 Self {182 string: None,183 bytes: Some(data),184 parsed: None,185 evaluated: None,186 evaluating: false,187 }188 }189}190191#[derive(Default, Trace)]192pub struct EvaluationStateInternals {193 /// Internal state194 file_cache: RefCell<GcHashMap<SourcePath, FileData>>,195 /// Settings, safe to change at runtime196 settings: RefCell<EvaluationSettings>,197}198199/// Maintains stack trace and import resolution200#[derive(Default, Clone, Trace)]201pub struct State(Cc<EvaluationStateInternals>);202203impl State {204 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise205 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {206 let mut file_cache = self.file_cache();207 let mut file = file_cache.raw_entry_mut().from_key(&path);208209 let file = match file {210 RawEntryMut::Occupied(ref mut d) => d.get_mut(),211 RawEntryMut::Vacant(v) => {212 let data = self.settings().import_resolver.load_file_contents(&path)?;213 v.insert(214 path.clone(),215 FileData::new_string(216 std::str::from_utf8(&data)217 .map_err(|_| ImportBadFileUtf8(path.clone()))?218 .into(),219 ),220 )221 .1222 }223 };224 if let Some(str) = &file.string {225 return Ok(str.clone());226 }227 if file.string.is_none() {228 file.string = Some(229 file.bytes230 .as_ref()231 .expect("either string or bytes should be set")232 .clone()233 .cast_str()234 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?,235 );236 }237 Ok(file.string.as_ref().expect("just set").clone())238 }239 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise240 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {241 let mut file_cache = self.file_cache();242 let mut file = file_cache.raw_entry_mut().from_key(&path);243244 let file = match file {245 RawEntryMut::Occupied(ref mut d) => d.get_mut(),246 RawEntryMut::Vacant(v) => {247 let data = self.settings().import_resolver.load_file_contents(&path)?;248 v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))249 .1250 }251 };252 if let Some(str) = &file.bytes {253 return Ok(str.clone());254 }255 if file.bytes.is_none() {256 file.bytes = Some(257 file.string258 .as_ref()259 .expect("either string or bytes should be set")260 .clone()261 .cast_bytes(),262 );263 }264 Ok(file.bytes.as_ref().expect("just set").clone())265 }266 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise267 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {268 let mut file_cache = self.file_cache();269 let mut file = file_cache.raw_entry_mut().from_key(&path);270271 let file = match file {272 RawEntryMut::Occupied(ref mut d) => d.get_mut(),273 RawEntryMut::Vacant(v) => {274 let data = self.settings().import_resolver.load_file_contents(&path)?;275 v.insert(276 path.clone(),277 FileData::new_string(278 std::str::from_utf8(&data)279 .map_err(|_| ImportBadFileUtf8(path.clone()))?280 .into(),281 ),282 )283 .1284 }285 };286 if let Some(val) = &file.evaluated {287 return Ok(val.clone());288 }289 if file.string.is_none() {290 file.string = Some(291 std::str::from_utf8(292 file.bytes293 .as_ref()294 .expect("either string or bytes should be set"),295 )296 .map_err(|_| ImportBadFileUtf8(path.clone()))?297 .into(),298 );299 }300 let code = file.string.as_ref().expect("just set");301 let file_name = Source::new(path.clone(), code.clone());302 if file.parsed.is_none() {303 file.parsed = Some(304 jrsonnet_parser::parse(305 code,306 &ParserSettings {307 source: file_name.clone(),308 },309 )310 .map_err(|e| ImportSyntaxError {311 path: file_name.clone(),312 error: Box::new(e),313 })?,314 );315 }316 let parsed = file.parsed.as_ref().expect("just set").clone();317 if file.evaluating {318 throw!(InfiniteRecursionDetected)319 }320 file.evaluating = true;321 // Dropping file cache guard here, as evaluation may use this map too322 drop(file_cache);323 let res = evaluate(self.create_default_context(file_name), &parsed);324325 let mut file_cache = self.file_cache();326 let mut file = file_cache.raw_entry_mut().from_key(&path);327328 let RawEntryMut::Occupied(file) = &mut file else {329 unreachable!("this file was just here!")330 };331 let file = file.get_mut();332 file.evaluating = false;333 match res {334 Ok(v) => {335 file.evaluated = Some(v.clone());336 Ok(v)337 }338 Err(e) => Err(e),339 }340 }341342 /// Has same semantics as `import 'path'` called from `from` file343 pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {344 let resolved = self.resolve_from(from, path)?;345 self.import_resolved(resolved)346 }347 pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {348 let resolved = self.resolve(path)?;349 self.import_resolved(resolved)350 }351352 /// Creates context with all passed global variables353 pub fn create_default_context(&self, source: Source) -> Context {354 let context_initializer = &self.settings().context_initializer;355 context_initializer.initialize(self.clone(), source)356 }357358 /// Executes code creating a new stack frame359 pub fn push<T>(360 e: CallLocation<'_>,361 frame_desc: impl FnOnce() -> String,362 f: impl FnOnce() -> Result<T>,363 ) -> Result<T> {364 let _guard = check_depth()?;365366 f().with_description_src(e, frame_desc)367 }368369 /// Executes code creating a new stack frame370 pub fn push_val(371 &self,372 e: &ExprLocation,373 frame_desc: impl FnOnce() -> String,374 f: impl FnOnce() -> Result<Val>,375 ) -> Result<Val> {376 let _guard = check_depth()?;377378 f().with_description_src(e, frame_desc)379 }380 /// Executes code creating a new stack frame381 pub fn push_description<T>(382 frame_desc: impl FnOnce() -> String,383 f: impl FnOnce() -> Result<T>,384 ) -> Result<T> {385 let _guard = check_depth()?;386387 f().with_description(frame_desc)388 }389}390391/// Internals392impl State {393 fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {394 self.0.file_cache.borrow_mut()395 }396 pub fn settings(&self) -> Ref<'_, EvaluationSettings> {397 self.0.settings.borrow()398 }399 pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {400 self.0.settings.borrow_mut()401 }402}403404/// Raw methods evaluate passed values but don't perform TLA execution405impl State {406 /// Parses and evaluates the given snippet407 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {408 let code = code.into();409 let source = Source::new_virtual(name.into(), code.clone());410 let parsed = jrsonnet_parser::parse(411 &code,412 &ParserSettings {413 source: source.clone(),414 },415 )416 .map_err(|e| ImportSyntaxError {417 path: source.clone(),418 error: Box::new(e),419 })?;420 evaluate(self.create_default_context(source), &parsed)421 }422}423424/// Settings utilities425impl State {426 // Only panics in case of [`ImportResolver`] contract violation427 #[allow(clippy::missing_panics_doc)]428 pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {429 self.import_resolver().resolve_from(from, path.as_ref())430 }431432 // Only panics in case of [`ImportResolver`] contract violation433 #[allow(clippy::missing_panics_doc)]434 pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {435 self.import_resolver().resolve(path.as_ref())436 }437 pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {438 Ref::map(self.settings(), |s| &*s.import_resolver)439 }440 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {441 self.settings_mut().import_resolver = TraceBox(resolver);442 }443 pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {444 Ref::map(self.settings(), |s| &*s.context_initializer)445 }446}1//! jsonnet interpreter implementation2#![cfg_attr(feature = "nightly", feature(thread_local))]3#![deny(unsafe_op_in_unsafe_fn)]4#![warn(5 clippy::all,6 clippy::nursery,7 clippy::pedantic,8 // missing_docs,9 elided_lifetimes_in_paths,10 explicit_outlives_requirements,11 noop_method_call,12 single_use_lifetimes,13 variant_size_differences,14 rustdoc::all15)]16#![allow(17 macro_expanded_macro_exports_accessed_by_absolute_paths,18 clippy::ptr_arg,19 // Too verbose20 clippy::must_use_candidate,21 // A lot of functions pass around errors thrown by code22 clippy::missing_errors_doc,23 // A lot of pointers have interior Rc24 clippy::needless_pass_by_value,25 // Its fine26 clippy::wildcard_imports,27 clippy::enum_glob_use,28 clippy::module_name_repetitions,29 // TODO: fix individual issues, however this works as intended almost everywhere30 clippy::cast_precision_loss,31 clippy::cast_possible_wrap,32 clippy::cast_possible_truncation,33 clippy::cast_sign_loss,34 // False positives35 // https://github.com/rust-lang/rust-clippy/issues/690236 clippy::use_self,37 // https://github.com/rust-lang/rust-clippy/issues/853938 clippy::iter_with_drain,39 // ci is being run with nightly, but library should work on stable40 clippy::missing_const_for_fn,41)]4243// For jrsonnet-macros44extern crate self as jrsonnet_evaluator;4546mod ctx;47mod dynamic;48pub mod error;49mod evaluate;50pub mod function;51pub mod gc;52mod import;53mod integrations;54pub mod manifest;55mod map;56mod obj;57pub mod stack;58pub mod stdlib;59mod tla;60pub mod trace;61pub mod typed;62pub mod val;6364use std::{65 any::Any,66 cell::{Ref, RefCell, RefMut},67 fmt::{self, Debug},68 path::Path,69};7071pub use ctx::*;72pub use dynamic::*;73pub use error::{Error, ErrorKind::*, Result, ResultExt};74pub use evaluate::*;75use function::CallLocation;76use gc::{GcHashMap, TraceBox};77use hashbrown::hash_map::RawEntryMut;78pub use import::*;79use jrsonnet_gcmodule::{Cc, Trace};80pub use jrsonnet_interner::{IBytes, IStr};81pub use jrsonnet_parser as parser;82use jrsonnet_parser::*;83pub use obj::*;84use stack::check_depth;85pub use tla::apply_tla;86pub use val::{Thunk, Val};8788/// Thunk without bound `super`/`this`89/// object inheritance may be overriden multiple times, and will be fixed only on field read90pub trait Unbound: Trace {91 /// Type of value after object context is bound92 type Bound;93 /// Create value bound to specified object context94 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;95}9697/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code98/// Standard jsonnet fields are always unbound99#[derive(Clone, Trace)]100pub enum MaybeUnbound {101 /// Value needs to be bound to `this`/`super`102 Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),103 /// Value is object-independent104 Bound(Thunk<Val>),105}106107impl Debug for MaybeUnbound {108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {109 write!(f, "MaybeUnbound")110 }111}112impl MaybeUnbound {113 /// Attach object context to value, if required114 pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {115 match self {116 Self::Unbound(v) => v.bind(sup, this),117 Self::Bound(v) => Ok(v.evaluate()?),118 }119 }120}121122/// During import, this trait will be called to create initial context for file.123/// It may initialize global variables, stdlib for example.124pub trait ContextInitializer: Trace {125 /// Initialize default file context.126 fn initialize(&self, state: State, for_file: Source) -> Context;127 /// Allows upcasting from abstract to concrete context initializer.128 /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.129 fn as_any(&self) -> &dyn Any;130}131132/// Context initializer which adds nothing.133#[derive(Trace)]134pub struct DummyContextInitializer;135impl ContextInitializer for DummyContextInitializer {136 fn initialize(&self, state: State, _for_file: Source) -> Context {137 ContextBuilder::new(state).build()138 }139 fn as_any(&self) -> &dyn Any {140 self141 }142}143144/// Dynamically reconfigurable evaluation settings145#[derive(Trace)]146pub struct EvaluationSettings {147 /// Context initializer, which will be used for imports and everything148 /// [`NoopContextInitializer`] is used by default, most likely you want to have `jrsonnet-stdlib`149 pub context_initializer: TraceBox<dyn ContextInitializer>,150 /// Used to resolve file locations/contents151 pub import_resolver: TraceBox<dyn ImportResolver>,152}153impl Default for EvaluationSettings {154 fn default() -> Self {155 Self {156 context_initializer: tb!(DummyContextInitializer),157 import_resolver: tb!(DummyImportResolver),158 }159 }160}161162#[derive(Trace)]163struct FileData {164 string: Option<IStr>,165 bytes: Option<IBytes>,166 parsed: Option<LocExpr>,167 evaluated: Option<Val>,168169 evaluating: bool,170}171impl FileData {172 fn new_string(data: IStr) -> Self {173 Self {174 string: Some(data),175 bytes: None,176 parsed: None,177 evaluated: None,178 evaluating: false,179 }180 }181 fn new_bytes(data: IBytes) -> Self {182 Self {183 string: None,184 bytes: Some(data),185 parsed: None,186 evaluated: None,187 evaluating: false,188 }189 }190}191192#[derive(Default, Trace)]193pub struct EvaluationStateInternals {194 /// Internal state195 file_cache: RefCell<GcHashMap<SourcePath, FileData>>,196 /// Settings, safe to change at runtime197 settings: RefCell<EvaluationSettings>,198}199200/// Maintains stack trace and import resolution201#[derive(Default, Clone, Trace)]202pub struct State(Cc<EvaluationStateInternals>);203204impl State {205 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise206 pub fn import_resolved_str(&self, path: SourcePath) -> Result<IStr> {207 let mut file_cache = self.file_cache();208 let mut file = file_cache.raw_entry_mut().from_key(&path);209210 let file = match file {211 RawEntryMut::Occupied(ref mut d) => d.get_mut(),212 RawEntryMut::Vacant(v) => {213 let data = self.settings().import_resolver.load_file_contents(&path)?;214 v.insert(215 path.clone(),216 FileData::new_string(217 std::str::from_utf8(&data)218 .map_err(|_| ImportBadFileUtf8(path.clone()))?219 .into(),220 ),221 )222 .1223 }224 };225 if let Some(str) = &file.string {226 return Ok(str.clone());227 }228 if file.string.is_none() {229 file.string = Some(230 file.bytes231 .as_ref()232 .expect("either string or bytes should be set")233 .clone()234 .cast_str()235 .ok_or_else(|| ImportBadFileUtf8(path.clone()))?,236 );237 }238 Ok(file.string.as_ref().expect("just set").clone())239 }240 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise241 pub fn import_resolved_bin(&self, path: SourcePath) -> Result<IBytes> {242 let mut file_cache = self.file_cache();243 let mut file = file_cache.raw_entry_mut().from_key(&path);244245 let file = match file {246 RawEntryMut::Occupied(ref mut d) => d.get_mut(),247 RawEntryMut::Vacant(v) => {248 let data = self.settings().import_resolver.load_file_contents(&path)?;249 v.insert(path.clone(), FileData::new_bytes(data.as_slice().into()))250 .1251 }252 };253 if let Some(str) = &file.bytes {254 return Ok(str.clone());255 }256 if file.bytes.is_none() {257 file.bytes = Some(258 file.string259 .as_ref()260 .expect("either string or bytes should be set")261 .clone()262 .cast_bytes(),263 );264 }265 Ok(file.bytes.as_ref().expect("just set").clone())266 }267 /// Should only be called with path retrieved from [`resolve_path`], may panic otherwise268 pub fn import_resolved(&self, path: SourcePath) -> Result<Val> {269 let mut file_cache = self.file_cache();270 let mut file = file_cache.raw_entry_mut().from_key(&path);271272 let file = match file {273 RawEntryMut::Occupied(ref mut d) => d.get_mut(),274 RawEntryMut::Vacant(v) => {275 let data = self.settings().import_resolver.load_file_contents(&path)?;276 v.insert(277 path.clone(),278 FileData::new_string(279 std::str::from_utf8(&data)280 .map_err(|_| ImportBadFileUtf8(path.clone()))?281 .into(),282 ),283 )284 .1285 }286 };287 if let Some(val) = &file.evaluated {288 return Ok(val.clone());289 }290 if file.string.is_none() {291 file.string = Some(292 std::str::from_utf8(293 file.bytes294 .as_ref()295 .expect("either string or bytes should be set"),296 )297 .map_err(|_| ImportBadFileUtf8(path.clone()))?298 .into(),299 );300 }301 let code = file.string.as_ref().expect("just set");302 let file_name = Source::new(path.clone(), code.clone());303 if file.parsed.is_none() {304 file.parsed = Some(305 jrsonnet_parser::parse(306 code,307 &ParserSettings {308 source: file_name.clone(),309 },310 )311 .map_err(|e| ImportSyntaxError {312 path: file_name.clone(),313 error: Box::new(e),314 })?,315 );316 }317 let parsed = file.parsed.as_ref().expect("just set").clone();318 if file.evaluating {319 throw!(InfiniteRecursionDetected)320 }321 file.evaluating = true;322 // Dropping file cache guard here, as evaluation may use this map too323 drop(file_cache);324 let res = evaluate(self.create_default_context(file_name), &parsed);325326 let mut file_cache = self.file_cache();327 let mut file = file_cache.raw_entry_mut().from_key(&path);328329 let RawEntryMut::Occupied(file) = &mut file else {330 unreachable!("this file was just here!")331 };332 let file = file.get_mut();333 file.evaluating = false;334 match res {335 Ok(v) => {336 file.evaluated = Some(v.clone());337 Ok(v)338 }339 Err(e) => Err(e),340 }341 }342343 /// Has same semantics as `import 'path'` called from `from` file344 pub fn import_from(&self, from: &SourcePath, path: &str) -> Result<Val> {345 let resolved = self.resolve_from(from, path)?;346 self.import_resolved(resolved)347 }348 pub fn import(&self, path: impl AsRef<Path>) -> Result<Val> {349 let resolved = self.resolve(path)?;350 self.import_resolved(resolved)351 }352353 /// Creates context with all passed global variables354 pub fn create_default_context(&self, source: Source) -> Context {355 let context_initializer = &self.settings().context_initializer;356 context_initializer.initialize(self.clone(), source)357 }358359 /// Executes code creating a new stack frame360 pub fn push<T>(361 e: CallLocation<'_>,362 frame_desc: impl FnOnce() -> String,363 f: impl FnOnce() -> Result<T>,364 ) -> Result<T> {365 let _guard = check_depth()?;366367 f().with_description_src(e, frame_desc)368 }369370 /// Executes code creating a new stack frame371 pub fn push_val(372 &self,373 e: &ExprLocation,374 frame_desc: impl FnOnce() -> String,375 f: impl FnOnce() -> Result<Val>,376 ) -> Result<Val> {377 let _guard = check_depth()?;378379 f().with_description_src(e, frame_desc)380 }381 /// Executes code creating a new stack frame382 pub fn push_description<T>(383 frame_desc: impl FnOnce() -> String,384 f: impl FnOnce() -> Result<T>,385 ) -> Result<T> {386 let _guard = check_depth()?;387388 f().with_description(frame_desc)389 }390}391392/// Internals393impl State {394 fn file_cache(&self) -> RefMut<'_, GcHashMap<SourcePath, FileData>> {395 self.0.file_cache.borrow_mut()396 }397 pub fn settings(&self) -> Ref<'_, EvaluationSettings> {398 self.0.settings.borrow()399 }400 pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {401 self.0.settings.borrow_mut()402 }403}404405/// Raw methods evaluate passed values but don't perform TLA execution406impl State {407 /// Parses and evaluates the given snippet408 pub fn evaluate_snippet(&self, name: impl Into<IStr>, code: impl Into<IStr>) -> Result<Val> {409 let code = code.into();410 let source = Source::new_virtual(name.into(), code.clone());411 let parsed = jrsonnet_parser::parse(412 &code,413 &ParserSettings {414 source: source.clone(),415 },416 )417 .map_err(|e| ImportSyntaxError {418 path: source.clone(),419 error: Box::new(e),420 })?;421 evaluate(self.create_default_context(source), &parsed)422 }423}424425/// Settings utilities426impl State {427 // Only panics in case of [`ImportResolver`] contract violation428 #[allow(clippy::missing_panics_doc)]429 pub fn resolve_from(&self, from: &SourcePath, path: &str) -> Result<SourcePath> {430 self.import_resolver().resolve_from(from, path.as_ref())431 }432433 // Only panics in case of [`ImportResolver`] contract violation434 #[allow(clippy::missing_panics_doc)]435 pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {436 self.import_resolver().resolve(path.as_ref())437 }438 pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {439 Ref::map(self.settings(), |s| &*s.import_resolver)440 }441 pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {442 self.settings_mut().import_resolver = TraceBox(resolver);443 }444 pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {445 Ref::map(self.settings(), |s| &*s.context_initializer)446 }447}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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -5,9 +5,10 @@
use jrsonnet_types::ValType;
use crate::{
- error::{Error::*, LocError},
+ error::{Error, ErrorKind::*},
function::FuncVal,
gc::{GcHashMap, TraceBox},
+ manifest::{ManifestFormat, ToStringFormat},
throw,
typed::BoundedUsize,
ObjValue, Result, Unbound, WeakObjValue,
@@ -21,7 +22,7 @@
#[derive(Trace)]
enum ThunkInner<T: Trace> {
Computed(T),
- Errored(LocError),
+ Errored(Error),
Waiting(TraceBox<dyn ThunkValue<Output = T>>),
Pending,
}
@@ -116,33 +117,6 @@
impl<T: Trace> PartialEq for Thunk<T> {
fn eq(&self, other: &Self) -> bool {
Cc::ptr_eq(&self.0, &other.0)
- }
-}
-
-pub trait ManifestFormat {
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
- fn manifest(&self, val: Val) -> Result<String> {
- let mut out = String::new();
- self.manifest_buf(val, &mut out)?;
- Ok(out)
- }
-}
-impl<T> ManifestFormat for Box<T>
-where
- T: ManifestFormat + ?Sized,
-{
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
- let inner = &**self;
- inner.manifest_buf(val, buf)
- }
-}
-impl<T> ManifestFormat for &'_ T
-where
- T: ManifestFormat + ?Sized,
-{
- fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
- let inner = &**self;
- inner.manifest_buf(val, buf)
}
}
@@ -649,9 +623,7 @@
Self::Bool(false) => "false".into(),
Self::Null => "null".into(),
Self::Str(s) => s.clone(),
- _ => self
- .manifest(crate::stdlib::manifest::ToStringFormat)
- .map(IStr::from)?,
+ _ => self.manifest(ToStringFormat).map(IStr::from)?,
})
}
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,
};