Skip to content

Commit

Permalink
Merge pull request #146 from CertainLach/fix/tests
Browse files Browse the repository at this point in the history
Fix failing CI for tests and lints
  • Loading branch information
CertainLach authored Jan 16, 2024
2 parents 0d49135 + 86f8537 commit 58696dc
Show file tree
Hide file tree
Showing 22 changed files with 93 additions and 94 deletions.
2 changes: 1 addition & 1 deletion cmds/jrsonnet-fmt/src/comments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ pub fn format_comments(comments: &ChildTrivia, loc: CommentLocation) -> PrintIte
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
Expand Down
4 changes: 2 additions & 2 deletions cmds/jrsonnet-fmt/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,8 @@ impl Printable for ObjBody {
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)));
Expand Down
21 changes: 15 additions & 6 deletions crates/jrsonnet-cli/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use jrsonnet_evaluator::manifest::{
};
use jrsonnet_stdlib::{TomlFormat, YamlFormat};

#[derive(Clone, ValueEnum)]
#[derive(Clone, Copy, ValueEnum)]
pub enum ManifestFormatName {
/// Expect string as output, and write them directly
String,
Expand All @@ -18,9 +18,11 @@ pub enum ManifestFormatName {
#[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")]
Expand All @@ -29,7 +31,9 @@ pub struct ManifestOpts {
#[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
Expand All @@ -44,7 +48,12 @@ impl ManifestOpts {
} 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),
Expand Down
14 changes: 5 additions & 9 deletions crates/jrsonnet-evaluator/src/arr/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ impl RangeArray {
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)
Expand Down Expand Up @@ -461,7 +461,7 @@ impl ArrayLike for MappedArray {
ArrayThunk::Waiting(..) => {}
};

let ArrayThunk::Waiting(_) =
let ArrayThunk::Waiting(()) =
replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
else {
unreachable!()
Expand Down Expand Up @@ -508,7 +508,7 @@ impl ArrayLike for MappedArray {
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 {
Expand Down Expand Up @@ -597,9 +597,7 @@ impl ArrayLike for PickObjectValues {
}

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()))
}

Expand Down Expand Up @@ -649,9 +647,7 @@ impl ArrayLike for PickObjectKeyValues {
}

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(
Expand Down
2 changes: 1 addition & 1 deletion crates/jrsonnet-evaluator/src/evaluate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub fn evaluate_comp(
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)?)? {
Expand Down
13 changes: 6 additions & 7 deletions crates/jrsonnet-evaluator/src/function/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use jrsonnet_interner::IStr;
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 {
Expand All @@ -27,10 +27,9 @@ impl ParamName {
}
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())
}
}

Expand Down Expand Up @@ -87,7 +86,7 @@ impl NativeCallback {
params: params
.into_iter()
.map(|n| BuiltinParam {
name: ParamName::new_dynamic(n.to_string()),
name: ParamName::new_dynamic(n),
has_default: false,
})
.collect(),
Expand Down
6 changes: 3 additions & 3 deletions crates/jrsonnet-evaluator/src/integrations/serde.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,11 @@ impl Serialize for Val {
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")]
Expand Down
10 changes: 6 additions & 4 deletions crates/jrsonnet-evaluator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions crates/jrsonnet-evaluator/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {
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,
Expand Down
12 changes: 6 additions & 6 deletions crates/jrsonnet-evaluator/src/obj.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ impl Debug for OopObject {
// .field("assertions_ran", &self.assertions_ran)
.field("this_entries", &self.this_entries)
// .field("value_cache", &self.value_cache)
.finish()
.finish_non_exhaustive()
}
}

Expand Down Expand Up @@ -347,7 +347,7 @@ impl ObjValue {
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);
Expand Down Expand Up @@ -395,7 +395,7 @@ impl ObjValue {

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>> {
Expand Down Expand Up @@ -474,7 +474,7 @@ impl ObjValue {
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)
}
}

Expand All @@ -495,7 +495,7 @@ impl ObjValue {
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 => {}
Expand Down Expand Up @@ -634,7 +634,7 @@ impl OopObject {
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 => {}
Expand Down
2 changes: 1 addition & 1 deletion crates/jrsonnet-evaluator/src/stdlib/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {
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((
Expand Down
32 changes: 14 additions & 18 deletions crates/jrsonnet-evaluator/src/typed/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -449,25 +449,21 @@ impl Typed for IBytes {
}

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())
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/jrsonnet-evaluator/src/typed/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ fn push_type_description(
item: impl Fn() -> Result<()>,
) -> Result<()> {
State::push_description(error_reason, || match item() {
Ok(_) => Ok(()),
Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
(e.1).0.push(path());
Expand Down
2 changes: 2 additions & 0 deletions crates/jrsonnet-evaluator/src/val.rs
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,8 @@ impl Display for StrValue {
}
}
impl PartialEq for StrValue {
// False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.
#[allow(clippy::unconditional_recursion)]

Check warning on line 355 in crates/jrsonnet-evaluator/src/val.rs

View workflow job for this annotation

GitHub Actions / clippy

unknown lint: `clippy::unconditional_recursion`

warning: unknown lint: `clippy::unconditional_recursion` --> crates/jrsonnet-evaluator/src/val.rs:355:10 | 355 | #[allow(clippy::unconditional_recursion)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: did you mean: `unconditional_recursion` | = note: `#[warn(unknown_lints)]` on by default
fn eq(&self, other: &Self) -> bool {
let a = self.clone().into_flat();
let b = other.clone().into_flat();
Expand Down
27 changes: 5 additions & 22 deletions crates/jrsonnet-interner/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
#![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},
ops::Deref,
str,
};

use hashbrown::HashMap;
use hashbrown::{hash_map::RawEntryMut, HashMap};
use jrsonnet_gcmodule::Trace;
use rustc_hash::FxHasher;

Expand Down Expand Up @@ -57,17 +57,6 @@ impl Deref for IStr {
}
}

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
Expand Down Expand Up @@ -146,12 +135,6 @@ impl Deref for IBytes {
}
}

impl Borrow<[u8]> for IBytes {
fn borrow(&self) -> &[u8] {
self.0.as_slice()
}
}

impl PartialEq for IBytes {
fn eq(&self, other: &Self) -> bool {
// all IStr should be inlined into same pool
Expand Down Expand Up @@ -285,9 +268,9 @@ pub fn intern_bytes(bytes: &[u8]) -> IBytes {
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())
}
}
Expand Down
1 change: 1 addition & 0 deletions crates/jrsonnet-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,7 @@ fn builtin_inner(
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)?;

Expand Down
2 changes: 1 addition & 1 deletion crates/jrsonnet-stdlib/src/encoding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ pub fn builtin_base64_decode(str: IStr) -> Result<String> {
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"))
}
Loading

0 comments on commit 58696dc

Please sign in to comment.