git.delta.rocks / jrsonnet / refs/commits / 58761866e4bc

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2022-11-12parent: #9a50551.patch.diff
in: master

35 files changed

modifiedCargo.lockdiffbeforeafterboth
67source = "registry+https://github.com/rust-lang/crates.io-index"67source = "registry+https://github.com/rust-lang/crates.io-index"
68checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"68checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
69
70[[package]]
71name = "block-buffer"
72version = "0.10.3"
73source = "registry+https://github.com/rust-lang/crates.io-index"
74checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"
75dependencies = [
76 "generic-array",
77]
6978
70[[package]]79[[package]]
71name = "cc"80name = "cc"
140 "bitflags",149 "bitflags",
141]150]
151
152[[package]]
153name = "cpufeatures"
154version = "0.2.5"
155source = "registry+https://github.com/rust-lang/crates.io-index"
156checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320"
157dependencies = [
158 "libc",
159]
160
161[[package]]
162name = "crypto-common"
163version = "0.1.6"
164source = "registry+https://github.com/rust-lang/crates.io-index"
165checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
166dependencies = [
167 "generic-array",
168 "typenum",
169]
170
171[[package]]
172name = "digest"
173version = "0.10.5"
174source = "registry+https://github.com/rust-lang/crates.io-index"
175checksum = "adfbc57365a37acbd2ebf2b64d7e69bb766e2fea813521ed536f5d0520dcf86c"
176dependencies = [
177 "block-buffer",
178 "crypto-common",
179]
180
181[[package]]
182name = "generic-array"
183version = "0.14.6"
184source = "registry+https://github.com/rust-lang/crates.io-index"
185checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
186dependencies = [
187 "typenum",
188 "version_check",
189]
142190
143[[package]]191[[package]]
144name = "getrandom"192name = "getrandom"
304 "serde",352 "serde",
305 "serde_json",353 "serde_json",
306 "serde_yaml_with_quirks",354 "serde_yaml_with_quirks",
355 "sha2",
307 "structdump",356 "structdump",
308]357]
309358
549 "yaml-rust",598 "yaml-rust",
550]599]
600
601[[package]]
602name = "sha2"
603version = "0.10.6"
604source = "registry+https://github.com/rust-lang/crates.io-index"
605checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
606dependencies = [
607 "cfg-if 1.0.0",
608 "cpufeatures",
609 "digest",
610]
551611
552[[package]]612[[package]]
553name = "smallvec"613name = "smallvec"
639 "syn",699 "syn",
640]700]
701
702[[package]]
703name = "typenum"
704version = "1.15.0"
705source = "registry+https://github.com/rust-lang/crates.io-index"
706checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
641707
642[[package]]708[[package]]
643name = "unicode-ident"709name = "unicode-ident"
modifiedbindings/jsonnet/src/import.rsdiffbeforeafterboth
12};12};
1313
14use jrsonnet_evaluator::{14use jrsonnet_evaluator::{
15 error::{Error::*, Result},15 error::{ErrorKind::*, Result},
16 throw, FileImportResolver, ImportResolver,16 throw, FileImportResolver, ImportResolver,
17};17};
18use jrsonnet_gcmodule::Trace;18use jrsonnet_gcmodule::Trace;
modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
1#![allow(clippy::box_default)]
2
1#[cfg(feature = "interop")]3#[cfg(feature = "interop")]
2pub mod interop;4pub mod interop;
20 apply_tla,22 apply_tla,
21 function::TlaArg,23 function::TlaArg,
22 gc::GcHashMap,24 gc::GcHashMap,
23 stack::set_stack_depth_limit,
24 stdlib::manifest::{JsonFormat, ToStringFormat},25 manifest::{JsonFormat, ManifestFormat, ToStringFormat},
26 stack::set_stack_depth_limit,
25 tb, throw,27 tb, throw,
26 trace::{CompactFormat, PathResolver, TraceFormat},28 trace::{CompactFormat, PathResolver, TraceFormat},
27 FileImportResolver, IStr, ManifestFormat, Result, State, Val,29 FileImportResolver, IStr, Result, State, Val,
28};30};
2931
30/// WASM stub32/// WASM stub
193 let filename = parse_path(CStr::from_ptr(filename));195 let filename = parse_path(CStr::from_ptr(filename));
194 match vm196 match vm
195 .state197 .state
196 .import(&filename)198 .import(filename)
197 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))199 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
198 .and_then(|val| val.manifest(&vm.manifest_format))200 .and_then(|val| val.manifest(&vm.manifest_format))
199 {201 {
286 let filename = parse_path(CStr::from_ptr(filename));288 let filename = parse_path(CStr::from_ptr(filename));
287 match vm289 match vm
288 .state290 .state
289 .import(&filename)291 .import(filename)
290 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))292 .and_then(|val| apply_tla(vm.state.clone(), &vm.tla_args, val))
291 .and_then(|val| val_to_multi(val, &vm.manifest_format))293 .and_then(|val| val_to_multi(val, &vm.manifest_format))
292 {294 {
modifiedbindings/jsonnet/src/native.rsdiffbeforeafterboth
5};5};
66
7use jrsonnet_evaluator::{7use jrsonnet_evaluator::{
8 error::{Error, LocError},8 error::{Error, ErrorKind},
9 function::builtin::{NativeCallback, NativeCallbackHandler},9 function::builtin::{NativeCallback, NativeCallbackHandler},
10 tb,10 tb,
11 typed::Typed,11 typed::Typed,
38 cb: JsonnetNativeCallback,38 cb: JsonnetNativeCallback,
39}39}
40impl NativeCallbackHandler for JsonnetNativeCallbackHandler {40impl NativeCallbackHandler for JsonnetNativeCallbackHandler {
41 fn call(&self, args: &[Val]) -> Result<Val, LocError> {41 fn call(&self, args: &[Val]) -> Result<Val, Error> {
42 let mut n_args = Vec::new();42 let mut n_args = Vec::new();
43 for a in args {43 for a in args {
44 n_args.push(Some(Box::new(a.clone())));44 n_args.push(Some(Box::new(a.clone())));
57 Ok(v)57 Ok(v)
58 } else {58 } else {
59 let e = IStr::from_untyped(v).expect("error msg should be a string");59 let e = IStr::from_untyped(v).expect("error msg should be a string");
60 Err(Error::RuntimeError(e).into())60 Err(ErrorKind::RuntimeError(e).into())
61 }61 }
62 }62 }
63}63}
modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
6use clap::{CommandFactory, Parser};6use clap::{CommandFactory, Parser};
7use clap_complete::Shell;7use clap_complete::Shell;
8use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};8use jrsonnet_cli::{ConfigureState, GeneralOpts, ManifestOpts, OutputOpts, TraceOpts};
9use jrsonnet_evaluator::{apply_tla, error::LocError, throw, ResultExt, State, Val};9use jrsonnet_evaluator::{
10 apply_tla,
11 error::{Error as JrError, ErrorKind},
12 throw, ResultExt, State, Val,
13};
1014
11#[cfg(feature = "mimalloc")]15#[cfg(feature = "mimalloc")]
96enum Error {100enum Error {
97 // Handled differently101 // Handled differently
98 #[error("evaluation error")]102 #[error("evaluation error")]
99 Evaluation(LocError),103 Evaluation(JrError),
100 #[error("io error")]104 #[error("io error")]
101 Io(#[from] std::io::Error),105 Io(#[from] std::io::Error),
102 #[error("input is not utf8 encoded")]106 #[error("input is not utf8 encoded")]
103 Utf8(#[from] std::str::Utf8Error),107 Utf8(#[from] std::str::Utf8Error),
104 #[error("missing input argument")]108 #[error("missing input argument")]
105 MissingInputArgument,109 MissingInputArgument,
106}110}
107impl From<LocError> for Error {111impl From<JrError> for Error {
108 fn from(e: LocError) -> Self {112 fn from(e: JrError) -> Self {
109 Self::Evaluation(e)113 Self::Evaluation(e)
110 }114 }
111}115}
112impl From<jrsonnet_evaluator::error::Error> for Error {116impl From<ErrorKind> for Error {
113 fn from(e: jrsonnet_evaluator::error::Error) -> Self {117 fn from(e: ErrorKind) -> Self {
114 Self::from(LocError::from(e))118 Self::from(JrError::from(e))
115 }119 }
116}120}
117121
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
3use clap::{Parser, ValueEnum};3use clap::{Parser, ValueEnum};
4use jrsonnet_evaluator::{4use jrsonnet_evaluator::{
5 error::Result,5 error::Result,
6 stdlib::manifest::{JsonFormat, StringFormat, ToStringFormat, YamlFormat, YamlStreamFormat},6 manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat},
7 ManifestFormat, State,7 State,
8};8};
9use jrsonnet_stdlib::YamlFormat;
910
10use crate::ConfigureState;11use crate::ConfigureState;
1112
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
1use clap::Parser;1use clap::Parser;
2use jrsonnet_evaluator::{2use jrsonnet_evaluator::{
3 error::{Error, Result},3 error::{ErrorKind, Result},
4 function::TlaArg,4 function::TlaArg,
5 gc::GcHashMap,5 gc::GcHashMap,
6 IStr, State,6 IStr, State,
51 {51 {
52 let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());52 let source = Source::new_virtual(format!("<top-level-arg:{name}>").into(), code.into());
53 out.insert(53 out.insert(
54 (&name as &str).into(),54 (name as &str).into(),
55 TlaArg::Code(55 TlaArg::Code(
56 jrsonnet_parser::parse(56 jrsonnet_parser::parse(
57 &code,57 code,
58 &ParserSettings {58 &ParserSettings {
59 source: source.clone(),59 source: source.clone(),
60 },60 },
61 )61 )
62 .map_err(|e| Error::ImportSyntaxError {62 .map_err(|e| ErrorKind::ImportSyntaxError {
63 path: source,63 path: source,
64 error: Box::new(e),64 error: Box::new(e),
65 })?,65 })?,
modifiedcrates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth
4use jrsonnet_interner::IStr;4use jrsonnet_interner::IStr;
55
6use crate::{6use crate::{
7 error::Error::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State, Thunk,7 error::ErrorKind::*, gc::GcHashMap, map::LayeredHashMap, ObjValue, Pending, Result, State,
8 Val,8 Thunk, Val,
9};9};
1010
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
74#[allow(missing_docs)]74#[allow(missing_docs)]
75#[derive(Error, Debug, Clone, Trace)]75#[derive(Error, Debug, Clone, Trace)]
76#[non_exhaustive]76#[non_exhaustive]
77pub enum Error {77pub enum ErrorKind {
78 #[error("intrinsic not found: {0}")]78 #[error("intrinsic not found: {0}")]
79 IntrinsicNotFound(IStr),79 IntrinsicNotFound(IStr),
8080
211}211}
212212
213#[cfg(feature = "anyhow-error")]213#[cfg(feature = "anyhow-error")]
214impl From<anyhow::Error> for LocError {214impl From<anyhow::Error> for Error {
215 fn from(e: anyhow::Error) -> Self {215 fn from(e: anyhow::Error) -> Self {
216 Self::new(Error::Other(Rc::new(e)))216 Self::new(ErrorKind::Other(Rc::new(e)))
217 }217 }
218}218}
219219
220impl From<Error> for LocError {220impl From<ErrorKind> for Error {
221 fn from(e: Error) -> Self {221 fn from(e: ErrorKind) -> Self {
222 Self::new(e)222 Self::new(e)
223 }223 }
224}224}
236pub struct StackTrace(pub Vec<StackTraceElement>);236pub struct StackTrace(pub Vec<StackTraceElement>);
237237
238#[derive(Clone, Trace)]238#[derive(Clone, Trace)]
239pub struct LocError(Box<(Error, StackTrace)>);239pub struct Error(Box<(ErrorKind, StackTrace)>);
240impl LocError {240impl Error {
241 pub fn new(e: Error) -> Self {241 pub fn new(e: ErrorKind) -> Self {
242 Self(Box::new((e, StackTrace(vec![]))))242 Self(Box::new((e, StackTrace(vec![]))))
243 }243 }
244244
245 pub const fn error(&self) -> &Error {245 pub const fn error(&self) -> &ErrorKind {
246 &(self.0).0246 &(self.0).0
247 }247 }
248 pub fn error_mut(&mut self) -> &mut Error {248 pub fn error_mut(&mut self) -> &mut ErrorKind {
249 &mut (self.0).0249 &mut (self.0).0
250 }250 }
251 pub const fn trace(&self) -> &StackTrace {251 pub const fn trace(&self) -> &StackTrace {
255 &mut (self.0).1255 &mut (self.0).1
256 }256 }
257}257}
258impl Display for LocError {258impl Display for Error {
259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260 writeln!(f, "{}", self.0 .0)?;260 writeln!(f, "{}", self.0 .0)?;
261 for el in &self.0 .1 .0 {261 for el in &self.0 .1 .0 {
269 Ok(())269 Ok(())
270 }270 }
271}271}
272impl Debug for LocError {272impl Debug for Error {
273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 f.debug_tuple("LocError").field(&self.0).finish()274 f.debug_tuple("LocError").field(&self.0).finish()
275 }275 }
294 }294 }
295}295}
296296
297pub type Result<V, E = LocError> = std::result::Result<V, E>;297pub type Result<V, E = Error> = std::result::Result<V, E>;
298pub trait ResultExt: Sized {298pub trait ResultExt: Sized {
299 #[must_use]299 #[must_use]
300 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;300 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;
314 self.with_description_src(src, || msg)314 self.with_description_src(src, || msg)
315 }315 }
316}316}
317impl<T> ResultExt for Result<T, LocError> {317impl<T> ResultExt for Result<T, Error> {
318 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {318 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {
319 if let Err(e) = &mut self {319 if let Err(e) = &mut self {
320 let trace = e.trace_mut();320 let trace = e.trace_mut();
348 return Err($w$(::$i)*$(($($tt)*))?.into())348 return Err($w$(::$i)*$(($($tt)*))?.into())
349 };349 };
350 ($l:literal) => {350 ($l:literal) => {
351 return Err($crate::error::Error::RuntimeError($l.into()).into())351 return Err($crate::error::ErrorKind::RuntimeError($l.into()).into())
352 };352 };
353 ($l:literal, $($tt:tt)*) => {353 ($l:literal, $($tt:tt)*) => {
354 return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())354 return Err($crate::error::ErrorKind::RuntimeError(format!($l, $($tt)*).into()).into())
355 };355 };
356}356}
357357
modifiedcrates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth
3use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};3use jrsonnet_parser::{BindSpec, Destruct, LocExpr, ParamsDesc};
44
5use crate::{5use crate::{
6 error::{Error::*, Result},6 error::{ErrorKind::*, Result},
7 evaluate, evaluate_method, evaluate_named,7 evaluate, evaluate_method, evaluate_named,
8 gc::GcHashMap,8 gc::GcHashMap,
9 tb, throw,9 tb, throw,
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
11use self::destructure::destruct;11use self::destructure::destruct;
12use crate::{12use crate::{
13 destructure::evaluate_dest,13 destructure::evaluate_dest,
14 error::Error::*,14 error::ErrorKind::*,
15 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
16 function::{CallLocation, FuncDesc, FuncVal},16 function::{CallLocation, FuncDesc, FuncVal},
17 tb, throw,17 tb, throw,
18 typed::Typed,18 typed::Typed,
19 val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19 val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},
20 Context, GcHashMap, LocError, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,20 Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,
21 ResultExt, State, Unbound, Val,21 Unbound, Val,
22};22};
23pub mod destructure;23pub mod destructure;
24pub mod operator;24pub mod operator;
165 uctx: B,165 uctx: B,
166 field: &FieldMember,166 field: &FieldMember,
167) -> Result<()> {167) -> Result<()> {
168 let name = evaluate_field_name(ctx.clone(), &field.name)?;168 let name = evaluate_field_name(ctx, &field.name)?;
169 let Some(name) = name else {169 let Some(name) = name else {
170 return Ok(());170 return Ok(());
171 };171 };
187 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {187 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {
188 type Bound = Val;188 type Bound = Val;
189 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {189 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
190 Ok(evaluate_named(190 evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())
191 self.uctx.bind(sup, this)?,
192 &self.value,
193 self.name.clone(),
194 )?)
195 }191 }
196 }192 }
197193
201 .with_visibility(*visibility)197 .with_visibility(*visibility)
202 .with_location(value.1.clone())198 .with_location(value.1.clone())
203 .bindable(tb!(UnboundValue {199 .bindable(tb!(UnboundValue {
204 uctx: uctx.clone(),200 uctx,
205 value: value.clone(),201 value: value.clone(),
206 name: name.clone()202 name,
207 }))?;203 }))?;
208 }204 }
209 FieldMember {205 FieldMember {
236 .with_visibility(*visibility)232 .with_visibility(*visibility)
237 .with_location(value.1.clone())233 .with_location(value.1.clone())
238 .bindable(tb!(UnboundMethod {234 .bindable(tb!(UnboundMethod {
239 uctx: uctx.clone(),235 uctx,
240 value: value.clone(),236 value: value.clone(),
241 params: params.clone(),237 params: params.clone(),
242 name: name.clone()238 name,
243 }))?;239 }))?;
244 }240 }
245 }241 }
267 for member in members.iter() {263 for member in members.iter() {
268 match member {264 match member {
269 Member::Field(field) => {265 Member::Field(field) => {
270 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), &field)?266 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;
271 }267 }
272 Member::AssertStmt(stmt) => {268 Member::AssertStmt(stmt) => {
273 #[derive(Trace)]269 #[derive(Trace)]
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
3use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};3use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
44
5use crate::{5use crate::{
6 error::Error::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,6 error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed, val::equals, Context,
7 Result, Val,7 Result, Val,
8};8};
99
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
180 }180 }
181}181}
182182
183impl<A: ArgLike, S> sealed::Named for HashMap<IStr, A, S> {}183impl<V: ArgLike, S> sealed::Named for HashMap<IStr, V, S> {}
184impl<A: ArgLike, S> ArgsLike for HashMap<IStr, A, S> {184impl<V: ArgLike, S> ArgsLike for HashMap<IStr, V, S> {
185 fn unnamed_len(&self) -> usize {185 fn unnamed_len(&self) -> usize {
186 0186 0
187 }187 }
213 }213 }
214 }214 }
215}215}
216impl<A, S> OptionalContext for HashMap<IStr, A, S> where A: ArgLike + OptionalContext {}216impl<V, S> OptionalContext for HashMap<IStr, V, S> where V: ArgLike + OptionalContext {}
217217
218impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {218impl<A: ArgLike> ArgsLike for GcHashMap<IStr, A> {
219 fn unnamed_len(&self) -> usize {219 fn unnamed_len(&self) -> usize {
239 }239 }
240240
241 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {241 fn named_names(&self, handler: &mut dyn FnMut(&IStr)) {
242 self.0.named_names(handler)242 self.0.named_names(handler);
243 }243 }
244}244}
245245
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
7use super::{arglike::ArgsLike, builtin::BuiltinParam};7use super::{arglike::ArgsLike, builtin::BuiltinParam};
8use crate::{8use crate::{
9 destructure::destruct,9 destructure::destruct,
10 error::{Error::*, Result},10 error::{ErrorKind::*, Result},
11 evaluate_named,11 evaluate_named,
12 gc::GcHashMap,12 gc::GcHashMap,
13 tb, throw,13 tb, throw,
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
12use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};12use jrsonnet_parser::{SourceDirectory, SourceFile, SourcePath};
1313
14use crate::{14use crate::{
15 error::{15 error::{ErrorKind::*, Result},
16 Error::{self, *},
17 Result,
18 },
19 throw,16 throw,
20};17};
94 } else if let Some(d) = from.downcast_ref::<SourceDirectory>() {91 } else if let Some(d) = from.downcast_ref::<SourceDirectory>() {
95 d.path().to_owned()92 d.path().to_owned()
96 } else if from.is_default() {93 } else if from.is_default() {
97 current_dir().map_err(|e| Error::ImportIo(e.to_string()))?94 current_dir().map_err(|e| ImportIo(e.to_string()))?
98 } else {95 } else {
99 unreachable!("resolver can't return this path")96 unreachable!("resolver can't return this path")
100 };97 };
122 Err(e) if e.kind() == ErrorKind::NotFound => {119 Err(e) if e.kind() == ErrorKind::NotFound => {
123 throw!(AbsoluteImportFileNotFound(path.to_owned()))120 throw!(AbsoluteImportFileNotFound(path.to_owned()))
124 }121 }
125 Err(e) => throw!(Error::ImportIo(e.to_string())),122 Err(e) => throw!(ImportIo(e.to_string())),
126 };123 };
127 if meta.is_file() {124 if meta.is_file() {
128 Ok(SourcePath::new(SourceFile::new(125 Ok(SourcePath::new(SourceFile::new(
141 let path = if let Some(f) = id.downcast_ref::<SourceFile>() {138 let path = if let Some(f) = id.downcast_ref::<SourceFile>() {
142 f.path()139 f.path()
143 } else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {140 } else if id.downcast_ref::<SourceDirectory>().is_some() || id.is_default() {
144 throw!(Error::ImportIsADirectory(id.clone()))141 throw!(ImportIsADirectory(id.clone()))
145 } else {142 } else {
146 unreachable!("other types are not supported in resolve");143 unreachable!("other types are not supported in resolve");
147 };144 };
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
51pub mod gc;51pub mod gc;
52mod import;52mod import;
53mod integrations;53mod integrations;
54pub mod manifest;
54mod map;55mod map;
55mod obj;56mod obj;
56pub mod stack;57pub mod stack;
6970
70pub use ctx::*;71pub use ctx::*;
71pub use dynamic::*;72pub use dynamic::*;
72pub use error::{Error::*, LocError, Result, ResultExt};73pub use error::{Error, ErrorKind::*, Result, ResultExt};
73pub use evaluate::*;74pub use evaluate::*;
74use function::CallLocation;75use function::CallLocation;
75use gc::{GcHashMap, TraceBox};76use gc::{GcHashMap, TraceBox};
82pub use obj::*;83pub use obj::*;
83use stack::check_depth;84use stack::check_depth;
84pub use tla::apply_tla;85pub use tla::apply_tla;
85pub use val::{ManifestFormat, Thunk, Val};86pub use val::{Thunk, Val};
8687
87/// Thunk without bound `super`/`this`88/// Thunk without bound `super`/`this`
88/// object inheritance may be overriden multiple times, and will be fixed only on field read89/// object inheritance may be overriden multiple times, and will be fixed only on field read
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
11use rustc_hash::FxHashMap;11use rustc_hash::FxHashMap;
1212
13use crate::{13use crate::{
14 error::{Error::*, LocError},14 error::{Error, ErrorKind::*},
15 function::CallLocation,15 function::CallLocation,
16 gc::{GcHashMap, GcHashSet, TraceBox},16 gc::{GcHashMap, GcHashSet, TraceBox},
17 operator::evaluate_add_op,17 operator::evaluate_add_op,
115 Cached(Val),115 Cached(Val),
116 NotFound,116 NotFound,
117 Pending,117 Pending,
118 Errored(LocError),118 Errored(Error),
119}119}
120120
121#[allow(clippy::module_name_repetitions)]121#[allow(clippy::module_name_repetitions)]
modifiedcrates/jrsonnet-evaluator/src/stack.rsdiffbeforeafterboth
1use std::{cell::Cell, marker::PhantomData};1use std::{cell::Cell, marker::PhantomData};
22
3use crate::error::{Error, LocError};3use crate::error::{Error, ErrorKind};
44
5struct StackLimit {5struct StackLimit {
6 max_stack_size: Cell<usize>,6 max_stack_size: Cell<usize>,
22}22}
2323
24pub struct StackOverflowError;24pub struct StackOverflowError;
25impl From<StackOverflowError> for Error {25impl From<StackOverflowError> for ErrorKind {
26 fn from(_: StackOverflowError) -> Self {26 fn from(_: StackOverflowError) -> Self {
27 Error::StackOverflow27 ErrorKind::StackOverflow
28 }28 }
29}29}
30impl From<StackOverflowError> for LocError {30impl From<StackOverflowError> for Error {
31 fn from(_: StackOverflowError) -> Self {31 fn from(_: StackOverflowError) -> Self {
32 Error::StackOverflow.into()32 ErrorKind::StackOverflow.into()
33 }33 }
34}34}
3535
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
6use jrsonnet_types::ValType;6use jrsonnet_types::ValType;
7use thiserror::Error;7use thiserror::Error;
88
9use crate::{error::Error::*, throw, typed::Typed, LocError, ObjValue, Result, Val};9use crate::{error::ErrorKind::*, throw, typed::Typed, Error, ObjValue, Result, Val};
1010
11#[derive(Debug, Clone, Error, Trace)]11#[derive(Debug, Clone, Error, Trace)]
12pub enum FormatError {12pub enum FormatError {
26 NoSuchFormatField(IStr),26 NoSuchFormatField(IStr),
27}27}
2828
29impl From<FormatError> for LocError {29impl From<FormatError> for Error {
30 fn from(e: FormatError) -> Self {30 fn from(e: FormatError) -> Self {
31 Self::new(Format(e))31 Self::new(Format(e))
32 }32 }
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
7use crate::{error::Result, function::CallLocation, State, Val};7use crate::{error::Result, function::CallLocation, State, Val};
88
9pub mod format;9pub mod format;
10pub mod manifest;
1110
12pub fn std_format(str: IStr, vals: Val) -> Result<String> {11pub fn std_format(str: IStr, vals: Val) -> Result<String> {
13 State::push(12 State::push(
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
6use jrsonnet_gcmodule::Trace;6use jrsonnet_gcmodule::Trace;
7use jrsonnet_parser::{CodeLocation, Source};7use jrsonnet_parser::{CodeLocation, Source};
88
9use crate::{error::Error, LocError};9use crate::{error::ErrorKind, Error};
1010
11/// The way paths should be displayed11/// The way paths should be displayed
12#[derive(Clone, Trace)]12#[derive(Clone, Trace)]
51 fn write_trace(51 fn write_trace(
52 &self,52 &self,
53 out: &mut dyn std::fmt::Write,53 out: &mut dyn std::fmt::Write,
54 error: &LocError,54 error: &Error,
55 ) -> Result<(), std::fmt::Error>;55 ) -> Result<(), std::fmt::Error>;
56 fn format(&self, error: &LocError) -> Result<String, std::fmt::Error> {56 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {
57 let mut out = String::new();57 let mut out = String::new();
58 self.write_trace(&mut out, error)?;58 self.write_trace(&mut out, error)?;
59 Ok(out)59 Ok(out)
107 fn write_trace(107 fn write_trace(
108 &self,108 &self,
109 out: &mut dyn std::fmt::Write,109 out: &mut dyn std::fmt::Write,
110 error: &LocError,110 error: &Error,
111 ) -> Result<(), std::fmt::Error> {111 ) -> Result<(), std::fmt::Error> {
112 write!(out, "{}", error.error())?;112 write!(out, "{}", error.error())?;
113 if let Error::ImportSyntaxError { path, error } = error.error() {113 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
114 use std::fmt::Write;114 use std::fmt::Write;
115115
116 writeln!(out)?;116 writeln!(out)?;
204 fn write_trace(204 fn write_trace(
205 &self,205 &self,
206 out: &mut dyn std::fmt::Write,206 out: &mut dyn std::fmt::Write,
207 error: &LocError,207 error: &Error,
208 ) -> Result<(), std::fmt::Error> {208 ) -> Result<(), std::fmt::Error> {
209 write!(out, "{}", error.error())?;209 write!(out, "{}", error.error())?;
210 for item in &error.trace().0 {210 for item in &error.trace().0 {
250 fn write_trace(250 fn write_trace(
251 &self,251 &self,
252 out: &mut dyn std::fmt::Write,252 out: &mut dyn std::fmt::Write,
253 error: &LocError,253 error: &Error,
254 ) -> Result<(), std::fmt::Error> {254 ) -> Result<(), std::fmt::Error> {
255 write!(out, "{}", error.error())?;255 write!(out, "{}", error.error())?;
256 if let Error::ImportSyntaxError { path, error } = error.error() {256 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {
257 writeln!(out)?;257 writeln!(out)?;
258 let offset = error.location.offset;258 let offset = error.location.offset;
259 let location = path259 let location = path
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
7use thiserror::Error;7use thiserror::Error;
88
9use crate::{9use crate::{
10 error::{Error, LocError, Result},10 error::{Error, ErrorKind, Result},
11 State, Val,11 State, Val,
12};12};
1313
26 )]26 )]
27 BoundsFailed(f64, Option<f64>, Option<f64>),27 BoundsFailed(f64, Option<f64>, Option<f64>),
28}28}
29impl From<TypeError> for LocError {29impl From<TypeError> for Error {
30 fn from(e: TypeError) -> Self {30 fn from(e: TypeError) -> Self {
31 Error::TypeError(e.into()).into()31 ErrorKind::TypeError(e.into()).into()
32 }32 }
33}33}
3434
39 Self(Box::new(e), ValuePathStack(Vec::new()))39 Self(Box::new(e), ValuePathStack(Vec::new()))
40 }40 }
41}41}
42impl From<TypeLocError> for LocError {42impl From<TypeLocError> for Error {
43 fn from(e: TypeLocError) -> Self {43 fn from(e: TypeLocError) -> Self {
44 Error::TypeError(e).into()44 ErrorKind::TypeError(e).into()
45 }45 }
46}46}
47impl Display for TypeLocError {47impl Display for TypeLocError {
92 State::push_description(error_reason, || match item() {92 State::push_description(error_reason, || match item() {
93 Ok(_) => Ok(()),93 Ok(_) => Ok(()),
94 Err(mut e) => {94 Err(mut e) => {
95 if let Error::TypeError(e) = &mut e.error_mut() {95 if let ErrorKind::TypeError(e) = &mut e.error_mut() {
96 (e.1).0.push(path());96 (e.1).0.push(path());
97 }97 }
98 Err(e)98 Err(e)
218 return Ok(());218 return Ok(());
219 }219 }
220 Err(e) => match e.error() {220 Err(e) => match e.error() {
221 Error::TypeError(e) => errors.push(e.clone()),221 ErrorKind::TypeError(e) => errors.push(e.clone()),
222 _ => return Err(e),222 _ => return Err(e),
223 },223 },
224 }224 }
233 return Ok(());233 return Ok(());
234 }234 }
235 Err(e) => match e.error() {235 Err(e) => match e.error() {
236 Error::TypeError(e) => errors.push(e.clone()),236 ErrorKind::TypeError(e) => errors.push(e.clone()),
237 _ => return Err(e),237 _ => return Err(e),
238 },238 },
239 }239 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
5use jrsonnet_types::ValType;5use jrsonnet_types::ValType;
66
7use crate::{7use crate::{
8 error::{Error::*, LocError},8 error::{Error, ErrorKind::*},
9 function::FuncVal,9 function::FuncVal,
10 gc::{GcHashMap, TraceBox},10 gc::{GcHashMap, TraceBox},
11 manifest::{ManifestFormat, ToStringFormat},
11 throw,12 throw,
12 typed::BoundedUsize,13 typed::BoundedUsize,
13 ObjValue, Result, Unbound, WeakObjValue,14 ObjValue, Result, Unbound, WeakObjValue,
21#[derive(Trace)]22#[derive(Trace)]
22enum ThunkInner<T: Trace> {23enum ThunkInner<T: Trace> {
23 Computed(T),24 Computed(T),
24 Errored(LocError),25 Errored(Error),
25 Waiting(TraceBox<dyn ThunkValue<Output = T>>),26 Waiting(TraceBox<dyn ThunkValue<Output = T>>),
26 Pending,27 Pending,
27}28}
119 }120 }
120}121}
121
122pub trait ManifestFormat {
123 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
124 fn manifest(&self, val: Val) -> Result<String> {
125 let mut out = String::new();
126 self.manifest_buf(val, &mut out)?;
127 Ok(out)
128 }
129}
130impl<T> ManifestFormat for Box<T>
131where
132 T: ManifestFormat + ?Sized,
133{
134 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
135 let inner = &**self;
136 inner.manifest_buf(val, buf)
137 }
138}
139impl<T> ManifestFormat for &'_ T
140where
141 T: ManifestFormat + ?Sized,
142{
143 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
144 let inner = &**self;
145 inner.manifest_buf(val, buf)
146 }
147}
148122
149#[derive(Debug, Clone, Trace)]123#[derive(Debug, Clone, Trace)]
150pub struct Slice {124pub struct Slice {
650 Self::Null => "null".into(),624 Self::Null => "null".into(),
651 Self::Str(s) => s.clone(),625 Self::Str(s) => s.clone(),
652 _ => self626 _ => self.manifest(ToStringFormat).map(IStr::from)?,
653 .manifest(crate::stdlib::manifest::ToStringFormat)
654 .map(IStr::from)?,
655 })627 })
656 }628 }
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
540 }540 }
541 } else {541 } else {
542 quote! {542 quote! {
543 <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| Error::NoSuchField(#name.into(), vec![]))?)?543 <#ty>::from_untyped(obj.get(#name.into())?.ok_or_else(|| ErrorKind::NoSuchField(#name.into(), vec![]))?)?
544 }544 }
545 };545 };
546546
638 use ::jrsonnet_evaluator::{638 use ::jrsonnet_evaluator::{
639 typed::{ComplexValType, Typed, TypedObj, CheckType},639 typed::{ComplexValType, Typed, TypedObj, CheckType},
640 Val, State,640 Val, State,
641 error::{LocError, Error, Result},641 error::{ErrorKind, Result as JrResult},
642 ObjValueBuilder, ObjValue,642 ObjValueBuilder, ObjValue,
643 };643 };
644644
645 #typed645 #typed
646646
647 impl TypedObj for #ident {647 impl TypedObj for #ident {
648 fn serialize(self, out: &mut ObjValueBuilder) -> Result<(), LocError> {648 fn serialize(self, out: &mut ObjValueBuilder) -> JrResult<()> {
649 #(#fields_serialize)*649 #(#fields_serialize)*
650650
651 Ok(())651 Ok(())
652 }652 }
653 fn parse(obj: &ObjValue) -> Result<Self, LocError> {653 fn parse(obj: &ObjValue) -> JrResult<Self> {
654 Ok(Self {654 Ok(Self {
655 #(#fields_parse)*655 #(#fields_parse)*
656 })656 })
modifiedcrates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth
450 fn imports() {450 fn imports() {
451 assert_eq!(451 assert_eq!(
452 parse!("import \"hello\""),452 parse!("import \"hello\""),
453 el!(Expr::Import("hello".into()), 0, 14),453 el!(Expr::Import(el!(Expr::Str("hello".into()), 7, 14)), 0, 14),
454 );454 );
455 assert_eq!(455 assert_eq!(
456 parse!("importstr \"garnish.txt\""),456 parse!("importstr \"garnish.txt\""),
457 el!(Expr::ImportStr("garnish.txt".into()), 0, 23)457 el!(
458 Expr::ImportStr(el!(Expr::Str("garnish.txt".into()), 10, 23)),
459 0,
460 23
461 )
458 );462 );
459 assert_eq!(463 assert_eq!(
460 parse!("importbin \"garnish.bin\""),464 parse!("importbin \"garnish.bin\""),
461 el!(Expr::ImportBin("garnish.bin".into()), 0, 23)465 el!(
466 Expr::ImportBin(el!(Expr::Str("garnish.bin".into()), 10, 23)),
467 0,
468 23
469 )
modifiedcrates/jrsonnet-stdlib/Cargo.tomldiffbeforeafterboth
7edition = "2021"7edition = "2021"
88
9[features]9[features]
10default = ["codegenerated-stdlib"]10default = ["codegenerated-stdlib", "exp-more-hashes"]
11# Speed-up initialization by generating code for parsed stdlib, instead11# Speed-up initialization by generating code for parsed stdlib, instead
12# of invoking parser for it12# of invoking parser for it
13codegenerated-stdlib = ["jrsonnet-parser/structdump"]13codegenerated-stdlib = ["jrsonnet-parser/structdump"]
14# Enables legacy `std.thisFile` support, at the cost of worse caching14# Enables legacy `std.thisFile` support, at the cost of worse caching
15legacy-this-file = []15legacy-this-file = []
16# Add order preservation flag to some functions16# Add order preservation flag to some functions
17exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]17exp-preserve-order = ["jrsonnet-evaluator/exp-preserve-order"]
18exp-more-hashes = ["sha2"]
1819
19[dependencies]20[dependencies]
20jrsonnet-evaluator.workspace = true21jrsonnet-evaluator.workspace = true
36# std.parseYaml, custom library fork is used for C++/golang compatibility37# std.parseYaml, custom library fork is used for C++/golang compatibility
37serde_yaml_with_quirks = "0.8.24"38serde_yaml_with_quirks = "0.8.24"
39
40sha2 = { version = "0.10.6", optional = true }
3841
39[build-dependencies]42[build-dependencies]
40jrsonnet-parser.workspace = true43jrsonnet-parser.workspace = true
modifiedcrates/jrsonnet-stdlib/build.rsdiffbeforeafterboth
19 {19 {
20 let out_dir = env::var("OUT_DIR").unwrap();20 let out_dir = env::var("OUT_DIR").unwrap();
21 let dest_path = Path::new(&out_dir).join("stdlib.rs");21 let dest_path = Path::new(&out_dir).join("stdlib.rs");
22 let mut f = File::create(&dest_path).unwrap();22 let mut f = File::create(dest_path).unwrap();
23 f.write_all(23 f.write_all(
24 ("#[allow(clippy::redundant_clone)]".to_owned() + &v.to_string())24 ("#[allow(clippy::redundant_clone)]".to_owned() + &v.to_string())
25 .replace(';', ";\n")25 .replace(';', ";\n")
modifiedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
1use jrsonnet_evaluator::{1use jrsonnet_evaluator::{
2 error::{Error::RuntimeError, Result},2 error::{ErrorKind::RuntimeError, Result},
3 function::builtin,3 function::builtin,
4 typed::{Either, Either2},4 typed::{Either, Either2},
5 IBytes, IStr,5 IBytes, IStr,
modifiedcrates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth
5 Ok(format!("{:x}", md5::compute(str.as_bytes())))5 Ok(format!("{:x}", md5::compute(str.as_bytes())))
6}6}
7
8#[cfg(feature = "exp-more-hashes")]
9#[builtin]
10pub fn builtin_sha256(str: IStr) -> Result<String> {
11 use sha2::digest::Digest;
12 Ok(format!("{:?}", sha2::Sha256::digest(str.as_bytes())))
13}
714
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
5};5};
66
7use jrsonnet_evaluator::{7use jrsonnet_evaluator::{
8 error::{Error::*, Result},8 error::{ErrorKind::*, Result},
9 function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},9 function::{builtin::Builtin, CallLocation, FuncVal, TlaArg},
10 gc::{GcHashMap, TraceBox},10 gc::{GcHashMap, TraceBox},
11 tb,11 tb,
101 ("sort", builtin_sort::INST),101 ("sort", builtin_sort::INST),
102 // Hash102 // Hash
103 ("md5", builtin_md5::INST),103 ("md5", builtin_md5::INST),
104 #[cfg(feature = "exp-more-hashes")]
105 ("sha256", builtin_sha256::INST),
104 // Encoding106 // Encoding
105 ("encodeUTF8", builtin_encode_utf8::INST),107 ("encodeUTF8", builtin_encode_utf8::INST),
106 ("decodeUTF8", builtin_decode_utf8::INST),108 ("decodeUTF8", builtin_decode_utf8::INST),
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
1use std::{cell::RefCell, rc::Rc};1use std::{cell::RefCell, rc::Rc};
22
3use jrsonnet_evaluator::{3use jrsonnet_evaluator::{
4 error::{Error::*, Result},4 error::{ErrorKind::*, Result},
5 function::{builtin, ArgLike, CallLocation, FuncVal},5 function::{builtin, ArgLike, CallLocation, FuncVal},
6 throw,6 throw,
7 typed::{Any, Either2, Either4},7 typed::{Any, Either2, Either4},
modifiedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
1use jrsonnet_evaluator::{1use jrsonnet_evaluator::{
2 error::{Error::RuntimeError, Result},2 error::{ErrorKind::RuntimeError, Result},
3 function::builtin,3 function::builtin,
4 typed::Any,4 typed::Any,
5 IStr, Val,5 IStr, Val,
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
1use jrsonnet_evaluator::{1use jrsonnet_evaluator::{
2 error::{Error::*, Result},2 error::{ErrorKind::*, Result},
3 function::builtin,3 function::builtin,
4 typed::{Either2, VecVal, M1},4 typed::{Either2, VecVal, M1},
5 val::ArrValue,5 val::ArrValue,
modifiedtests/tests/common.rsdiffbeforeafterboth
29macro_rules! ensure_val_eq {29macro_rules! ensure_val_eq {
30 ($a:expr, $b:expr) => {{30 ($a:expr, $b:expr) => {{
31 if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {31 if !::jrsonnet_evaluator::val::equals(&$a.clone(), &$b.clone())? {
32 use ::jrsonnet_evaluator::stdlib::manifest::JsonFormat;32 use ::jrsonnet_evaluator::manifest::JsonFormat;
33 ::jrsonnet_evaluator::throw!(33 ::jrsonnet_evaluator::throw!(
34 "assertion failed: a != b\na={:#?}\nb={:#?}",34 "assertion failed: a != b\na={:#?}\nb={:#?}",
35 $a.manifest(JsonFormat::default())?,35 $a.manifest(JsonFormat::default())?,
modifiedtests/tests/golden.rsdiffbeforeafterboth
4};4};
55
6use jrsonnet_evaluator::{6use jrsonnet_evaluator::{
7 stdlib::manifest::JsonFormat,7 manifest::JsonFormat,
8 trace::{CompactFormat, PathResolver, TraceFormat},8 trace::{CompactFormat, PathResolver, TraceFormat},
9 FileImportResolver, State,9 FileImportResolver, State,
10};10};