difftreelog
Merge pull request #146 from CertainLach/fix/tests
in: master
Fix failing CI for tests and lints
22 files changed
cmds/jrsonnet-fmt/src/comments.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/comments.rs
+++ b/cmds/jrsonnet-fmt/src/comments.rs
@@ -72,7 +72,7 @@
if matches!(loc, CommentLocation::ItemInline) {
p!(pi: str(" "));
}
- p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */"))
+ p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */") nl)
} else if !lines.is_empty() {
fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {
let offset = a
cmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/main.rs
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -372,8 +372,8 @@
return p!(new: str("{ }"));
}
let mut pi = p!(new: str("{") >i nl);
- for mem in children.into_iter() {
- if mem.should_start_with_newline {
+ for (i, mem) in children.into_iter().enumerate() {
+ if mem.should_start_with_newline && i != 0 {
p!(pi: nl);
}
p!(pi: items(format_comments(&mem.before_trivia, CommentLocation::AboveItem)));
crates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -6,7 +6,7 @@
};
use jrsonnet_stdlib::{TomlFormat, YamlFormat};
-#[derive(Clone, ValueEnum)]
+#[derive(Clone, Copy, ValueEnum)]
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
String,
@@ -18,9 +18,11 @@
#[derive(Parser)]
#[clap(next_help_heading = "MANIFESTIFICATION OUTPUT")]
pub struct ManifestOpts {
- /// Output format, wraps resulting value to corresponding std.manifest call.
- #[clap(long, short = 'f', default_value = "json")]
- format: ManifestFormatName,
+ /// Output format, wraps resulting value to corresponding std.manifest call
+ ///
+ /// [default: json, yaml when -y is used]
+ #[clap(long, short = 'f')]
+ format: Option<ManifestFormatName>,
/// Expect plain string as output.
/// Mutually exclusive with `--format`
#[clap(long, short = 'S', conflicts_with = "format")]
@@ -29,7 +31,9 @@
#[clap(long, short = 'y', conflicts_with = "string")]
yaml_stream: bool,
/// Number of spaces to pad output manifest with.
- /// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml/toml]
+ /// `0` for hard tabs, `-1` for single line output
+ ///
+ /// [default: 3 for json, 2 for yaml/toml]
#[clap(long)]
line_padding: Option<usize>,
/// Preserve order in object manifestification
@@ -44,7 +48,12 @@
} else {
#[cfg(feature = "exp-preserve-order")]
let preserve_order = self.preserve_order;
- match self.format {
+ let format = match self.format {
+ Some(v) => v,
+ None if self.yaml_stream => ManifestFormatName::Yaml,
+ None => ManifestFormatName::Json,
+ };
+ match format {
ManifestFormatName::String => Box::new(ToStringFormat),
ManifestFormatName::Json => Box::new(JsonFormat::cli(
self.line_padding.unwrap_or(3),
crates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -372,7 +372,7 @@
pub fn new_inclusive(start: i32, end: i32) -> Self {
Self { start, end }
}
- fn range(&self) -> impl Iterator<Item = i32> + ExactSizeIterator + DoubleEndedIterator {
+ fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {
WithExactSize(
self.start..=self.end,
(self.end as usize)
@@ -461,7 +461,7 @@
ArrayThunk::Waiting(..) => {}
};
- let ArrayThunk::Waiting(_) =
+ let ArrayThunk::Waiting(()) =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
else {
unreachable!()
@@ -508,7 +508,7 @@
match &self.cached.borrow()[index] {
ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
- ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+ ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}
};
Some(Thunk::new(ArrayElement {
@@ -597,9 +597,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
Some(self.obj.get_lazy_or_bail(key.clone()))
}
@@ -649,9 +647,7 @@
}
fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
- let Some(key) = self.keys.get(index) else {
- return None;
- };
+ let key = self.keys.get(index)?;
// Nothing can fail in the key part, yet value is still
// lazy-evaluated
Some(Thunk::evaluated(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -89,7 +89,7 @@
specs: &[CompSpec],
callback: &mut impl FnMut(Context) -> Result<()>,
) -> Result<()> {
- match specs.get(0) {
+ match specs.first() {
None => callback(ctx)?,
Some(CompSpec::IfSpec(IfSpecData(cond))) => {
if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -6,8 +6,8 @@
use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
use crate::{gc::TraceBox, tb, Context, Result, Val};
-/// Can't have str | IStr, because constant BuiltinParam causes
-/// E0492: constant functions cannot refer to interior mutable data
+/// Can't have `str` | `IStr`, because constant `BuiltinParam` causes
+/// `E0492: constant functions cannot refer to interior mutable data`
#[derive(Clone, Trace)]
pub struct ParamName(Option<Cow<'static, str>>);
impl ParamName {
@@ -27,10 +27,9 @@
}
impl PartialEq<IStr> for ParamName {
fn eq(&self, other: &IStr) -> bool {
- match &self.0 {
- Some(s) => s.as_bytes() == other.as_bytes(),
- None => false,
- }
+ self.0
+ .as_ref()
+ .map_or(false, |s| s.as_bytes() == other.as_bytes())
}
}
@@ -87,7 +86,7 @@
params: params
.into_iter()
.map(|n| BuiltinParam {
- name: ParamName::new_dynamic(n.to_string()),
+ name: ParamName::new_dynamic(n),
has_default: false,
})
.collect(),
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -159,11 +159,11 @@
Val::Null => serializer.serialize_none(),
Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
Val::Num(n) => {
- if n.fract() != 0.0 {
- serializer.serialize_f64(*n)
- } else {
+ if n.fract() == 0.0 {
let n = *n as i64;
serializer.serialize_i64(n)
+ } else {
+ serializer.serialize_f64(*n)
}
}
#[cfg(feature = "exp-bigint")]
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -41,10 +41,12 @@
clippy::missing_const_for_fn,
// too many false-positives with .expect() calls
clippy::missing_panics_doc,
- // false positive for IStr type. There is an configuration option for
- // such cases, but it doesn't work:
- // https://github.com/rust-lang/rust-clippy/issues/9801
- clippy::mutable_key_type,
+ // false positive for IStr type. There is an configuration option for
+ // such cases, but it doesn't work:
+ // https://github.com/rust-lang/rust-clippy/issues/9801
+ clippy::mutable_key_type,
+ // false positives
+ clippy::redundant_pub_crate,
)]
// For jrsonnet-macros
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -175,6 +175,8 @@
manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
Ok(out)
}
+
+#[allow(clippy::too_many_lines)]
fn manifest_json_ex_buf(
val: &Val,
buf: &mut String,
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -171,7 +171,7 @@
// .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
// .field("value_cache", &self.value_cache)
- .finish()
+ .finish_non_exhaustive()
}
}
@@ -347,7 +347,7 @@
out.with_super(self);
let mut member = out.field(key);
if value.flags.add() {
- member = member.add()
+ member = member.add();
}
if let Some(loc) = value.location {
member = member.with_location(loc);
@@ -395,7 +395,7 @@
pub fn get(&self, key: IStr) -> Result<Option<Val>> {
self.run_assertions()?;
- self.get_for(key, self.0.this().unwrap_or(self.clone()))
+ self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
}
pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
@@ -474,7 +474,7 @@
type Output = Val;
fn get(self: Box<Self>) -> Result<Self::Output> {
- Ok(self.obj.get_or_bail(self.key)?)
+ self.obj.get_or_bail(self.key)
}
}
@@ -495,7 +495,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
@@ -634,7 +634,7 @@
SuperDepth::default(),
&mut |depth, index, name, visibility| {
let new_sort_key = FieldSortKey::new(depth, index);
- let entry = out.entry(name.clone());
+ let entry = out.entry(name);
let (visible, _) = entry.or_insert((true, new_sort_key));
match visibility {
Visibility::Normal => {}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -248,7 +248,7 @@
let (cflags, str) = try_parse_cflags(str)?;
let (width, str) = try_parse_field_width(str)?;
let (precision, str) = try_parse_precision(str)?;
- let (_, str) = try_parse_length_modifier(str)?;
+ let ((), str) = try_parse_length_modifier(str)?;
let (convtype, str) = parse_conversion_type(str)?;
Ok((
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -449,25 +449,21 @@
}
fn from_untyped(value: Val) -> Result<Self> {
- match &value {
- Val::Arr(a) => {
- if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
- return Ok(bytes.0.as_slice().into());
- };
- <Self as Typed>::TYPE.check(&value)?;
- // Any::downcast_ref::<ByteArray>(&a);
- let mut out = Vec::with_capacity(a.len());
- for e in a.iter() {
- let r = e?;
- out.push(u8::from_untyped(r)?);
- }
- Ok(out.as_slice().into())
- }
- _ => {
- <Self as Typed>::TYPE.check(&value)?;
- unreachable!()
- }
+ let Val::Arr(a) = &value else {
+ <Self as Typed>::TYPE.check(&value)?;
+ unreachable!()
+ };
+ if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
+ return Ok(bytes.0.as_slice().into());
+ };
+ <Self as Typed>::TYPE.check(&value)?;
+ // Any::downcast_ref::<ByteArray>(&a);
+ let mut out = Vec::with_capacity(a.len());
+ for e in a.iter() {
+ let r = e?;
+ out.push(u8::from_untyped(r)?);
}
+ Ok(out.as_slice().into())
}
}
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth1use std::{fmt::Display, rc::Rc};23mod conversions;4pub use conversions::*;5use jrsonnet_gcmodule::Trace;6pub use jrsonnet_types::{ComplexValType, ValType};7use thiserror::Error;89use crate::{10 error::{Error, ErrorKind, Result},11 State, Val,12};1314#[derive(Debug, Error, Clone, Trace)]15pub enum TypeError {16 #[error("expected {0}, got {1}")]17 ExpectedGot(ComplexValType, ValType),18 #[error("missing property {0} from {1}")]19 MissingProperty(#[trace(skip)] Rc<str>, ComplexValType),20 #[error("every failed from {0}:\n{1}")]21 UnionFailed(ComplexValType, TypeLocErrorList),22 #[error(23 "number out of bounds: {0} not in {}..{}",24 .1.map(|v|v.to_string()).unwrap_or_default(),25 .2.map(|v|v.to_string()).unwrap_or_default(),26 )]27 BoundsFailed(f64, Option<f64>, Option<f64>),28}29impl From<TypeError> for Error {30 fn from(e: TypeError) -> Self {31 ErrorKind::TypeError(e.into()).into()32 }33}3435#[derive(Debug, Clone, Trace)]36pub struct TypeLocError(Box<TypeError>, ValuePathStack);37impl From<TypeError> for TypeLocError {38 fn from(e: TypeError) -> Self {39 Self(Box::new(e), ValuePathStack(Vec::new()))40 }41}42impl From<TypeLocError> for Error {43 fn from(e: TypeLocError) -> Self {44 ErrorKind::TypeError(e).into()45 }46}47impl Display for TypeLocError {48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {49 write!(f, "{}", self.0)?;50 if !(self.1).0.is_empty() {51 write!(f, " at {}", self.1)?;52 }53 Ok(())54 }55}5657#[derive(Debug, Clone, Trace)]58pub struct TypeLocErrorList(Vec<TypeLocError>);59impl Display for TypeLocErrorList {60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61 use std::fmt::Write;62 let mut out = String::new();63 for (i, err) in self.0.iter().enumerate() {64 if i != 0 {65 writeln!(f)?;66 }67 out.clear();68 write!(out, "{err}")?;6970 for (i, line) in out.lines().enumerate() {71 if line.trim().is_empty() {72 continue;73 }74 if i == 0 {75 write!(f, " - ")?;76 } else {77 writeln!(f)?;78 write!(f, " ")?;79 }80 write!(f, "{line}")?;81 }82 }83 Ok(())84 }85}8687fn push_type_description(88 error_reason: impl Fn() -> String,89 path: impl Fn() -> ValuePathItem,90 item: impl Fn() -> Result<()>,91) -> Result<()> {92 State::push_description(error_reason, || match item() {93 Ok(_) => Ok(()),94 Err(mut e) => {95 if let ErrorKind::TypeError(e) = &mut e.error_mut() {96 (e.1).0.push(path());97 }98 Err(e)99 }100 })101}102103// TODO: check_fast for fast path of union type checking104pub trait CheckType {105 fn check(&self, value: &Val) -> Result<()>;106}107108impl CheckType for ValType {109 fn check(&self, value: &Val) -> Result<()> {110 let got = value.value_type();111 if got != *self {112 let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();113 return Err(loc_error.into());114 }115 Ok(())116 }117}118119#[derive(Clone, Debug, Trace)]120enum ValuePathItem {121 Field(#[trace(skip)] Rc<str>),122 Index(u64),123}124impl Display for ValuePathItem {125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {126 match self {127 Self::Field(name) => write!(f, ".{name:?}")?,128 Self::Index(idx) => write!(f, "[{idx}]")?,129 }130 Ok(())131 }132}133134#[derive(Clone, Debug, Trace)]135struct ValuePathStack(Vec<ValuePathItem>);136impl Display for ValuePathStack {137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {138 write!(f, "self")?;139 for elem in self.0.iter().rev() {140 write!(f, "{elem}")?;141 }142 Ok(())143 }144}145146impl CheckType for ComplexValType {147 #[allow(clippy::too_many_lines)]148 fn check(&self, value: &Val) -> Result<()> {149 match self {150 Self::Any => Ok(()),151 Self::Simple(t) => t.check(value),152 Self::Char => match value {153 Val::Str(s) if s.len() == 1 || s.clone().into_flat().chars().count() == 1 => Ok(()),154 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),155 },156 Self::BoundedNumber(from, to) => {157 if let Val::Num(n) = value {158 if from.map(|from| from > *n).unwrap_or(false)159 || to.map(|to| to < *n).unwrap_or(false)160 {161 return Err(TypeError::BoundsFailed(*n, *from, *to).into());162 }163 Ok(())164 } else {165 Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())166 }167 }168 Self::Array(elem_type) => match value {169 Val::Arr(a) => {170 for (i, item) in a.iter().enumerate() {171 push_type_description(172 || format!("array index {i}"),173 || ValuePathItem::Index(i as u64),174 || elem_type.check(&item.clone()?),175 )?;176 }177 Ok(())178 }179 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),180 },181 Self::ArrayRef(elem_type) => match value {182 Val::Arr(a) => {183 for (i, item) in a.iter().enumerate() {184 push_type_description(185 || format!("array index {i}"),186 || ValuePathItem::Index(i as u64),187 || elem_type.check(&item.clone()?),188 )?;189 }190 Ok(())191 }192 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),193 },194 Self::AttrsOf(a) => match value {195 Val::Obj(o) => {196 for (_key, value) in o.iter(197 #[cfg(feature = "exp-preserve-order")]198 false,199 ) {200 let value = value?;201 a.check(&value)?;202 }203 Ok(())204 }205 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),206 },207 Self::ObjectRef(elems) => match value {208 Val::Obj(obj) => {209 for (k, v) in *elems {210 if let Some(got_v) = obj.get((*k).into())? {211 push_type_description(212 || format!("property {k}"),213 || ValuePathItem::Field((*k).into()),214 || v.check(&got_v),215 )?;216 } else {217 return Err(218 TypeError::MissingProperty((*k).into(), self.clone()).into()219 );220 }221 }222 Ok(())223 }224 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),225 },226 Self::Union(types) => {227 let mut errors = Vec::new();228 for ty in types {229 match ty.check(value) {230 Ok(()) => {231 return Ok(());232 }233 Err(e) => match e.error() {234 ErrorKind::TypeError(e) => errors.push(e.clone()),235 _ => return Err(e),236 },237 }238 }239 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())240 }241 Self::UnionRef(types) => {242 let mut errors = Vec::new();243 for ty in *types {244 match ty.check(value) {245 Ok(()) => {246 return Ok(());247 }248 Err(e) => match e.error() {249 ErrorKind::TypeError(e) => errors.push(e.clone()),250 _ => return Err(e),251 },252 }253 }254 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())255 }256 Self::Sum(types) => {257 for ty in types {258 ty.check(value)?;259 }260 Ok(())261 }262 Self::SumRef(types) => {263 for ty in *types {264 ty.check(value)?;265 }266 Ok(())267 }268 Self::Lazy(_lazy) => Ok(()),269 }270 }271}1use std::{fmt::Display, rc::Rc};23mod conversions;4pub use conversions::*;5use jrsonnet_gcmodule::Trace;6pub use jrsonnet_types::{ComplexValType, ValType};7use thiserror::Error;89use crate::{10 error::{Error, ErrorKind, Result},11 State, Val,12};1314#[derive(Debug, Error, Clone, Trace)]15pub enum TypeError {16 #[error("expected {0}, got {1}")]17 ExpectedGot(ComplexValType, ValType),18 #[error("missing property {0} from {1}")]19 MissingProperty(#[trace(skip)] Rc<str>, ComplexValType),20 #[error("every failed from {0}:\n{1}")]21 UnionFailed(ComplexValType, TypeLocErrorList),22 #[error(23 "number out of bounds: {0} not in {}..{}",24 .1.map(|v|v.to_string()).unwrap_or_default(),25 .2.map(|v|v.to_string()).unwrap_or_default(),26 )]27 BoundsFailed(f64, Option<f64>, Option<f64>),28}29impl From<TypeError> for Error {30 fn from(e: TypeError) -> Self {31 ErrorKind::TypeError(e.into()).into()32 }33}3435#[derive(Debug, Clone, Trace)]36pub struct TypeLocError(Box<TypeError>, ValuePathStack);37impl From<TypeError> for TypeLocError {38 fn from(e: TypeError) -> Self {39 Self(Box::new(e), ValuePathStack(Vec::new()))40 }41}42impl From<TypeLocError> for Error {43 fn from(e: TypeLocError) -> Self {44 ErrorKind::TypeError(e).into()45 }46}47impl Display for TypeLocError {48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {49 write!(f, "{}", self.0)?;50 if !(self.1).0.is_empty() {51 write!(f, " at {}", self.1)?;52 }53 Ok(())54 }55}5657#[derive(Debug, Clone, Trace)]58pub struct TypeLocErrorList(Vec<TypeLocError>);59impl Display for TypeLocErrorList {60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61 use std::fmt::Write;62 let mut out = String::new();63 for (i, err) in self.0.iter().enumerate() {64 if i != 0 {65 writeln!(f)?;66 }67 out.clear();68 write!(out, "{err}")?;6970 for (i, line) in out.lines().enumerate() {71 if line.trim().is_empty() {72 continue;73 }74 if i == 0 {75 write!(f, " - ")?;76 } else {77 writeln!(f)?;78 write!(f, " ")?;79 }80 write!(f, "{line}")?;81 }82 }83 Ok(())84 }85}8687fn push_type_description(88 error_reason: impl Fn() -> String,89 path: impl Fn() -> ValuePathItem,90 item: impl Fn() -> Result<()>,91) -> Result<()> {92 State::push_description(error_reason, || match item() {93 Ok(()) => Ok(()),94 Err(mut e) => {95 if let ErrorKind::TypeError(e) = &mut e.error_mut() {96 (e.1).0.push(path());97 }98 Err(e)99 }100 })101}102103// TODO: check_fast for fast path of union type checking104pub trait CheckType {105 fn check(&self, value: &Val) -> Result<()>;106}107108impl CheckType for ValType {109 fn check(&self, value: &Val) -> Result<()> {110 let got = value.value_type();111 if got != *self {112 let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();113 return Err(loc_error.into());114 }115 Ok(())116 }117}118119#[derive(Clone, Debug, Trace)]120enum ValuePathItem {121 Field(#[trace(skip)] Rc<str>),122 Index(u64),123}124impl Display for ValuePathItem {125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {126 match self {127 Self::Field(name) => write!(f, ".{name:?}")?,128 Self::Index(idx) => write!(f, "[{idx}]")?,129 }130 Ok(())131 }132}133134#[derive(Clone, Debug, Trace)]135struct ValuePathStack(Vec<ValuePathItem>);136impl Display for ValuePathStack {137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {138 write!(f, "self")?;139 for elem in self.0.iter().rev() {140 write!(f, "{elem}")?;141 }142 Ok(())143 }144}145146impl CheckType for ComplexValType {147 #[allow(clippy::too_many_lines)]148 fn check(&self, value: &Val) -> Result<()> {149 match self {150 Self::Any => Ok(()),151 Self::Simple(t) => t.check(value),152 Self::Char => match value {153 Val::Str(s) if s.len() == 1 || s.clone().into_flat().chars().count() == 1 => Ok(()),154 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),155 },156 Self::BoundedNumber(from, to) => {157 if let Val::Num(n) = value {158 if from.map(|from| from > *n).unwrap_or(false)159 || to.map(|to| to < *n).unwrap_or(false)160 {161 return Err(TypeError::BoundsFailed(*n, *from, *to).into());162 }163 Ok(())164 } else {165 Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())166 }167 }168 Self::Array(elem_type) => match value {169 Val::Arr(a) => {170 for (i, item) in a.iter().enumerate() {171 push_type_description(172 || format!("array index {i}"),173 || ValuePathItem::Index(i as u64),174 || elem_type.check(&item.clone()?),175 )?;176 }177 Ok(())178 }179 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),180 },181 Self::ArrayRef(elem_type) => match value {182 Val::Arr(a) => {183 for (i, item) in a.iter().enumerate() {184 push_type_description(185 || format!("array index {i}"),186 || ValuePathItem::Index(i as u64),187 || elem_type.check(&item.clone()?),188 )?;189 }190 Ok(())191 }192 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),193 },194 Self::AttrsOf(a) => match value {195 Val::Obj(o) => {196 for (_key, value) in o.iter(197 #[cfg(feature = "exp-preserve-order")]198 false,199 ) {200 let value = value?;201 a.check(&value)?;202 }203 Ok(())204 }205 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),206 },207 Self::ObjectRef(elems) => match value {208 Val::Obj(obj) => {209 for (k, v) in *elems {210 if let Some(got_v) = obj.get((*k).into())? {211 push_type_description(212 || format!("property {k}"),213 || ValuePathItem::Field((*k).into()),214 || v.check(&got_v),215 )?;216 } else {217 return Err(218 TypeError::MissingProperty((*k).into(), self.clone()).into()219 );220 }221 }222 Ok(())223 }224 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),225 },226 Self::Union(types) => {227 let mut errors = Vec::new();228 for ty in types {229 match ty.check(value) {230 Ok(()) => {231 return Ok(());232 }233 Err(e) => match e.error() {234 ErrorKind::TypeError(e) => errors.push(e.clone()),235 _ => return Err(e),236 },237 }238 }239 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())240 }241 Self::UnionRef(types) => {242 let mut errors = Vec::new();243 for ty in *types {244 match ty.check(value) {245 Ok(()) => {246 return Ok(());247 }248 Err(e) => match e.error() {249 ErrorKind::TypeError(e) => errors.push(e.clone()),250 _ => return Err(e),251 },252 }253 }254 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())255 }256 Self::Sum(types) => {257 for ty in types {258 ty.check(value)?;259 }260 Ok(())261 }262 Self::SumRef(types) => {263 for ty in *types {264 ty.check(value)?;265 }266 Ok(())267 }268 Self::Lazy(_lazy) => Ok(()),269 }270 }271}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -351,6 +351,8 @@
}
}
impl PartialEq for StrValue {
+ // False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.
+ #[allow(clippy::unconditional_recursion)]
fn eq(&self, other: &Self) -> bool {
let a = self.clone().into_flat();
let b = other.clone().into_flat();
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -6,7 +6,7 @@
#![warn(clippy::pedantic, clippy::nursery)]
#![allow(clippy::missing_const_for_fn)]
use std::{
- borrow::{Borrow, Cow},
+ borrow::Cow,
cell::RefCell,
fmt::{self, Display},
hash::{BuildHasherDefault, Hash, Hasher},
@@ -14,7 +14,7 @@
str,
};
-use hashbrown::HashMap;
+use hashbrown::{hash_map::RawEntryMut, HashMap};
use jrsonnet_gcmodule::Trace;
use rustc_hash::FxHasher;
@@ -57,17 +57,6 @@
}
}
-impl Borrow<str> for IStr {
- fn borrow(&self) -> &str {
- self.as_str()
- }
-}
-impl Borrow<[u8]> for IStr {
- fn borrow(&self) -> &[u8] {
- self.as_bytes()
- }
-}
-
impl PartialEq for IStr {
fn eq(&self, other: &Self) -> bool {
// all IStr should be inlined into same pool
@@ -142,12 +131,6 @@
type Target = [u8];
fn deref(&self) -> &Self::Target {
- self.0.as_slice()
- }
-}
-
-impl Borrow<[u8]> for IBytes {
- fn borrow(&self) -> &[u8] {
self.0.as_slice()
}
}
@@ -285,9 +268,9 @@
let mut pool = pool.borrow_mut();
let entry = pool.raw_entry_mut().from_key(bytes);
match entry {
- hashbrown::hash_map::RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
- hashbrown::hash_map::RawEntryMut::Vacant(e) => {
- let (k, _) = e.insert(Inner::new_bytes(bytes), ());
+ RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
+ RawEntryMut::Vacant(e) => {
+ let (k, ()) = e.insert(Inner::new_bytes(bytes), ());
IBytes(k.clone())
}
}
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -374,6 +374,7 @@
fn params(&self) -> &[BuiltinParam] {
PARAMS
}
+ #[allow(unused_variable)]
fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;
crates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -39,5 +39,5 @@
let bytes = STANDARD
.decode(str.as_bytes())
.map_err(|e| runtime_error!("invalid base64: {e}"))?;
- Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
+ String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))
}
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -134,6 +134,14 @@
buf.push_str(&options.padding);
buf.push_str(line);
}
+ } else if s.contains('\n') {
+ buf.push_str("|-");
+ for line in s.split('\n') {
+ buf.push('\n');
+ buf.push_str(cur_padding);
+ buf.push_str(&options.padding);
+ buf.push_str(line);
+ }
} else if !options.quote_keys && !yaml_needs_quotes(&s) {
buf.push_str(&s);
} else {
crates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
.ext_natives
.get(&x)
.cloned()
- .map_or(Val::Null, |v| Val::Func(v))
+ .map_or(Val::Null, Val::Func)
}
#[builtin(fields(
flake.lockdiffbeforeafterboth--- a/flake.lock
+++ b/flake.lock
@@ -5,11 +5,11 @@
"systems": "systems"
},
"locked": {
- "lastModified": 1694529238,
- "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
+ "lastModified": 1705309234,
+ "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
"owner": "numtide",
"repo": "flake-utils",
- "rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
+ "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
"type": "github"
},
"original": {
@@ -20,11 +20,11 @@
},
"nixpkgs": {
"locked": {
- "lastModified": 1701376520,
- "narHash": "sha256-U3iGiOZqgu7wvVzgfoQzGGFMqNsDj/q/6zPIjCy7ajg=",
+ "lastModified": 1705391267,
+ "narHash": "sha256-gGVm9QudiRtYTX8PN9cTTy7uuJcL4I2lRMoPx496kXk=",
"owner": "nixos",
"repo": "nixpkgs",
- "rev": "c74cc3c3db2ed5e68895953d75c397797d499133",
+ "rev": "41a9a7f170c740acb24f3390323877d11c69d5ee",
"type": "github"
},
"original": {
@@ -50,11 +50,11 @@
]
},
"locked": {
- "lastModified": 1701310566,
- "narHash": "sha256-CL9J3xUR2Ejni4LysrEGX0IdO+Y4BXCiH/By0lmF3eQ=",
+ "lastModified": 1705371439,
+ "narHash": "sha256-P1kulUXpYWkcrjiX3sV4j8ACJZh9XXSaaD+jDLBDLKo=",
"owner": "oxalica",
"repo": "rust-overlay",
- "rev": "6d3c6e185198b8bf7ad639f22404a75aa9a09bff",
+ "rev": "b21f3c0d5bf0f0179f5f0140e8e0cd099618bd04",
"type": "github"
},
"original": {
flake.nixdiffbeforeafterboth--- a/flake.nix
+++ b/flake.nix
@@ -25,14 +25,14 @@
lib = pkgs.lib;
rust =
(pkgs.rustChannelOf {
- date = "2023-10-28";
+ date = "2024-01-10";
channel = "nightly";
})
.default
.override {
extensions = ["rust-src" "miri" "rust-analyzer" "clippy"];
};
- in rec {
+ in {
packages = rec {
go-jsonnet = pkgs.callPackage ./nix/go-jsonnet.nix {};
sjsonnet = pkgs.callPackage ./nix/sjsonnet.nix {};
tests/suite/std_param_names.jsonnetdiffbeforeafterboth--- a/tests/suite/std_param_names.jsonnet
+++ b/tests/suite/std_param_names.jsonnet
@@ -103,6 +103,7 @@
asin: ['x'],
acos: ['x'],
atan: ['x'],
+ atan2: ['y', 'x'],
type: ['x'],
filter: ['func', 'arr'],
objectHasEx: ['obj', 'fname', 'hidden'],