difftreelog
style fix clippy warnings
in: master
4 files changed
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -192,8 +192,6 @@
inc_hidden: bool,
#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
) -> Result<VecVal> {
- #[cfg(not(feature = "exp-preserve-order"))]
- let preserve_order = false;
#[cfg(feature = "exp-preserve-order")]
let preserve_order = preserve_order.unwrap_or(false);
let out = obj.fields_ex(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -680,7 +680,7 @@
Ok(Some(push_frame(
loc,
|| format!("slice {}", desc),
- || Ok(evaluate(context.clone(), value)?.try_into()?),
+ || evaluate(context.clone(), value)?.try_into(),
)?))
} else {
Ok(None)
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5};67use gcmodule::{Cc, Trace, Weak};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ExprLocation, Visibility};10use rustc_hash::FxHashMap;1112use crate::{13 cc_ptr_eq,14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22pub(crate) mod ordering {23 use gcmodule::Trace;2425 #[derive(Clone, Copy, Default, Debug, Trace)]26 pub struct FieldIndex;27 impl FieldIndex {28 pub fn next(self) -> Self {29 Self30 }31 }3233 #[derive(Clone, Copy, Default, Debug, Trace)]34 pub struct SuperDepth;35 impl SuperDepth {36 pub fn deeper(self) -> Self {37 Self38 }39 }4041 #[derive(Clone, Copy)]42 pub struct FieldSortKey;43 impl FieldSortKey {44 pub fn new(_: SuperDepth, _: FieldIndex) -> Self {45 Self46 }47 }48}4950#[cfg(feature = "exp-preserve-order")]51mod ordering {52 use std::cmp::Reverse;5354 use gcmodule::Trace;5556 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]57 pub struct FieldIndex(u32);58 impl FieldIndex {59 pub fn next(self) -> Self {60 Self(self.0 + 1)61 }62 }6364 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]65 pub struct SuperDepth(u32);66 impl SuperDepth {67 pub fn deeper(self) -> Self {68 Self(self.0 + 1)69 }70 }7172 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]73 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);74 impl FieldSortKey {75 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {76 Self(Reverse(depth), index)77 }78 pub fn collide(self, other: Self) -> Self {79 if self.0 .0 > other.0 .0 {80 self81 } else if self.0 .0 < other.0 .0 {82 other83 } else {84 unreachable!("object can't have two fields with same name")85 }86 }87 }88}8990pub(crate) use ordering::*;9192#[derive(Debug, Trace)]93pub struct ObjMember {94 pub add: bool,95 pub visibility: Visibility,96 original_index: FieldIndex,97 pub invoke: LazyBinding,98 pub location: Option<ExprLocation>,99}100101pub trait ObjectAssertion: Trace {102 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;103}104105// Field => This106type CacheKey = (IStr, WeakObjValue);107108#[derive(Trace)]109enum CacheValue {110 Cached(Val),111 NotFound,112 Pending,113 Errored(LocError),114}115116#[derive(Trace)]117#[force_tracking]118pub struct ObjValueInternals {119 super_obj: Option<ObjValue>,120 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,121 assertions_ran: RefCell<GcHashSet<ObjValue>>,122 this_obj: Option<ObjValue>,123 this_entries: Cc<GcHashMap<IStr, ObjMember>>,124 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,125}126127#[derive(Clone, Trace)]128pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);129130impl PartialEq for WeakObjValue {131 fn eq(&self, other: &Self) -> bool {132 weak_ptr_eq(self.0.clone(), other.0.clone())133 }134}135136impl Eq for WeakObjValue {}137impl Hash for WeakObjValue {138 fn hash<H: Hasher>(&self, hasher: &mut H) {139 hasher.write_usize(weak_raw(self.0.clone()) as usize)140 }141}142143#[derive(Clone, Trace)]144pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);145impl Debug for ObjValue {146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {147 if let Some(super_obj) = self.0.super_obj.as_ref() {148 if f.alternate() {149 write!(f, "{:#?}", super_obj)?;150 } else {151 write!(f, "{:?}", super_obj)?;152 }153 write!(f, " + ")?;154 }155 let mut debug = f.debug_struct("ObjValue");156 for (name, member) in self.0.this_entries.iter() {157 debug.field(name, member);158 }159 debug.finish_non_exhaustive()160 }161}162163impl ObjValue {164 pub fn new(165 super_obj: Option<Self>,166 this_entries: Cc<GcHashMap<IStr, ObjMember>>,167 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,168 ) -> Self {169 Self(Cc::new(ObjValueInternals {170 super_obj,171 assertions,172 assertions_ran: RefCell::new(GcHashSet::new()),173 this_obj: None,174 this_entries,175 value_cache: RefCell::new(GcHashMap::new()),176 }))177 }178 pub fn new_empty() -> Self {179 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))180 }181 pub fn extend_from(&self, super_obj: Self) -> Self {182 match &self.0.super_obj {183 None => Self::new(184 Some(super_obj),185 self.0.this_entries.clone(),186 self.0.assertions.clone(),187 ),188 Some(v) => Self::new(189 Some(v.extend_from(super_obj)),190 self.0.this_entries.clone(),191 self.0.assertions.clone(),192 ),193 }194 }195 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {196 let mut new = GcHashMap::with_capacity(1);197 new.insert(key, value);198 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))199 }200 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {201 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())202 }203 pub fn with_this(&self, this_obj: Self) -> Self {204 Self(Cc::new(ObjValueInternals {205 super_obj: self.0.super_obj.clone(),206 assertions: self.0.assertions.clone(),207 assertions_ran: RefCell::new(GcHashSet::new()),208 this_obj: Some(this_obj),209 this_entries: self.0.this_entries.clone(),210 value_cache: RefCell::new(GcHashMap::new()),211 }))212 }213214 pub fn len(&self) -> usize {215 self.fields_visibility()216 .into_iter()217 .filter(|(_, (visible, _))| *visible)218 .count()219 }220221 pub fn is_empty(&self) -> bool {222 if !self.0.this_entries.is_empty() {223 return false;224 }225 self.0226 .super_obj227 .as_ref()228 .map(|s| s.is_empty())229 .unwrap_or(true)230 }231232 /// Run callback for every field found in object233 pub(crate) fn enum_fields(234 &self,235 depth: SuperDepth,236 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,237 ) -> bool {238 if let Some(s) = &self.0.super_obj {239 if s.enum_fields(depth.deeper(), handler) {240 return true;241 }242 }243 for (name, member) in self.0.this_entries.iter() {244 if handler(depth, name, member) {245 return true;246 }247 }248 false249 }250251 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {252 let mut out = FxHashMap::default();253 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {254 let new_sort_key = FieldSortKey::new(depth, member.original_index);255 match member.visibility {256 Visibility::Normal => {257 let entry = out.entry(name.to_owned());258 let v = entry.or_insert((true, new_sort_key));259 v.1 = new_sort_key;260 }261 Visibility::Hidden => {262 out.insert(name.to_owned(), (false, new_sort_key));263 }264 Visibility::Unhide => {265 out.insert(name.to_owned(), (true, new_sort_key));266 }267 };268 false269 });270 out271 }272 pub fn fields_ex(273 &self,274 include_hidden: bool,275 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,276 ) -> Vec<IStr> {277 #[cfg(feature = "exp-preserve-order")]278 if preserve_order {279 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self280 .fields_visibility()281 .into_iter()282 .filter(|(_, (visible, _))| include_hidden || *visible)283 .enumerate()284 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))285 .unzip();286 keys.sort_unstable_by_key(|v| v.0);287 // Reorder in-place by resulting indexes288 for i in 0..fields.len() {289 let x = fields[i].clone();290 let mut j = i;291 loop {292 let k = keys[j].1;293 keys[j].1 = j;294 if k == i {295 break;296 }297 fields[j] = fields[k].clone();298 j = k299 }300 fields[j] = x;301 }302 return fields;303 }304305 let mut fields: Vec<_> = self306 .fields_visibility()307 .into_iter()308 .filter(|(_, (visible, _))| include_hidden || *visible)309 .map(|(k, _)| k)310 .collect();311 fields.sort_unstable();312 fields313 }314 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {315 self.fields_ex(316 false,317 #[cfg(feature = "exp-preserve-order")]318 preserve_order,319 )320 }321322 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {323 if let Some(m) = self.0.this_entries.get(&name) {324 Some(match &m.visibility {325 Visibility::Normal => self326 .0327 .super_obj328 .as_ref()329 .and_then(|super_obj| super_obj.field_visibility(name))330 .unwrap_or(Visibility::Normal),331 v => *v,332 })333 } else if let Some(super_obj) = &self.0.super_obj {334 super_obj.field_visibility(name)335 } else {336 None337 }338 }339340 fn has_field_include_hidden(&self, name: IStr) -> bool {341 if self.0.this_entries.contains_key(&name) {342 true343 } else if let Some(super_obj) = &self.0.super_obj {344 super_obj.has_field_include_hidden(name)345 } else {346 false347 }348 }349350 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {351 if include_hidden {352 self.has_field_include_hidden(name)353 } else {354 self.has_field(name)355 }356 }357 pub fn has_field(&self, name: IStr) -> bool {358 self.field_visibility(name)359 .map(|v| v.is_visible())360 .unwrap_or(false)361 }362363 pub fn get(&self, key: IStr) -> Result<Option<Val>> {364 self.run_assertions()?;365 self.get_raw(key, self.0.this_obj.as_ref())366 }367368 // pub fn extend_with(self, key: )369370 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {371 let real_this = real_this.unwrap_or(self);372 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));373374 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {375 return Ok(match v {376 CacheValue::Cached(v) => Some(v.clone()),377 CacheValue::NotFound => None,378 CacheValue::Pending => throw!(InfiniteRecursionDetected),379 CacheValue::Errored(e) => return Err(e.clone()),380 });381 }382 self.0383 .value_cache384 .borrow_mut()385 .insert(cache_key.clone(), CacheValue::Pending);386 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {387 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),388 (Some(k), Some(s)) => {389 let our = self.evaluate_this(k, real_this)?;390 if k.add {391 s.get_raw(key, Some(real_this))?392 .map_or(Ok(Some(our.clone())), |v| {393 Ok(Some(evaluate_add_op(&v, &our)?))394 })395 } else {396 Ok(Some(our))397 }398 }399 (None, Some(s)) => s.get_raw(key, Some(real_this)),400 (None, None) => Ok(None),401 };402 let value = match value {403 Ok(v) => v,404 Err(e) => {405 self.0406 .value_cache407 .borrow_mut()408 .insert(cache_key, CacheValue::Errored(e.clone()));409 return Err(e);410 }411 };412 self.0.value_cache.borrow_mut().insert(413 cache_key,414 match &value {415 Some(v) => CacheValue::Cached(v.clone()),416 None => CacheValue::NotFound,417 },418 );419 Ok(value)420 }421 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {422 v.invoke423 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?424 .evaluate()425 }426427 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {428 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {429 for assertion in self.0.assertions.iter() {430 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {431 self.0.assertions_ran.borrow_mut().remove(real_this);432 return Err(e);433 }434 }435 if let Some(super_obj) = &self.0.super_obj {436 super_obj.run_assertions_raw(real_this)?;437 }438 }439 Ok(())440 }441 pub fn run_assertions(&self) -> Result<()> {442 self.run_assertions_raw(self)443 }444445 pub fn ptr_eq(a: &Self, b: &Self) -> bool {446 cc_ptr_eq(&a.0, &b.0)447 }448}449450impl PartialEq for ObjValue {451 fn eq(&self, other: &Self) -> bool {452 cc_ptr_eq(&self.0, &other.0)453 }454}455456impl Eq for ObjValue {}457impl Hash for ObjValue {458 fn hash<H: Hasher>(&self, hasher: &mut H) {459 hasher.write_usize(&*self.0 as *const _ as usize)460 }461}462463pub struct ObjValueBuilder {464 super_obj: Option<ObjValue>,465 map: GcHashMap<IStr, ObjMember>,466 assertions: Vec<TraceBox<dyn ObjectAssertion>>,467 next_field_index: FieldIndex,468}469impl ObjValueBuilder {470 pub fn new() -> Self {471 Self::with_capacity(0)472 }473 pub fn with_capacity(capacity: usize) -> Self {474 Self {475 super_obj: None,476 map: GcHashMap::with_capacity(capacity),477 assertions: Vec::new(),478 next_field_index: FieldIndex::default(),479 }480 }481 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {482 self.assertions.reserve_exact(capacity);483 self484 }485 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {486 self.super_obj = Some(super_obj);487 self488 }489490 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {491 self.assertions.push(assertion);492 self493 }494 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {495 let field_index = self.next_field_index;496 self.next_field_index = self.next_field_index.next();497 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)498 }499500 pub fn build(self) -> ObjValue {501 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))502 }503}504impl Default for ObjValueBuilder {505 fn default() -> Self {506 Self::with_capacity(0)507 }508}509510#[must_use = "value not added unless binding() was called"]511pub struct ObjMemberBuilder<Kind> {512 kind: Kind,513 name: IStr,514 add: bool,515 visibility: Visibility,516 original_index: FieldIndex,517 location: Option<ExprLocation>,518}519520#[allow(clippy::missing_const_for_fn)]521impl<Kind> ObjMemberBuilder<Kind> {522 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {523 Self {524 kind,525 name,526 original_index,527 add: false,528 visibility: Visibility::Normal,529 location: None,530 }531 }532533 pub const fn with_add(mut self, add: bool) -> Self {534 self.add = add;535 self536 }537 pub fn add(self) -> Self {538 self.with_add(true)539 }540 pub fn with_visibility(mut self, visibility: Visibility) -> Self {541 self.visibility = visibility;542 self543 }544 pub fn hide(self) -> Self {545 self.with_visibility(Visibility::Hidden)546 }547 pub fn with_location(mut self, location: ExprLocation) -> Self {548 self.location = Some(location);549 self550 }551 fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {552 (553 self.kind,554 self.name,555 ObjMember {556 add: self.add,557 visibility: self.visibility,558 original_index: self.original_index,559 invoke: binding,560 location: self.location,561 },562 )563 }564}565566pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);567impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {568 pub fn value(self, value: Val) -> Result<()> {569 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))570 }571 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {572 self.binding(LazyBinding::Bindable(Cc::new(bindable)))573 }574 pub fn binding(self, binding: LazyBinding) -> Result<()> {575 let (receiver, name, member) = self.build_member(binding);576 let location = member.location.clone();577 let old = receiver.0.map.insert(name.clone(), member);578 if old.is_some() {579 push_frame(580 CallLocation(location.as_ref()),581 || format!("field <{}> initializtion", name.clone()),582 || throw!(DuplicateFieldName(name.clone())),583 )?584 }585 Ok(())586 }587}588589pub struct ExtendBuilder<'v>(&'v mut ObjValue);590impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {591 pub fn value(self, value: Val) {592 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))593 }594 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) {595 self.binding(LazyBinding::Bindable(Cc::new(bindable)))596 }597 pub fn binding(self, binding: LazyBinding) -> () {598 let (receiver, name, member) = self.build_member(binding);599 let new = receiver.0.clone();600 *receiver.0 = new.extend_with_raw_member(name, member)601 }602}crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -201,16 +201,16 @@
pub(crate) step: u32,
}
impl Slice {
- fn from(&self) -> usize {
+ const fn from(&self) -> usize {
self.from as usize
}
- fn to(&self) -> usize {
+ const fn to(&self) -> usize {
self.to as usize
}
- fn step(&self) -> usize {
+ const fn step(&self) -> usize {
self.step as usize
}
- fn len(&self) -> usize {
+ const fn len(&self) -> usize {
// TODO: use div_ceil
let diff = self.to() - self.from();
let rem = diff % self.step();