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.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.rsdiffbeforeafterboth1use std::{2 cell::{Ref, RefCell, RefMut},3 collections::HashMap,4 rc::Rc,5};67use jrsonnet_evaluator::{8 error::{Error::*, Result},9 function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},10 gc::{GcHashMap, TraceBox},11 tb,12 trace::PathResolver,13 Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,14};15use jrsonnet_gcmodule::{Cc, Trace};16use jrsonnet_parser::Source;1718mod expr;19mod types;20pub use types::*;21mod arrays;22pub use arrays::*;23mod math;24pub use math::*;25mod operator;26pub use operator::*;27mod sort;28pub use sort::*;29mod hash;30pub use hash::*;31mod encoding;32pub use encoding::*;33mod objects;34pub use objects::*;35mod manifest;36pub use manifest::*;37mod parse;38pub use parse::*;39mod strings;40pub use strings::*;41mod misc;42pub use misc::*;4344pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {45 let mut builder = ObjValueBuilder::new();4647 let expr = expr::stdlib_expr();48 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)49 .expect("stdlib.jsonnet should have no errors")50 .as_obj()51 .expect("stdlib.jsonnet should evaluate to object");5253 builder.with_super(eval);5455 for (name, builtin) in [56 // Types57 ("type", builtin_type::INST),58 ("isString", builtin_is_string::INST),59 ("isNumber", builtin_is_number::INST),60 ("isBoolean", builtin_is_boolean::INST),61 ("isObject", builtin_is_object::INST),62 ("isArray", builtin_is_array::INST),63 ("isFunction", builtin_is_function::INST),64 // Arrays65 ("makeArray", builtin_make_array::INST),66 ("slice", builtin_slice::INST),67 ("map", builtin_map::INST),68 ("flatMap", builtin_flatmap::INST),69 ("filter", builtin_filter::INST),70 ("foldl", builtin_foldl::INST),71 ("foldr", builtin_foldr::INST),72 ("range", builtin_range::INST),73 ("join", builtin_join::INST),74 ("reverse", builtin_reverse::INST),75 ("any", builtin_any::INST),76 ("all", builtin_all::INST),77 ("member", builtin_member::INST),78 ("count", builtin_count::INST),79 // Math80 ("modulo", builtin_modulo::INST),81 ("floor", builtin_floor::INST),82 ("ceil", builtin_ceil::INST),83 ("log", builtin_log::INST),84 ("pow", builtin_pow::INST),85 ("sqrt", builtin_sqrt::INST),86 ("sin", builtin_sin::INST),87 ("cos", builtin_cos::INST),88 ("tan", builtin_tan::INST),89 ("asin", builtin_asin::INST),90 ("acos", builtin_acos::INST),91 ("atan", builtin_atan::INST),92 ("exp", builtin_exp::INST),93 ("mantissa", builtin_mantissa::INST),94 ("exponent", builtin_exponent::INST),95 // Operator96 ("mod", builtin_mod::INST),97 ("primitiveEquals", builtin_primitive_equals::INST),98 ("equals", builtin_equals::INST),99 ("format", builtin_format::INST),100 // Sort101 ("sort", builtin_sort::INST),102 // Hash103 ("md5", builtin_md5::INST),104 // Encoding105 ("encodeUTF8", builtin_encode_utf8::INST),106 ("decodeUTF8", builtin_decode_utf8::INST),107 ("base64", builtin_base64::INST),108 ("base64Decode", builtin_base64_decode::INST),109 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),110 // Objects111 ("objectFieldsEx", builtin_object_fields_ex::INST),112 ("objectHasEx", builtin_object_has_ex::INST),113 // Manifest114 ("escapeStringJson", builtin_escape_string_json::INST),115 ("manifestJsonEx", builtin_manifest_json_ex::INST),116 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),117 // Parsing118 ("parseJson", builtin_parse_json::INST),119 ("parseYaml", builtin_parse_yaml::INST),120 // Strings121 ("codepoint", builtin_codepoint::INST),122 ("substr", builtin_substr::INST),123 ("char", builtin_char::INST),124 ("strReplace", builtin_str_replace::INST),125 ("splitLimit", builtin_splitlimit::INST),126 ("asciiUpper", builtin_ascii_upper::INST),127 ("asciiLower", builtin_ascii_lower::INST),128 ("findSubstr", builtin_find_substr::INST),129 // Misc130 ("length", builtin_length::INST),131 ("startsWith", builtin_starts_with::INST),132 ("endsWith", builtin_ends_with::INST),133 ]134 .iter()135 .cloned()136 {137 builder138 .member(name.into())139 .hide()140 .value(Val::Func(FuncVal::StaticBuiltin(builtin)))141 .expect("no conflict");142 }143144 builder145 .member("extVar".into())146 .hide()147 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {148 settings: settings.clone()149 })))))150 .expect("no conflict");151 builder152 .member("native".into())153 .hide()154 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {155 settings: settings.clone()156 })))))157 .expect("no conflict");158 builder159 .member("trace".into())160 .hide()161 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace {162 settings163 })))))164 .expect("no conflict");165166 builder167 .member("id".into())168 .hide()169 .value(Val::Func(FuncVal::Id))170 .expect("no conflict");171172 builder.build()173}174175pub trait TracePrinter {176 fn print_trace(&self, loc: CallLocation, value: IStr);177}178179pub struct StdTracePrinter {180 resolver: PathResolver,181}182impl StdTracePrinter {183 pub fn new(resolver: PathResolver) -> Self {184 Self { resolver }185 }186}187impl TracePrinter for StdTracePrinter {188 fn print_trace(&self, loc: CallLocation, value: IStr) {189 eprint!("TRACE:");190 if let Some(loc) = loc.0 {191 let locs = loc.0.map_source_locations(&[loc.1]);192 eprint!(193 " {}:{}",194 match loc.0.source_path().path() {195 Some(p) => self.resolver.resolve(p),196 None => loc.0.source_path().to_string(),197 },198 locs[0].line199 );200 }201 eprintln!(" {}", value);202 }203}204205pub struct Settings {206 /// Used for `std.extVar`207 pub ext_vars: HashMap<IStr, TlaArg>,208 /// Used for `std.native`209 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,210 /// Helper to add globals without implementing custom ContextInitializer211 pub globals: GcHashMap<IStr, Thunk<Val>>,212 /// Used for `std.trace`213 pub trace_printer: Box<dyn TracePrinter>,214 /// Used for `std.thisFile`215 pub path_resolver: PathResolver,216}217218fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {219 let source_name = format!("<extvar:{}>", name);220 Source::new_virtual(source_name.into(), code.into())221}222223#[derive(Trace)]224pub struct ContextInitializer {225 // When we don't need to support legacy-this-file, we can reuse same context for all files226 #[cfg(not(feature = "legacy-this-file"))]227 context: Context,228 // Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it229 #[cfg(feature = "legacy-this-file")]230 stdlib_obj: ObjValue,231 settings: Rc<RefCell<Settings>>,232}233impl ContextInitializer {234 pub fn new(s: State, resolver: PathResolver) -> Self {235 let settings = Settings {236 ext_vars: Default::default(),237 ext_natives: Default::default(),238 globals: Default::default(),239 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),240 path_resolver: resolver,241 };242 let settings = Rc::new(RefCell::new(settings));243 Self {244 #[cfg(not(feature = "legacy-this-file"))]245 context: {246 let mut context = ContextBuilder::with_capacity(s, 1);247 context.bind(248 "std".into(),249 Thunk::evaluated(Val::Obj(stdlib_uncached(settings.clone()))),250 );251 context.build()252 },253 #[cfg(feature = "legacy-this-file")]254 stdlib_obj: stdlib_uncached(s, settings.clone()),255 settings,256 }257 }258 pub fn settings(&self) -> Ref<Settings> {259 self.settings.borrow()260 }261 pub fn settings_mut(&self) -> RefMut<Settings> {262 self.settings.borrow_mut()263 }264 pub fn add_ext_var(&self, name: IStr, value: Val) {265 self.settings_mut()266 .ext_vars267 .insert(name, TlaArg::Val(value));268 }269 pub fn add_ext_str(&self, name: IStr, value: IStr) {270 self.settings_mut()271 .ext_vars272 .insert(name, TlaArg::String(value));273 }274 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {275 let code = code.into();276 let source = extvar_source(name, code.clone());277 let parsed = jrsonnet_parser::parse(278 &code,279 &jrsonnet_parser::ParserSettings {280 source: source.clone(),281 },282 )283 .map_err(|e| ImportSyntaxError {284 path: source,285 error: Box::new(e),286 })?;287 // self.data_mut().volatile_files.insert(source_name, code);288 self.settings_mut()289 .ext_vars290 .insert(name.into(), TlaArg::Code(parsed));291 Ok(())292 }293 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {294 self.settings_mut().ext_natives.insert(name, cb);295 }296}297impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {298 #[cfg(not(feature = "legacy-this-file"))]299 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {300 let out = self.context.clone();301 let globals = &self.settings().globals;302 if globals.is_empty() {303 return out;304 }305306 let mut out = ContextBuilder::extend(out);307 for (k, v) in globals.iter() {308 out.bind(k.clone(), v.clone());309 }310 out.build()311 }312 #[cfg(feature = "legacy-this-file")]313 fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {314 let mut builder = ObjValueBuilder::new();315 builder.with_super(self.stdlib_obj.clone());316 builder317 .member("thisFile".into())318 .hide()319 .value(320 s,321 Val::Str(match source.source_path().path() {322 Some(p) => self.settings().path_resolver.resolve(p).into(),323 None => source.source_path().to_string().into(),324 }),325 )326 .expect("this object builder is empty");327 let stdlib_with_this_file = builder.build();328329 let mut context = ContextBuilder::with_capacity(1);330 context.bind(331 "std".into(),332 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),333 );334 for (k, v) in self.settings().globals.iter() {335 context.bind(k.clone(), v.clone());336 }337 context.build()338 }339 fn as_any(&self) -> &dyn std::any::Any {340 self341 }342}343344pub trait StateExt {345 /// This method was previously implemented in jrsonnet-evaluator itself346 fn with_stdlib(&self);347 fn add_global(&self, name: IStr, value: Thunk<Val>);348}349350impl StateExt for State {351 fn with_stdlib(&self) {352 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());353 self.settings_mut().context_initializer = tb!(initializer)354 }355 fn add_global(&self, name: IStr, value: Thunk<Val>) {356 self.settings()357 .context_initializer358 .as_any()359 .downcast_ref::<ContextInitializer>()360 .expect("not standard context initializer")361 .settings_mut()362 .globals363 .insert(name, value);364 }365}1use std::{2 cell::{Ref, RefCell, RefMut},3 collections::HashMap,4 rc::Rc,5};67use jrsonnet_evaluator::{8 error::{ErrorKind::*, Result},9 function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},10 gc::{GcHashMap, TraceBox},11 tb,12 trace::PathResolver,13 Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,14};15use jrsonnet_gcmodule::{Cc, Trace};16use jrsonnet_parser::Source;1718mod expr;19mod types;20pub use types::*;21mod arrays;22pub use arrays::*;23mod math;24pub use math::*;25mod operator;26pub use operator::*;27mod sort;28pub use sort::*;29mod hash;30pub use hash::*;31mod encoding;32pub use encoding::*;33mod objects;34pub use objects::*;35mod manifest;36pub use manifest::*;37mod parse;38pub use parse::*;39mod strings;40pub use strings::*;41mod misc;42pub use misc::*;4344pub fn stdlib_uncached(settings: Rc<RefCell<Settings>>) -> ObjValue {45 let mut builder = ObjValueBuilder::new();4647 let expr = expr::stdlib_expr();48 let eval = jrsonnet_evaluator::evaluate(ContextBuilder::dangerous_empty_state().build(), &expr)49 .expect("stdlib.jsonnet should have no errors")50 .as_obj()51 .expect("stdlib.jsonnet should evaluate to object");5253 builder.with_super(eval);5455 for (name, builtin) in [56 // Types57 ("type", builtin_type::INST),58 ("isString", builtin_is_string::INST),59 ("isNumber", builtin_is_number::INST),60 ("isBoolean", builtin_is_boolean::INST),61 ("isObject", builtin_is_object::INST),62 ("isArray", builtin_is_array::INST),63 ("isFunction", builtin_is_function::INST),64 // Arrays65 ("makeArray", builtin_make_array::INST),66 ("slice", builtin_slice::INST),67 ("map", builtin_map::INST),68 ("flatMap", builtin_flatmap::INST),69 ("filter", builtin_filter::INST),70 ("foldl", builtin_foldl::INST),71 ("foldr", builtin_foldr::INST),72 ("range", builtin_range::INST),73 ("join", builtin_join::INST),74 ("reverse", builtin_reverse::INST),75 ("any", builtin_any::INST),76 ("all", builtin_all::INST),77 ("member", builtin_member::INST),78 ("count", builtin_count::INST),79 // Math80 ("modulo", builtin_modulo::INST),81 ("floor", builtin_floor::INST),82 ("ceil", builtin_ceil::INST),83 ("log", builtin_log::INST),84 ("pow", builtin_pow::INST),85 ("sqrt", builtin_sqrt::INST),86 ("sin", builtin_sin::INST),87 ("cos", builtin_cos::INST),88 ("tan", builtin_tan::INST),89 ("asin", builtin_asin::INST),90 ("acos", builtin_acos::INST),91 ("atan", builtin_atan::INST),92 ("exp", builtin_exp::INST),93 ("mantissa", builtin_mantissa::INST),94 ("exponent", builtin_exponent::INST),95 // Operator96 ("mod", builtin_mod::INST),97 ("primitiveEquals", builtin_primitive_equals::INST),98 ("equals", builtin_equals::INST),99 ("format", builtin_format::INST),100 // Sort101 ("sort", builtin_sort::INST),102 // Hash103 ("md5", builtin_md5::INST),104 #[cfg(feature = "exp-more-hashes")]105 ("sha256", builtin_sha256::INST),106 // Encoding107 ("encodeUTF8", builtin_encode_utf8::INST),108 ("decodeUTF8", builtin_decode_utf8::INST),109 ("base64", builtin_base64::INST),110 ("base64Decode", builtin_base64_decode::INST),111 ("base64DecodeBytes", builtin_base64_decode_bytes::INST),112 // Objects113 ("objectFieldsEx", builtin_object_fields_ex::INST),114 ("objectHasEx", builtin_object_has_ex::INST),115 // Manifest116 ("escapeStringJson", builtin_escape_string_json::INST),117 ("manifestJsonEx", builtin_manifest_json_ex::INST),118 ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),119 // Parsing120 ("parseJson", builtin_parse_json::INST),121 ("parseYaml", builtin_parse_yaml::INST),122 // Strings123 ("codepoint", builtin_codepoint::INST),124 ("substr", builtin_substr::INST),125 ("char", builtin_char::INST),126 ("strReplace", builtin_str_replace::INST),127 ("splitLimit", builtin_splitlimit::INST),128 ("asciiUpper", builtin_ascii_upper::INST),129 ("asciiLower", builtin_ascii_lower::INST),130 ("findSubstr", builtin_find_substr::INST),131 // Misc132 ("length", builtin_length::INST),133 ("startsWith", builtin_starts_with::INST),134 ("endsWith", builtin_ends_with::INST),135 ]136 .iter()137 .cloned()138 {139 builder140 .member(name.into())141 .hide()142 .value(Val::Func(FuncVal::StaticBuiltin(builtin)))143 .expect("no conflict");144 }145146 builder147 .member("extVar".into())148 .hide()149 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {150 settings: settings.clone()151 })))))152 .expect("no conflict");153 builder154 .member("native".into())155 .hide()156 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {157 settings: settings.clone()158 })))))159 .expect("no conflict");160 builder161 .member("trace".into())162 .hide()163 .value(Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace {164 settings165 })))))166 .expect("no conflict");167168 builder169 .member("id".into())170 .hide()171 .value(Val::Func(FuncVal::Id))172 .expect("no conflict");173174 builder.build()175}176177pub trait TracePrinter {178 fn print_trace(&self, loc: CallLocation, value: IStr);179}180181pub struct StdTracePrinter {182 resolver: PathResolver,183}184impl StdTracePrinter {185 pub fn new(resolver: PathResolver) -> Self {186 Self { resolver }187 }188}189impl TracePrinter for StdTracePrinter {190 fn print_trace(&self, loc: CallLocation, value: IStr) {191 eprint!("TRACE:");192 if let Some(loc) = loc.0 {193 let locs = loc.0.map_source_locations(&[loc.1]);194 eprint!(195 " {}:{}",196 match loc.0.source_path().path() {197 Some(p) => self.resolver.resolve(p),198 None => loc.0.source_path().to_string(),199 },200 locs[0].line201 );202 }203 eprintln!(" {}", value);204 }205}206207pub struct Settings {208 /// Used for `std.extVar`209 pub ext_vars: HashMap<IStr, TlaArg>,210 /// Used for `std.native`211 pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,212 /// Helper to add globals without implementing custom ContextInitializer213 pub globals: GcHashMap<IStr, Thunk<Val>>,214 /// Used for `std.trace`215 pub trace_printer: Box<dyn TracePrinter>,216 /// Used for `std.thisFile`217 pub path_resolver: PathResolver,218}219220fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {221 let source_name = format!("<extvar:{}>", name);222 Source::new_virtual(source_name.into(), code.into())223}224225#[derive(Trace)]226pub struct ContextInitializer {227 // When we don't need to support legacy-this-file, we can reuse same context for all files228 #[cfg(not(feature = "legacy-this-file"))]229 context: Context,230 // Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it231 #[cfg(feature = "legacy-this-file")]232 stdlib_obj: ObjValue,233 settings: Rc<RefCell<Settings>>,234}235impl ContextInitializer {236 pub fn new(s: State, resolver: PathResolver) -> Self {237 let settings = Settings {238 ext_vars: Default::default(),239 ext_natives: Default::default(),240 globals: Default::default(),241 trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),242 path_resolver: resolver,243 };244 let settings = Rc::new(RefCell::new(settings));245 Self {246 #[cfg(not(feature = "legacy-this-file"))]247 context: {248 let mut context = ContextBuilder::with_capacity(s, 1);249 context.bind(250 "std".into(),251 Thunk::evaluated(Val::Obj(stdlib_uncached(settings.clone()))),252 );253 context.build()254 },255 #[cfg(feature = "legacy-this-file")]256 stdlib_obj: stdlib_uncached(s, settings.clone()),257 settings,258 }259 }260 pub fn settings(&self) -> Ref<Settings> {261 self.settings.borrow()262 }263 pub fn settings_mut(&self) -> RefMut<Settings> {264 self.settings.borrow_mut()265 }266 pub fn add_ext_var(&self, name: IStr, value: Val) {267 self.settings_mut()268 .ext_vars269 .insert(name, TlaArg::Val(value));270 }271 pub fn add_ext_str(&self, name: IStr, value: IStr) {272 self.settings_mut()273 .ext_vars274 .insert(name, TlaArg::String(value));275 }276 pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {277 let code = code.into();278 let source = extvar_source(name, code.clone());279 let parsed = jrsonnet_parser::parse(280 &code,281 &jrsonnet_parser::ParserSettings {282 source: source.clone(),283 },284 )285 .map_err(|e| ImportSyntaxError {286 path: source,287 error: Box::new(e),288 })?;289 // self.data_mut().volatile_files.insert(source_name, code);290 self.settings_mut()291 .ext_vars292 .insert(name.into(), TlaArg::Code(parsed));293 Ok(())294 }295 pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {296 self.settings_mut().ext_natives.insert(name, cb);297 }298}299impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {300 #[cfg(not(feature = "legacy-this-file"))]301 fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {302 let out = self.context.clone();303 let globals = &self.settings().globals;304 if globals.is_empty() {305 return out;306 }307308 let mut out = ContextBuilder::extend(out);309 for (k, v) in globals.iter() {310 out.bind(k.clone(), v.clone());311 }312 out.build()313 }314 #[cfg(feature = "legacy-this-file")]315 fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {316 let mut builder = ObjValueBuilder::new();317 builder.with_super(self.stdlib_obj.clone());318 builder319 .member("thisFile".into())320 .hide()321 .value(322 s,323 Val::Str(match source.source_path().path() {324 Some(p) => self.settings().path_resolver.resolve(p).into(),325 None => source.source_path().to_string().into(),326 }),327 )328 .expect("this object builder is empty");329 let stdlib_with_this_file = builder.build();330331 let mut context = ContextBuilder::with_capacity(1);332 context.bind(333 "std".into(),334 Thunk::evaluated(Val::Obj(stdlib_with_this_file)),335 );336 for (k, v) in self.settings().globals.iter() {337 context.bind(k.clone(), v.clone());338 }339 context.build()340 }341 fn as_any(&self) -> &dyn std::any::Any {342 self343 }344}345346pub trait StateExt {347 /// This method was previously implemented in jrsonnet-evaluator itself348 fn with_stdlib(&self);349 fn add_global(&self, name: IStr, value: Thunk<Val>);350}351352impl StateExt for State {353 fn with_stdlib(&self) {354 let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());355 self.settings_mut().context_initializer = tb!(initializer)356 }357 fn add_global(&self, name: IStr, value: Thunk<Val>) {358 self.settings()359 .context_initializer360 .as_any()361 .downcast_ref::<ContextInitializer>()362 .expect("not standard context initializer")363 .settings_mut()364 .globals365 .insert(name, value);366 }367}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,
};