difftreelog
style fix clippy warnings
in: master
24 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -676,18 +676,18 @@
[[package]]
name = "jrsonnet-gcmodule"
-version = "0.4.1"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c33f4f6cdc60f5ae94ebae3dfe7f484ae79b364225d9b19601b24c804cfd8751"
+checksum = "f95b976a79e4000bb9e07ff0709dca0ea27bcf1952d4c17d91fb7364d6145683"
dependencies = [
"jrsonnet-gcmodule-derive",
]
[[package]]
name = "jrsonnet-gcmodule-derive"
-version = "0.4.1"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b30c95b285f9bb6709f1b3e6fc69b3a25e39b32ff987587fd108f0f22be5fa3"
+checksum = "51d928626220a310ff0cec815e80cf7fe104697184352ca21c40534e0b0d72d9"
dependencies = [
"proc-macro2",
"quote",
@@ -1602,7 +1602,7 @@
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.59.0",
+ "windows-sys 0.61.2",
]
[[package]]
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,7 +20,7 @@
jrsonnet-cli = { path = "./crates/jrsonnet-cli", version = "0.5.0-pre97" }
jrsonnet-types = { path = "./crates/jrsonnet-types", version = "0.5.0-pre97" }
jrsonnet-formatter = { path = "./crates/jrsonnet-formatter", version = "0.5.0-pre97" }
-jrsonnet-gcmodule = { version = "0.4.1" }
+jrsonnet-gcmodule = { version = "0.4.2" }
# Diagnostics.
# hi-doc is my library, which handles text formatting very well, but isn't polished enough yet
# Previous implementation was based on annotate-snippets, which I don't like for many reasons.
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -66,8 +66,8 @@
base.as_ptr(),
rel.as_ptr(),
&mut found_here.cast_const(),
- &mut buf,
- &mut buf_len,
+ &raw mut buf,
+ &raw mut buf_len,
)
};
let buf_slice: &[u8] = unsafe { std::slice::from_raw_parts(buf.cast(), buf_len) };
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -9,6 +9,9 @@
evaluate_method, evaluate_named_param, Context, Pending, Thunk, Val,
};
+#[cfg(feature = "exp-preserve-order")]
+use crate::evaluate;
+
#[allow(clippy::too_many_lines)]
#[allow(unused_variables)]
pub fn destruct<H: BuildHasher>(
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -143,7 +143,7 @@
false,
) {
let fctx = Pending::new();
- let mut new_bindings = FxHashMap::with_capacity(var.capacity_hint());
+ let mut new_bindings = FxHashMap::with_capacity(var.binds_len());
let obj = obj.clone();
let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![
Thunk::evaluated(Val::string(field.clone())),
crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -98,9 +98,9 @@
fn call(&self, _loc: CallLocation<'_>, args: &[Option<Thunk<Val>>]) -> Result<Val> {
let args = args
- .into_iter()
+ .iter()
.map(|a| a.as_ref().expect("legacy natives have no default params"))
- .map(|a| a.evaluate())
+ .map(Thunk::evaluate)
.collect::<Result<Vec<Val>>>()?;
self.handler.call(&args)
}
crates/jrsonnet-evaluator/src/obj/mod.rsdiffbeforeafterboth1use std::{2 any::Any,3 cell::{Cell, RefCell},4 clone::Clone,5 collections::hash_map::Entry,6 fmt::{self, Debug},7 hash::{Hash, Hasher},8 num::Saturating,9 ops::ControlFlow,10};1112use educe::Educe;13use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};14use jrsonnet_interner::IStr;15use jrsonnet_parser::Span;16use rustc_hash::{FxHashMap, FxHashSet};1718mod oop;1920pub use jrsonnet_parser::Visibility;21pub use oop::ObjValueBuilder;2223use crate::{24 arr::{PickObjectKeyValues, PickObjectValues},25 bail,26 error::{suggest_object_fields, ErrorKind::*},27 identity_hash,28 operator::evaluate_add_op,29 val::{ArrValue, ThunkValue},30 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,31};3233#[cfg(not(feature = "exp-preserve-order"))]34pub mod ordering {35 #![allow(36 // This module works as stub for preserve-order feature37 clippy::unused_self,38 )]3940 use jrsonnet_gcmodule::Trace;4142 #[derive(Clone, Copy, Default, Debug, Trace)]43 pub struct FieldIndex(());44 impl FieldIndex {45 pub fn absolute(_v: u32) -> Self {46 Self(())47 }48 pub const fn next(self) -> Self {49 Self(())50 }51 }5253 #[derive(Clone, Copy, Default, Debug, Trace)]54 pub struct SuperDepth(());55 impl SuperDepth {56 pub(super) fn deepen(self) {}57 }58}5960#[cfg(feature = "exp-preserve-order")]61pub mod ordering {62 use std::cmp::Reverse;6364 use jrsonnet_gcmodule::Trace;6566 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67 pub struct FieldIndex(u32);68 impl FieldIndex {69 pub fn absolute(v: u32) -> Self {70 Self(v)71 }72 pub fn next(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct SuperDepth(u32);79 impl SuperDepth {80 pub(super) fn deepen(&mut self) {81 self.0 += 182 }83 }8485 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]86 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);87 impl FieldSortKey {88 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {89 Self(Reverse(depth), index)90 }91 }92}9394#[cfg(feature = "exp-preserve-order")]95use ordering::FieldSortKey;96use ordering::{FieldIndex, SuperDepth};9798// 0 - add99// 12 - visibility100#[derive(Clone, Copy)]101pub struct ObjFieldFlags(u8);102impl ObjFieldFlags {103 fn new(add: bool, visibility: Visibility) -> Self {104 let mut v = 0;105 if add {106 v |= 1;107 }108 v |= match visibility {109 Visibility::Normal => 0b000,110 Visibility::Hidden => 0b010,111 Visibility::Unhide => 0b100,112 };113 Self(v)114 }115 pub fn add(&self) -> bool {116 self.0 & 1 != 0117 }118 pub fn visibility(&self) -> Visibility {119 match (self.0 & 0b110) >> 1 {120 0b00 => Visibility::Normal,121 0b01 => Visibility::Hidden,122 0b10 => Visibility::Unhide,123 _ => unreachable!(),124 }125 }126}127impl Debug for ObjFieldFlags {128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {129 f.debug_struct("ObjFieldFlags")130 .field("add", &self.add())131 .field("visibility", &self.visibility())132 .finish()133 }134}135136#[allow(clippy::module_name_repetitions)]137#[derive(Debug, Trace)]138pub struct ObjMember {139 #[trace(skip)]140 flags: ObjFieldFlags,141 original_index: FieldIndex,142 pub invoke: MaybeUnbound,143 pub location: Option<Span>,144}145146cc_dyn!(CcObjectAssertion, ObjectAssertion);147pub trait ObjectAssertion: Trace {148 fn run(&self, sup_this: SupThis) -> Result<()>;149}150151// Field => This152153#[derive(Trace, Debug)]154enum CacheValue {155 Cached(Result<Option<Val>>),156 Pending,157}158159pub type EnumFieldsHandler<'a> =160 dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;161162pub enum EnumFields {163 Normal(Visibility),164 Omit(Skip),165}166167#[derive(Trace, Clone)]168pub enum GetFor {169 // Return value170 Final(Val),171 // Continue iterating over cores, add current value to sum stack172 SuperPlus(Val),173 // Ignore the field value, stop at this layer instead174 Omit(#[trace(skip)] Skip),175 NotFound,176}177178#[derive(Acyclic, Clone)]179pub enum FieldVisibility {180 Found(Visibility),181 Omit(Skip),182 NotFound,183}184185#[derive(Acyclic, Clone)]186pub enum HasFieldIncludeHidden {187 Exists,188 NotFound,189 Omit(Skip),190}191192type Skip = Saturating<usize>;193194pub trait ObjectCore: Trace + Any + Debug {195 // If callback returns false, iteration stops, and this call returns false.196 fn enum_fields_core(197 &self,198 super_depth: &mut SuperDepth,199 handler: &mut EnumFieldsHandler<'_>,200 ) -> bool;201202 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;203204 fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;205 fn field_visibility_core(&self, field: IStr) -> FieldVisibility;206207 fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;208}209210#[derive(Clone, Trace)]211pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);212impl Debug for WeakObjValue {213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {214 f.debug_tuple("WeakObjValue").finish()215 }216}217218impl PartialEq for WeakObjValue {219 fn eq(&self, other: &Self) -> bool {220 Weak::ptr_eq(&self.0, &other.0)221 }222}223224impl Eq for WeakObjValue {}225impl Hash for WeakObjValue {226 fn hash<H: Hasher>(&self, hasher: &mut H) {227 // Safety: usize is POD228 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };229 hasher.write_usize(addr);230 }231}232233cc_dyn!(234 #[derive(Clone, Debug)]235 CcObjectCore, ObjectCore,236 pub fn new() {...}237);238#[derive(Trace, Educe)]239#[educe(Debug)]240struct ObjValueInner {241 cores: Vec<CcObjectCore>,242 assertions_ran: Cell<bool>,243 value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,244}245246thread_local! {247 static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();248}249fn is_asserting(obj: &ObjValue) -> bool {250 RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))251}252/// Returns false if already asserting253fn start_asserting(obj: &ObjValue) -> bool {254 RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))255}256fn finish_asserting(obj: &ObjValue) {257 RUNNING_ASSERTIONS.with_borrow_mut(|v| {258 let r = v.remove(obj);259 debug_assert!(260 r,261 "finish_asserting was called before start_asserting or twice"262 );263 });264}265266thread_local! {267 static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {268 cores: vec![],269 assertions_ran: Cell::new(true),270 value_cache: RefCell::default(),271 }))272}273274#[allow(clippy::module_name_repetitions)]275#[derive(Clone, Trace, Debug, Educe)]276#[educe(PartialEq, Hash, Eq)]277pub struct ObjValue(278 #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,279);280281impl ObjValue {282 pub fn empty() -> Self {283 EMPTY_OBJ.with(Clone::clone)284 }285 pub fn is_empty(&self) -> bool {286 self.0.cores.is_empty() || self.len() == 0287 }288}289290#[derive(Trace, Debug)]291struct StandaloneSuperCore {292 sup: CoreIdx,293 this: ObjValue,294}295impl ObjectCore for StandaloneSuperCore {296 fn enum_fields_core(297 &self,298 super_depth: &mut SuperDepth,299 handler: &mut EnumFieldsHandler<'_>,300 ) -> bool {301 self.this.enum_fields_idx(super_depth, handler, self.sup)302 }303304 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {305 if self.this.has_field_include_hidden_idx(name, self.sup) {306 HasFieldIncludeHidden::Exists307 } else {308 HasFieldIncludeHidden::NotFound309 }310 }311312 fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {313 if omit_only {314 return Ok(GetFor::NotFound);315 }316 let v = self.this.get_idx(key, self.sup)?;317 Ok(v.map_or(GetFor::NotFound, GetFor::Final))318 }319320 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {321 self.this322 .field_visibility_idx(field, self.sup)323 .map_or(FieldVisibility::NotFound, FieldVisibility::Found)324 }325326 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {327 self.this.run_assertions()328 }329}330331#[derive(Debug, Acyclic)]332struct OmitFieldsCore {333 omit: FxHashSet<IStr>,334 prev_layers: usize,335}336impl ObjectCore for OmitFieldsCore {337 fn enum_fields_core(338 &self,339 super_depth: &mut SuperDepth,340 handler: &mut EnumFieldsHandler<'_>,341 ) -> bool {342 let mut fi = FieldIndex::default();343 for f in &self.omit {344 if handler(345 *super_depth,346 fi,347 f.clone(),348 EnumFields::Omit(Saturating(self.prev_layers)),349 ) == ControlFlow::Break(())350 {351 return false;352 }353 fi = fi.next();354 }355 true356 }357358 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {359 if self.omit.contains(&name) {360 return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));361 }362 HasFieldIncludeHidden::NotFound363 }364365 fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {366 if self.omit.contains(&key) {367 return Ok(GetFor::Omit(Saturating(self.prev_layers)));368 }369 Ok(GetFor::NotFound)370 }371372 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {373 if self.omit.contains(&field) {374 return FieldVisibility::Omit(Saturating(self.prev_layers));375 }376 FieldVisibility::NotFound377 }378379 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {380 Ok(())381 }382}383384#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]385struct CoreIdx {386 idx: usize,387}388impl CoreIdx {389 fn super_exists(self) -> bool {390 self.idx != 0391 }392}393#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]394pub struct SupThis {395 sup: CoreIdx,396 this: ObjValue,397}398impl SupThis {399 pub fn has_super(&self) -> bool {400 self.sup.super_exists()401 }402 /// Implementation of `"field" in super` operation,403 /// works faster than standalone super path.404 ///405 /// In case of no `super` existence, returns false.406 pub fn field_in_super(&self, field: IStr) -> bool {407 self.this.has_field_include_hidden_idx(field, self.sup)408 }409 /// Implementation of `super.field` operation,410 /// works faster than standalone super path.411 ///412 /// In case of no `super` existence, returns `NoSuperFound`413 pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {414 if !self.sup.super_exists() {415 bail!(NoSuperFound);416 }417 self.this.get_idx(field, self.sup)418 }419 /// `super` with `self` overriden for top-level lookups.420 /// Exists when super appears outside of `super.field`/`"field" in super` expressions421 /// Exclusive to jrsonnet.422 ///423 /// Might return `NoSuperFound` error.424 pub fn standalone_super(&self) -> Result<ObjValue> {425 if !self.sup.super_exists() {426 bail!(NoSuperFound)427 }428 let mut out = ObjValue::builder();429 out.reserve_cores(1).extend_with_core(StandaloneSuperCore {430 sup: self.sup,431 this: self.this.clone(),432 });433 Ok(out.build())434 }435 pub fn this(&self) -> &ObjValue {436 &self.this437 }438 pub fn downgrade(self) -> WeakSupThis {439 WeakSupThis {440 sup: self.sup,441 this: self.this.downgrade(),442 }443 }444}445#[derive(Trace, PartialEq, Eq, Hash, Debug)]446pub struct WeakSupThis {447 sup: CoreIdx,448 this: WeakObjValue,449}450451impl ObjValue {452 pub fn builder() -> ObjValueBuilder {453 ObjValueBuilder::new()454 }455 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {456 ObjValueBuilder::with_capacity(capacity)457 }458 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {459 let mut out = ObjValueBuilder::with_capacity(1);460 out.with_super(self);461 let mut member = out.field(key);462 if value.flags.add() {463 member = member.add();464 }465 if let Some(loc) = value.location {466 member = member.with_location(loc);467 }468 let _ = member469 .with_visibility(value.flags.visibility())470 .binding(value.invoke);471 out.build()472 }473 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {474 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())475 }476477 pub fn extend(&mut self) -> ObjValueBuilder {478 let mut out = ObjValueBuilder::new();479 out.with_super(self.clone());480 out481 }482483 #[must_use]484 pub fn extend_from(&self, sup: Self) -> Self {485 let mut cores = sup.0.cores.clone();486 cores.extend(self.0.cores.iter().cloned());487 ObjValue(Cc::new(ObjValueInner {488 cores,489 value_cache: RefCell::default(),490 assertions_ran: Cell::new(false),491 }))492 }493 // #[must_use]494 // pub fn with_this(&self, this: Self) -> Self {495 // self.0.with_this(self.clone(), this)496 // }497 /// Returns amount of visible object fields498 /// If object only contains hidden fields - may return zero.499 pub fn len(&self) -> usize {500 self.fields_visibility()501 .values()502 .filter(|d| d.visible())503 .count()504 }505 /// For each field, calls callback.506 /// If callback returns false - ends iteration prematurely.507 ///508 /// Returns false if ended prematurely509 pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {510 let mut super_depth = SuperDepth::default();511 self.enum_fields_idx(512 &mut super_depth,513 handler,514 CoreIdx {515 idx: self.0.cores.len(),516 },517 )518 }519 fn enum_fields_idx(520 &self,521 super_depth: &mut SuperDepth,522 handler: &mut EnumFieldsHandler<'_>,523 idx: CoreIdx,524 ) -> bool {525 for core in self.0.cores[..idx.idx].iter().rev() {526 if !core.0.enum_fields_core(super_depth, handler) {527 return false;528 }529 super_depth.deepen();530 }531 true532 }533534 pub fn has_field_include_hidden(&self, name: IStr) -> bool {535 self.has_field_include_hidden_idx(536 name,537 CoreIdx {538 idx: self.0.cores.len(),539 },540 )541 }542 fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {543 let mut skip = Saturating(0usize);544 for ele in self.0.cores[..core.idx].iter().rev() {545 match ele.0.has_field_include_hidden_core(name.clone()) {546 HasFieldIncludeHidden::Exists => {547 if skip.0 == 0 {548 return true;549 }550 }551 HasFieldIncludeHidden::Omit(new_skip) => {552 // +1 including this core553 skip = skip.max(new_skip + Saturating(1));554 }555 HasFieldIncludeHidden::NotFound => {}556 }557 skip -= 1;558 }559 false560 }561 pub fn has_field(&self, name: IStr) -> bool {562 match self.field_visibility(name) {563 Some(Visibility::Unhide | Visibility::Normal) => true,564 Some(Visibility::Hidden) | None => false,565 }566 }567 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {568 if include_hidden {569 self.has_field_include_hidden(name)570 } else {571 self.has_field(name)572 }573 }574 pub fn get(&self, key: IStr) -> Result<Option<Val>> {575 self.get_idx(576 key,577 CoreIdx {578 idx: self.0.cores.len(),579 },580 )581 }582583 fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {584 let cache_key = (key.clone(), core);585 {586 let mut cache = self.0.value_cache.borrow_mut();587 // entry_ref candidate?588 match cache.entry(cache_key.clone()) {589 Entry::Occupied(v) => match v.get() {590 CacheValue::Cached(v) => return v.clone(),591 CacheValue::Pending => {592 if !is_asserting(self) {593 bail!(InfiniteRecursionDetected);594 }595 }596 },597 Entry::Vacant(v) => {598 v.insert(CacheValue::Pending);599 }600 };601 }602 let result = self.get_idx_uncached(key, core);603 {604 let mut cache = self.0.value_cache.borrow_mut();605 cache.insert(cache_key, CacheValue::Cached(result.clone()));606 }607 result608 }609 fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {610 self.run_assertions()?;611 let mut add_stack = Vec::with_capacity(2);612 let mut skip = Saturating(0);613 for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {614 let sup_this = SupThis {615 sup: CoreIdx { idx: sup },616 this: self.clone(),617 };618 match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {619 GetFor::Final(val) if add_stack.is_empty() => {620 if skip.0 == 0 {621 return Ok(Some(val));622 }623 }624 GetFor::Final(val) => {625 if skip.0 == 0 {626 add_stack.push(val);627 break;628 }629 }630 GetFor::SuperPlus(val) => {631 if skip.0 == 0 {632 add_stack.push(val);633 }634 }635 GetFor::Omit(new_skip) => {636 // +1 including this core637 skip = skip.max(new_skip + Saturating(1));638 }639 GetFor::NotFound => {}640 }641 skip -= 1;642 }643 if add_stack.is_empty() {644 // None of layers had this field645 return Ok(None);646 } else if add_stack.len() == 1 {647 // A layer had this field, but it wanted this field to be added with super.648 // However, no super had this field, fail-safe649 return Ok(Some(add_stack.pop().expect("single element on stack")));650 }651 let mut values = add_stack.into_iter().rev();652 let init = values.next().expect("at least 2 elements");653654 values655 .try_fold(init, |a, b| evaluate_add_op(&a, &b))656 .map(Some)657658 // self.0.get_raw(key, this)659 }660661 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {662 let Some(value) = self.get(key.clone())? else {663 let suggestions = suggest_object_fields(self, key.clone());664 bail!(NoSuchField(key, suggestions))665 };666 Ok(value)667 }668669 fn field_visibility(&self, field: IStr) -> Option<Visibility> {670 self.field_visibility_idx(671 field,672 CoreIdx {673 idx: self.0.cores.len(),674 },675 )676 }677 fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {678 let mut exists = false;679 let mut skip = Saturating(0usize);680 for ele in self.0.cores[..core.idx].iter().rev() {681 let vis = ele.0.field_visibility_core(field.clone());682 match vis {683 FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {684 if skip.0 == 0 {685 return Some(vis);686 }687 }688 FieldVisibility::Found(Visibility::Normal) => {689 if skip.0 == 0 {690 exists = true;691 }692 }693 FieldVisibility::NotFound => {}694 FieldVisibility::Omit(new_skip) => {695 // +1 including this core696 skip = skip.max(new_skip + Saturating(1));697 }698 }699 skip -= 1;700 }701 exists.then_some(Visibility::Normal)702 }703704 pub fn run_assertions(&self) -> Result<()> {705 if self.0.assertions_ran.get() {706 return Ok(());707 }708 if !start_asserting(self) {709 return Ok(());710 }711 for (idx, ele) in self.0.cores.iter().enumerate() {712 let sup_this = SupThis {713 sup: CoreIdx { idx },714 this: self.clone(),715 };716 ele.0.run_assertions_core(sup_this).inspect_err(|_e| {717 finish_asserting(self);718 })?;719 }720 finish_asserting(self);721 self.0.assertions_ran.set(true);722 Ok(())723 }724725 pub fn iter(726 &self,727 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,728 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {729 let fields = self.fields(730 #[cfg(feature = "exp-preserve-order")]731 preserve_order,732 );733 fields.into_iter().map(|field| {734 (735 field.clone(),736 self.get(field)737 .map(|opt| opt.expect("iterating over keys, field exists")),738 )739 })740 }741 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {742 #[derive(Trace)]743 struct ObjFieldThunk {744 obj: ObjValue,745 key: IStr,746 }747 impl ThunkValue for ObjFieldThunk {748 type Output = Val;749750 fn get(&self) -> Result<Self::Output> {751 self.obj752 .get(self.key.clone())753 .transpose()754 .expect("field existence checked")755 }756 }757758 if !self.has_field_ex(key.clone(), true) {759 return None;760 }761762 Some(Thunk::new(ObjFieldThunk {763 obj: self.clone(),764 key,765 }))766 }767 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {768 #[derive(Trace)]769 struct ObjFieldThunk {770 obj: ObjValue,771 key: IStr,772 }773 impl ThunkValue for ObjFieldThunk {774 type Output = Val;775776 fn get(&self) -> Result<Self::Output> {777 self.obj.get_or_bail(self.key.clone())778 }779 }780781 Thunk::new(ObjFieldThunk {782 obj: self.clone(),783 key,784 })785 }786 pub fn ptr_eq(a: &Self, b: &Self) -> bool {787 Cc::ptr_eq(&a.0, &b.0)788 }789 pub fn downgrade(self) -> WeakObjValue {790 WeakObjValue(self.0.downgrade())791 }792}793794#[derive(Debug)]795struct FieldVisibilityData {796 omitted_until: Saturating<usize>,797 exists_visible: Option<Visibility>,798 #[cfg(feature = "exp-preserve-order")]799 key: FieldSortKey,800}801impl FieldVisibilityData {802 fn visible(&self) -> bool {803 self.exists_visible804 .expect("non-existing fields shall be dropped at the end of fn fields_visibility()")805 .is_visible()806 }807 #[cfg(feature = "exp-preserve-order")]808 fn sort_key(&self) -> FieldSortKey {809 self.key810 }811}812813impl ObjValue {814 fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {815 let mut out = FxHashMap::default();816817 let mut super_depth = SuperDepth::default();818 let mut omit_index = Saturating(0);819 for core in self.0.cores.iter().rev() {820 core.0821 .enum_fields_core(&mut super_depth, &mut |_depth, _index, name, visibility| {822 let entry = out.entry(name);823 let data = entry.or_insert(FieldVisibilityData {824 exists_visible: None,825 #[cfg(feature = "exp-preserve-order")]826 key: FieldSortKey::new(_depth, _index),827 omitted_until: omit_index,828 });829 match visibility {830 EnumFields::Omit(new_skip) => {831 // +1 including this core832 data.omitted_until = data833 .omitted_until834 .max(omit_index + new_skip + Saturating(1));835 }836 EnumFields::Normal(Visibility::Normal) => {837 if data.omitted_until <= omit_index && data.exists_visible.is_none() {838 data.exists_visible = Some(Visibility::Normal);839 }840 }841 EnumFields::Normal(Visibility::Hidden) => {842 if data.omitted_until <= omit_index {843 data.exists_visible = Some(match data.exists_visible {844 // We're iterating in reverse, later unhide is preserved845 Some(Visibility::Unhide) => Visibility::Unhide,846 _ => Visibility::Hidden,847 });848 }849 }850 EnumFields::Normal(Visibility::Unhide) => {851 if data.omitted_until <= omit_index {852 data.exists_visible = Some(match data.exists_visible {853 // We're iterating in reverse, later hide is preserved854 Some(Visibility::Hidden) => Visibility::Hidden,855 _ => Visibility::Unhide,856 });857 }858 }859 }860 ControlFlow::Continue(())861 });862863 super_depth.deepen();864 omit_index += 1;865 }866867 out.retain(|_, v| v.exists_visible.is_some());868869 out870 }871 pub fn fields_ex(872 &self,873 include_hidden: bool,874 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,875 ) -> Vec<IStr> {876 #[cfg(feature = "exp-preserve-order")]877 if preserve_order {878 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self879 .fields_visibility()880 .into_iter()881 .filter(|(_, d)| include_hidden || d.visible())882 .enumerate()883 .map(|(idx, (k, d))| (k, (d.sort_key(), idx)))884 .unzip();885 keys.sort_unstable_by_key(|v| v.0);886 // Reorder in-place by resulting indexes887 for i in 0..fields.len() {888 let x = fields[i].clone();889 let mut j = i;890 loop {891 let k = keys[j].1;892 keys[j].1 = j;893 if k == i {894 break;895 }896 fields[j] = fields[k].clone();897 j = k;898 }899 fields[j] = x;900 }901 return fields;902 }903904 let mut fields: Vec<_> = self905 .fields_visibility()906 .into_iter()907 .filter(|(_, d)| include_hidden || d.visible())908 .map(|(k, _)| k)909 .collect();910 fields.sort_unstable();911 fields912 }913 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {914 self.fields_ex(915 false,916 #[cfg(feature = "exp-preserve-order")]917 preserve_order,918 )919 }920 pub fn values_ex(921 &self,922 include_hidden: bool,923 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,924 ) -> ArrValue {925 ArrValue::new(PickObjectValues::new(926 self.clone(),927 self.fields_ex(928 include_hidden,929 #[cfg(feature = "exp-preserve-order")]930 preserve_order,931 ),932 ))933 }934 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {935 self.values_ex(936 false,937 #[cfg(feature = "exp-preserve-order")]938 preserve_order,939 )940 }941 pub fn key_values_ex(942 &self,943 include_hidden: bool,944 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,945 ) -> ArrValue {946 ArrValue::new(PickObjectKeyValues::new(947 self.clone(),948 self.fields_ex(949 include_hidden,950 #[cfg(feature = "exp-preserve-order")]951 preserve_order,952 ),953 ))954 }955 pub fn key_values(956 &self,957 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,958 ) -> ArrValue {959 self.key_values_ex(960 false,961 #[cfg(feature = "exp-preserve-order")]962 preserve_order,963 )964 }965}966967#[allow(clippy::module_name_repetitions)]968#[must_use = "value not added unless binding() was called"]969pub struct ObjMemberBuilder<Kind> {970 kind: Kind,971 name: IStr,972 add: bool,973 visibility: Visibility,974 original_index: FieldIndex,975 location: Option<Span>,976}977978#[allow(clippy::missing_const_for_fn)]979impl<Kind> ObjMemberBuilder<Kind> {980 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {981 Self {982 kind,983 name,984 original_index,985 add: false,986 visibility: Visibility::Normal,987 location: None,988 }989 }990991 pub const fn with_add(mut self, add: bool) -> Self {992 self.add = add;993 self994 }995 pub fn add(self) -> Self {996 self.with_add(true)997 }998 pub fn with_visibility(mut self, visibility: Visibility) -> Self {999 self.visibility = visibility;1000 self1001 }1002 pub fn hide(self) -> Self {1003 self.with_visibility(Visibility::Hidden)1004 }1005 pub fn with_location(mut self, location: Span) -> Self {1006 self.location = Some(location);1007 self1008 }1009 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1010 (1011 self.kind,1012 self.name,1013 ObjMember {1014 flags: ObjFieldFlags::new(self.add, self.visibility),1015 original_index: self.original_index,1016 invoke: binding,1017 location: self.location,1018 },1019 )1020 }1021}10221023pub struct ExtendBuilder<'v>(&'v mut ObjValue);1024impl ObjMemberBuilder<ExtendBuilder<'_>> {1025 pub fn value(self, value: impl Into<Val>) {1026 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1027 }1028 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1029 self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1030 }1031 pub fn binding(self, binding: MaybeUnbound) {1032 let (receiver, name, member) = self.build_member(binding);1033 let new = receiver.0.clone();1034 *receiver.0 = new.extend_with_raw_member(name, member);1035 }1036}1use std::{2 any::Any, cell::{Cell, RefCell}, clone::Clone, cmp::Reverse, collections::hash_map::Entry, fmt::{self, Debug}, hash::{Hash, Hasher}, num::Saturating, ops::ControlFlow3};45use educe::Educe;6use jrsonnet_gcmodule::{cc_dyn, Acyclic, Cc, Trace, Weak};7use jrsonnet_interner::IStr;8use jrsonnet_parser::Span;9use rustc_hash::{FxHashMap, FxHashSet};1011mod oop;1213pub use jrsonnet_parser::Visibility;14pub use oop::ObjValueBuilder;1516use crate::{17 arr::{PickObjectKeyValues, PickObjectValues},18 bail,19 error::{suggest_object_fields, ErrorKind::*},20 identity_hash,21 operator::evaluate_add_op,22 val::{ArrValue, ThunkValue},23 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27pub mod ordering {28 #![allow(29 // This module works as stub for preserve-order feature30 clippy::unused_self,31 )]3233 use jrsonnet_gcmodule::Trace;3435 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]36 pub struct FieldIndex(());37 impl FieldIndex {38 pub fn absolute(_v: u32) -> Self {39 Self(())40 }41 #[must_use]42 pub const fn next(self) -> Self {43 Self(())44 }45 }4647 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]48 pub struct SuperDepth(());49 impl SuperDepth {50 pub(super) fn deepen(self) {}51 }52}5354#[cfg(feature = "exp-preserve-order")]55pub mod ordering {56 use jrsonnet_gcmodule::Trace;5758 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]59 pub struct FieldIndex(u32);60 impl FieldIndex {61 pub fn absolute(v: u32) -> Self {62 Self(v)63 }64 #[must_use]65 pub fn next(self) -> Self {66 Self(self.0 + 1)67 }68 }6970 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]71 pub struct SuperDepth(u32);72 impl SuperDepth {73 pub(super) fn deepen(&mut self) {74 self.0 += 1;75 }76 }77}7879use ordering::{FieldIndex, SuperDepth};8081#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]82pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);83impl FieldSortKey {84 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {85 Self(Reverse(depth), index)86 }87}8889// 0 - add90// 12 - visibility91#[derive(Clone, Copy)]92pub struct ObjFieldFlags(u8);93impl ObjFieldFlags {94 fn new(add: bool, visibility: Visibility) -> Self {95 let mut v = 0;96 if add {97 v |= 1;98 }99 v |= match visibility {100 Visibility::Normal => 0b000,101 Visibility::Hidden => 0b010,102 Visibility::Unhide => 0b100,103 };104 Self(v)105 }106 pub fn add(&self) -> bool {107 self.0 & 1 != 0108 }109 pub fn visibility(&self) -> Visibility {110 match (self.0 & 0b110) >> 1 {111 0b00 => Visibility::Normal,112 0b01 => Visibility::Hidden,113 0b10 => Visibility::Unhide,114 _ => unreachable!(),115 }116 }117}118impl Debug for ObjFieldFlags {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120 f.debug_struct("ObjFieldFlags")121 .field("add", &self.add())122 .field("visibility", &self.visibility())123 .finish()124 }125}126127#[allow(clippy::module_name_repetitions)]128#[derive(Debug, Trace)]129pub struct ObjMember {130 #[trace(skip)]131 flags: ObjFieldFlags,132 original_index: FieldIndex,133 pub invoke: MaybeUnbound,134 pub location: Option<Span>,135}136137cc_dyn!(CcObjectAssertion, ObjectAssertion);138pub trait ObjectAssertion: Trace {139 fn run(&self, sup_this: SupThis) -> Result<()>;140}141142// Field => This143144#[derive(Trace, Debug)]145enum CacheValue {146 Cached(Result<Option<Val>>),147 Pending,148}149150pub type EnumFieldsHandler<'a> =151 dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;152153pub enum EnumFields {154 Normal(Visibility),155 Omit(Skip),156}157158#[derive(Trace, Clone)]159pub enum GetFor {160 // Return value161 Final(Val),162 // Continue iterating over cores, add current value to sum stack163 SuperPlus(Val),164 // Ignore the field value, stop at this layer instead165 Omit(#[trace(skip)] Skip),166 NotFound,167}168169#[derive(Acyclic, Clone)]170pub enum FieldVisibility {171 Found(Visibility),172 Omit(Skip),173 NotFound,174}175176#[derive(Acyclic, Clone)]177pub enum HasFieldIncludeHidden {178 Exists,179 NotFound,180 Omit(Skip),181}182183type Skip = Saturating<usize>;184185pub trait ObjectCore: Trace + Any + Debug {186 // If callback returns false, iteration stops, and this call returns false.187 fn enum_fields_core(188 &self,189 super_depth: &mut SuperDepth,190 handler: &mut EnumFieldsHandler<'_>,191 ) -> bool;192193 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;194195 fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;196 fn field_visibility_core(&self, field: IStr) -> FieldVisibility;197198 fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;199}200201#[derive(Clone, Trace)]202pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);203impl Debug for WeakObjValue {204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {205 f.debug_tuple("WeakObjValue").finish()206 }207}208209impl PartialEq for WeakObjValue {210 fn eq(&self, other: &Self) -> bool {211 Weak::ptr_eq(&self.0, &other.0)212 }213}214215impl Eq for WeakObjValue {}216impl Hash for WeakObjValue {217 fn hash<H: Hasher>(&self, hasher: &mut H) {218 // Safety: usize is POD219 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };220 hasher.write_usize(addr);221 }222}223224cc_dyn!(225 #[derive(Clone, Debug)]226 CcObjectCore, ObjectCore,227 pub fn new() {...}228);229#[derive(Trace, Educe)]230#[educe(Debug)]231struct ObjValueInner {232 cores: Vec<CcObjectCore>,233 assertions_ran: Cell<bool>,234 value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,235}236237thread_local! {238 static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();239}240fn is_asserting(obj: &ObjValue) -> bool {241 RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))242}243/// Returns false if already asserting244fn start_asserting(obj: &ObjValue) -> bool {245 RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))246}247fn finish_asserting(obj: &ObjValue) {248 RUNNING_ASSERTIONS.with_borrow_mut(|v| {249 let r = v.remove(obj);250 debug_assert!(251 r,252 "finish_asserting was called before start_asserting or twice"253 );254 });255}256257thread_local! {258 static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {259 cores: vec![],260 assertions_ran: Cell::new(true),261 value_cache: RefCell::default(),262 }))263}264265#[allow(clippy::module_name_repetitions)]266#[derive(Clone, Trace, Debug, Educe)]267#[educe(PartialEq, Hash, Eq)]268pub struct ObjValue(269 #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,270);271272impl ObjValue {273 pub fn empty() -> Self {274 EMPTY_OBJ.with(Clone::clone)275 }276 pub fn is_empty(&self) -> bool {277 self.0.cores.is_empty() || self.len() == 0278 }279}280281#[derive(Trace, Debug)]282struct StandaloneSuperCore {283 sup: CoreIdx,284 this: ObjValue,285}286impl ObjectCore for StandaloneSuperCore {287 fn enum_fields_core(288 &self,289 super_depth: &mut SuperDepth,290 handler: &mut EnumFieldsHandler<'_>,291 ) -> bool {292 self.this.enum_fields_idx(super_depth, handler, self.sup)293 }294295 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {296 if self.this.has_field_include_hidden_idx(name, self.sup) {297 HasFieldIncludeHidden::Exists298 } else {299 HasFieldIncludeHidden::NotFound300 }301 }302303 fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {304 if omit_only {305 return Ok(GetFor::NotFound);306 }307 let v = self.this.get_idx(key, self.sup)?;308 Ok(v.map_or(GetFor::NotFound, GetFor::Final))309 }310311 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {312 self.this313 .field_visibility_idx(field, self.sup)314 .map_or(FieldVisibility::NotFound, FieldVisibility::Found)315 }316317 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {318 self.this.run_assertions()319 }320}321322#[derive(Debug, Acyclic)]323struct OmitFieldsCore {324 omit: FxHashSet<IStr>,325 prev_layers: usize,326}327impl ObjectCore for OmitFieldsCore {328 fn enum_fields_core(329 &self,330 super_depth: &mut SuperDepth,331 handler: &mut EnumFieldsHandler<'_>,332 ) -> bool {333 let mut fi = FieldIndex::default();334 for f in &self.omit {335 if handler(336 *super_depth,337 fi,338 f.clone(),339 EnumFields::Omit(Saturating(self.prev_layers)),340 ) == ControlFlow::Break(())341 {342 return false;343 }344 fi = fi.next();345 }346 true347 }348349 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {350 if self.omit.contains(&name) {351 return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));352 }353 HasFieldIncludeHidden::NotFound354 }355356 fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {357 if self.omit.contains(&key) {358 return Ok(GetFor::Omit(Saturating(self.prev_layers)));359 }360 Ok(GetFor::NotFound)361 }362363 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {364 if self.omit.contains(&field) {365 return FieldVisibility::Omit(Saturating(self.prev_layers));366 }367 FieldVisibility::NotFound368 }369370 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {371 Ok(())372 }373}374375#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]376struct CoreIdx {377 idx: usize,378}379impl CoreIdx {380 fn super_exists(self) -> bool {381 self.idx != 0382 }383}384#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]385pub struct SupThis {386 sup: CoreIdx,387 this: ObjValue,388}389impl SupThis {390 pub fn has_super(&self) -> bool {391 self.sup.super_exists()392 }393 /// Implementation of `"field" in super` operation,394 /// works faster than standalone super path.395 ///396 /// In case of no `super` existence, returns false.397 pub fn field_in_super(&self, field: IStr) -> bool {398 self.this.has_field_include_hidden_idx(field, self.sup)399 }400 /// Implementation of `super.field` operation,401 /// works faster than standalone super path.402 ///403 /// In case of no `super` existence, returns `NoSuperFound`404 pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {405 if !self.sup.super_exists() {406 bail!(NoSuperFound);407 }408 self.this.get_idx(field, self.sup)409 }410 /// `super` with `self` overriden for top-level lookups.411 /// Exists when super appears outside of `super.field`/`"field" in super` expressions412 /// Exclusive to jrsonnet.413 ///414 /// Might return `NoSuperFound` error.415 pub fn standalone_super(&self) -> Result<ObjValue> {416 if !self.sup.super_exists() {417 bail!(NoSuperFound)418 }419 let mut out = ObjValue::builder();420 out.reserve_cores(1).extend_with_core(StandaloneSuperCore {421 sup: self.sup,422 this: self.this.clone(),423 });424 Ok(out.build())425 }426 pub fn this(&self) -> &ObjValue {427 &self.this428 }429 pub fn downgrade(self) -> WeakSupThis {430 WeakSupThis {431 sup: self.sup,432 this: self.this.downgrade(),433 }434 }435}436#[derive(Trace, PartialEq, Eq, Hash, Debug)]437pub struct WeakSupThis {438 sup: CoreIdx,439 this: WeakObjValue,440}441442impl ObjValue {443 pub fn builder() -> ObjValueBuilder {444 ObjValueBuilder::new()445 }446 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {447 ObjValueBuilder::with_capacity(capacity)448 }449 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {450 let mut out = ObjValueBuilder::with_capacity(1);451 out.with_super(self);452 let mut member = out.field(key);453 if value.flags.add() {454 member = member.add();455 }456 if let Some(loc) = value.location {457 member = member.with_location(loc);458 }459 let _ = member460 .with_visibility(value.flags.visibility())461 .binding(value.invoke);462 out.build()463 }464 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {465 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())466 }467468 pub fn extend(&mut self) -> ObjValueBuilder {469 let mut out = ObjValueBuilder::new();470 out.with_super(self.clone());471 out472 }473474 #[must_use]475 pub fn extend_from(&self, sup: Self) -> Self {476 let mut cores = sup.0.cores.clone();477 cores.extend(self.0.cores.iter().cloned());478 ObjValue(Cc::new(ObjValueInner {479 cores,480 value_cache: RefCell::default(),481 assertions_ran: Cell::new(false),482 }))483 }484 // #[must_use]485 // pub fn with_this(&self, this: Self) -> Self {486 // self.0.with_this(self.clone(), this)487 // }488 /// Returns amount of visible object fields489 /// If object only contains hidden fields - may return zero.490 pub fn len(&self) -> usize {491 self.fields_visibility()492 .values()493 .filter(|d| d.visible())494 .count()495 }496 /// For each field, calls callback.497 /// If callback returns false - ends iteration prematurely.498 ///499 /// Returns false if ended prematurely500 pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {501 let mut super_depth = SuperDepth::default();502 self.enum_fields_idx(503 &mut super_depth,504 handler,505 CoreIdx {506 idx: self.0.cores.len(),507 },508 )509 }510 fn enum_fields_idx(511 &self,512 super_depth: &mut SuperDepth,513 handler: &mut EnumFieldsHandler<'_>,514 idx: CoreIdx,515 ) -> bool {516 for core in self.0.cores[..idx.idx].iter().rev() {517 if !core.0.enum_fields_core(super_depth, handler) {518 return false;519 }520 super_depth.deepen();521 }522 true523 }524525 pub fn has_field_include_hidden(&self, name: IStr) -> bool {526 self.has_field_include_hidden_idx(527 name,528 CoreIdx {529 idx: self.0.cores.len(),530 },531 )532 }533 fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {534 let mut skip = Saturating(0usize);535 for ele in self.0.cores[..core.idx].iter().rev() {536 match ele.0.has_field_include_hidden_core(name.clone()) {537 HasFieldIncludeHidden::Exists => {538 if skip.0 == 0 {539 return true;540 }541 }542 HasFieldIncludeHidden::Omit(new_skip) => {543 // +1 including this core544 skip = skip.max(new_skip + Saturating(1));545 }546 HasFieldIncludeHidden::NotFound => {}547 }548 skip -= 1;549 }550 false551 }552 pub fn has_field(&self, name: IStr) -> bool {553 match self.field_visibility(name) {554 Some(Visibility::Unhide | Visibility::Normal) => true,555 Some(Visibility::Hidden) | None => false,556 }557 }558 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {559 if include_hidden {560 self.has_field_include_hidden(name)561 } else {562 self.has_field(name)563 }564 }565 pub fn get(&self, key: IStr) -> Result<Option<Val>> {566 self.get_idx(567 key,568 CoreIdx {569 idx: self.0.cores.len(),570 },571 )572 }573574 fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {575 let cache_key = (key.clone(), core);576 {577 let mut cache = self.0.value_cache.borrow_mut();578 // entry_ref candidate?579 match cache.entry(cache_key.clone()) {580 Entry::Occupied(v) => match v.get() {581 CacheValue::Cached(v) => return v.clone(),582 CacheValue::Pending => {583 if !is_asserting(self) {584 bail!(InfiniteRecursionDetected);585 }586 }587 },588 Entry::Vacant(v) => {589 v.insert(CacheValue::Pending);590 }591 };592 }593 let result = self.get_idx_uncached(key, core);594 {595 let mut cache = self.0.value_cache.borrow_mut();596 cache.insert(cache_key, CacheValue::Cached(result.clone()));597 }598 result599 }600 fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {601 self.run_assertions()?;602 let mut add_stack = Vec::with_capacity(2);603 let mut skip = Saturating(0);604 for (sup, core) in self.0.cores[..core.idx].iter().enumerate().rev() {605 let sup_this = SupThis {606 sup: CoreIdx { idx: sup },607 this: self.clone(),608 };609 match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {610 GetFor::Final(val) if add_stack.is_empty() => {611 if skip.0 == 0 {612 return Ok(Some(val));613 }614 }615 GetFor::Final(val) => {616 if skip.0 == 0 {617 add_stack.push(val);618 break;619 }620 }621 GetFor::SuperPlus(val) => {622 if skip.0 == 0 {623 add_stack.push(val);624 }625 }626 GetFor::Omit(new_skip) => {627 // +1 including this core628 skip = skip.max(new_skip + Saturating(1));629 }630 GetFor::NotFound => {}631 }632 skip -= 1;633 }634 if add_stack.is_empty() {635 // None of layers had this field636 return Ok(None);637 } else if add_stack.len() == 1 {638 // A layer had this field, but it wanted this field to be added with super.639 // However, no super had this field, fail-safe640 return Ok(Some(add_stack.pop().expect("single element on stack")));641 }642 let mut values = add_stack.into_iter().rev();643 let init = values.next().expect("at least 2 elements");644645 values646 .try_fold(init, |a, b| evaluate_add_op(&a, &b))647 .map(Some)648649 // self.0.get_raw(key, this)650 }651652 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {653 let Some(value) = self.get(key.clone())? else {654 let suggestions = suggest_object_fields(self, key.clone());655 bail!(NoSuchField(key, suggestions))656 };657 Ok(value)658 }659660 fn field_visibility(&self, field: IStr) -> Option<Visibility> {661 self.field_visibility_idx(662 field,663 CoreIdx {664 idx: self.0.cores.len(),665 },666 )667 }668 fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {669 let mut exists = false;670 let mut skip = Saturating(0usize);671 for ele in self.0.cores[..core.idx].iter().rev() {672 let vis = ele.0.field_visibility_core(field.clone());673 match vis {674 FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {675 if skip.0 == 0 {676 return Some(vis);677 }678 }679 FieldVisibility::Found(Visibility::Normal) => {680 if skip.0 == 0 {681 exists = true;682 }683 }684 FieldVisibility::NotFound => {}685 FieldVisibility::Omit(new_skip) => {686 // +1 including this core687 skip = skip.max(new_skip + Saturating(1));688 }689 }690 skip -= 1;691 }692 exists.then_some(Visibility::Normal)693 }694695 pub fn run_assertions(&self) -> Result<()> {696 if self.0.assertions_ran.get() {697 return Ok(());698 }699 if !start_asserting(self) {700 return Ok(());701 }702 for (idx, ele) in self.0.cores.iter().enumerate() {703 let sup_this = SupThis {704 sup: CoreIdx { idx },705 this: self.clone(),706 };707 ele.0.run_assertions_core(sup_this).inspect_err(|_e| {708 finish_asserting(self);709 })?;710 }711 finish_asserting(self);712 self.0.assertions_ran.set(true);713 Ok(())714 }715716 pub fn iter(717 &self,718 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,719 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {720 let fields = self.fields(721 #[cfg(feature = "exp-preserve-order")]722 preserve_order,723 );724 fields.into_iter().map(|field| {725 (726 field.clone(),727 self.get(field)728 .map(|opt| opt.expect("iterating over keys, field exists")),729 )730 })731 }732 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {733 #[derive(Trace)]734 struct ObjFieldThunk {735 obj: ObjValue,736 key: IStr,737 }738 impl ThunkValue for ObjFieldThunk {739 type Output = Val;740741 fn get(&self) -> Result<Self::Output> {742 self.obj743 .get(self.key.clone())744 .transpose()745 .expect("field existence checked")746 }747 }748749 if !self.has_field_ex(key.clone(), true) {750 return None;751 }752753 Some(Thunk::new(ObjFieldThunk {754 obj: self.clone(),755 key,756 }))757 }758 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {759 #[derive(Trace)]760 struct ObjFieldThunk {761 obj: ObjValue,762 key: IStr,763 }764 impl ThunkValue for ObjFieldThunk {765 type Output = Val;766767 fn get(&self) -> Result<Self::Output> {768 self.obj.get_or_bail(self.key.clone())769 }770 }771772 Thunk::new(ObjFieldThunk {773 obj: self.clone(),774 key,775 })776 }777 pub fn ptr_eq(a: &Self, b: &Self) -> bool {778 Cc::ptr_eq(&a.0, &b.0)779 }780 pub fn downgrade(self) -> WeakObjValue {781 WeakObjValue(self.0.downgrade())782 }783}784785#[derive(Debug)]786struct FieldVisibilityData {787 omitted_until: Saturating<usize>,788 exists_visible: Option<Visibility>,789 #[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]790 key: FieldSortKey,791}792impl FieldVisibilityData {793 fn visible(&self) -> bool {794 self.exists_visible795 .expect("non-existing fields shall be dropped at the end of fn fields_visibility()")796 .is_visible()797 }798 #[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]799 fn sort_key(&self) -> FieldSortKey {800 self.key801 }802}803804impl ObjValue {805 fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {806 let mut out = FxHashMap::default();807808 let mut super_depth = SuperDepth::default();809 let mut omit_index = Saturating(0);810 for core in self.0.cores.iter().rev() {811 core.0812 .enum_fields_core(&mut super_depth, &mut |depth, index, name, visibility| {813 let entry = out.entry(name);814 let data = entry.or_insert_with(|| FieldVisibilityData {815 exists_visible: None,816 key: FieldSortKey::new(depth, index),817 omitted_until: omit_index,818 });819 match visibility {820 EnumFields::Omit(new_skip) => {821 // +1 including this core822 data.omitted_until = data823 .omitted_until824 .max(omit_index + new_skip + Saturating(1));825 }826 EnumFields::Normal(Visibility::Normal) => {827 if data.omitted_until <= omit_index && data.exists_visible.is_none() {828 data.exists_visible = Some(Visibility::Normal);829 }830 }831 EnumFields::Normal(Visibility::Hidden) => {832 if data.omitted_until <= omit_index {833 data.exists_visible = Some(match data.exists_visible {834 // We're iterating in reverse, later unhide is preserved835 Some(Visibility::Unhide) => Visibility::Unhide,836 _ => Visibility::Hidden,837 });838 }839 }840 EnumFields::Normal(Visibility::Unhide) => {841 if data.omitted_until <= omit_index {842 data.exists_visible = Some(match data.exists_visible {843 // We're iterating in reverse, later hide is preserved844 Some(Visibility::Hidden) => Visibility::Hidden,845 _ => Visibility::Unhide,846 });847 }848 }849 }850 ControlFlow::Continue(())851 });852853 super_depth.deepen();854 omit_index += 1;855 }856857 out.retain(|_, v| v.exists_visible.is_some());858859 out860 }861 pub fn fields_ex(862 &self,863 include_hidden: bool,864 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,865 ) -> Vec<IStr> {866 #[cfg(feature = "exp-preserve-order")]867 if preserve_order {868 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self869 .fields_visibility()870 .into_iter()871 .filter(|(_, d)| include_hidden || d.visible())872 .enumerate()873 .map(|(idx, (k, d))| (k, (d.sort_key(), idx)))874 .unzip();875 keys.sort_unstable_by_key(|v| v.0);876 // Reorder in-place by resulting indexes877 for i in 0..fields.len() {878 let x = fields[i].clone();879 let mut j = i;880 loop {881 let k = keys[j].1;882 keys[j].1 = j;883 if k == i {884 break;885 }886 fields[j] = fields[k].clone();887 j = k;888 }889 fields[j] = x;890 }891 return fields;892 }893894 let mut fields: Vec<_> = self895 .fields_visibility()896 .into_iter()897 .filter(|(_, d)| include_hidden || d.visible())898 .map(|(k, _)| k)899 .collect();900 fields.sort_unstable();901 fields902 }903 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {904 self.fields_ex(905 false,906 #[cfg(feature = "exp-preserve-order")]907 preserve_order,908 )909 }910 pub fn values_ex(911 &self,912 include_hidden: bool,913 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,914 ) -> ArrValue {915 ArrValue::new(PickObjectValues::new(916 self.clone(),917 self.fields_ex(918 include_hidden,919 #[cfg(feature = "exp-preserve-order")]920 preserve_order,921 ),922 ))923 }924 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {925 self.values_ex(926 false,927 #[cfg(feature = "exp-preserve-order")]928 preserve_order,929 )930 }931 pub fn key_values_ex(932 &self,933 include_hidden: bool,934 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,935 ) -> ArrValue {936 ArrValue::new(PickObjectKeyValues::new(937 self.clone(),938 self.fields_ex(939 include_hidden,940 #[cfg(feature = "exp-preserve-order")]941 preserve_order,942 ),943 ))944 }945 pub fn key_values(946 &self,947 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,948 ) -> ArrValue {949 self.key_values_ex(950 false,951 #[cfg(feature = "exp-preserve-order")]952 preserve_order,953 )954 }955}956957#[allow(clippy::module_name_repetitions)]958#[must_use = "value not added unless binding() was called"]959pub struct ObjMemberBuilder<Kind> {960 kind: Kind,961 name: IStr,962 add: bool,963 visibility: Visibility,964 original_index: FieldIndex,965 location: Option<Span>,966}967968#[allow(clippy::missing_const_for_fn)]969impl<Kind> ObjMemberBuilder<Kind> {970 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {971 Self {972 kind,973 name,974 original_index,975 add: false,976 visibility: Visibility::Normal,977 location: None,978 }979 }980981 pub const fn with_add(mut self, add: bool) -> Self {982 self.add = add;983 self984 }985 pub fn add(self) -> Self {986 self.with_add(true)987 }988 pub fn with_visibility(mut self, visibility: Visibility) -> Self {989 self.visibility = visibility;990 self991 }992 pub fn hide(self) -> Self {993 self.with_visibility(Visibility::Hidden)994 }995 pub fn with_location(mut self, location: Span) -> Self {996 self.location = Some(location);997 self998 }999 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1000 (1001 self.kind,1002 self.name,1003 ObjMember {1004 flags: ObjFieldFlags::new(self.add, self.visibility),1005 original_index: self.original_index,1006 invoke: binding,1007 location: self.location,1008 },1009 )1010 }1011}10121013pub struct ExtendBuilder<'v>(&'v mut ObjValue);1014impl ObjMemberBuilder<ExtendBuilder<'_>> {1015 pub fn value(self, value: impl Into<Val>) {1016 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1017 }1018 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1019 self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1020 }1021 pub fn binding(self, binding: MaybeUnbound) {1022 let (receiver, name, member) = self.build_member(binding);1023 let new = receiver.0.clone();1024 *receiver.0 = new.extend_with_raw_member(name, member);1025 }1026}crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -61,9 +61,16 @@
}
}
+#[diagnostic::on_unimplemented(
+ note = "don't implement `ParseTypedObj` directly, it is automatically provided by `FromUntyped` derive"
+)]
pub trait ParseTypedObj: Typed {
fn parse(obj: &ObjValue) -> Result<Self>;
}
+
+#[diagnostic::on_unimplemented(
+ note = "don't implement `SerializeTypedObj` directly, it is automatically provided by `IntoUntyped` derive"
+)]
pub trait SerializeTypedObj: Typed {
fn serialize(self, out: &mut ObjValueBuilder) -> Result<()>;
fn into_object(self) -> Result<ObjValue> {
crates/jrsonnet-formatter/src/comments.rsdiffbeforeafterboth--- a/crates/jrsonnet-formatter/src/comments.rs
+++ b/crates/jrsonnet-formatter/src/comments.rs
@@ -136,7 +136,7 @@
}
line = new_line.to_string();
}
- p!(out, string(line.to_string()) nl);
+ p!(out, string(line.clone()) nl);
}
}
if doc {
crates/jrsonnet-formatter/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-formatter/src/lib.rs
+++ b/crates/jrsonnet-formatter/src/lib.rs
@@ -37,8 +37,7 @@
format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);
items.into_rc_path()
};
- let items =
- new_line_group(pi!(@i; items(o.into()) items(end_comments_items.into()))).into_rc_path();
+ let items = new_line_group(pi!(@i; items(o) items(end_comments_items.into()))).into_rc_path();
let indented = with_indent(pi!(@i; nl items(items.into())));
@@ -355,48 +354,48 @@
}
impl Printable for ArgsDesc {
fn print(&self, out: &mut PrintItems) {
- let start = LineNumber::new("args start line");
- let end = LineNumber::new("args end line");
- let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {
- is_multiple_lines(condition_context, start, end)
- });
-
- let (children, end_comments) = children_between::<Arg>(
- self.syntax().clone(),
- self.l_paren_token().map(Into::into).as_ref(),
- self.r_paren_token().map(Into::into).as_ref(),
- None,
- );
-
fn gen_args(children: Vec<Child<Arg>>, multi_line: ConditionResolver) -> PrintItems {
- let mut _out = PrintItems::new();
- let out = &mut _out;
+ let mut out = PrintItems::new();
let mut args = children.into_iter().peekable();
while let Some(ele) = args.next() {
if ele.should_start_with_newline {
p!(out, nl);
}
- format_comments(&ele.before_trivia, CommentLocation::AboveItem, out);
+ format_comments(&ele.before_trivia, CommentLocation::AboveItem, &mut out);
let arg = ele.value;
if arg.name().is_some() || arg.assign_token().is_some() {
- p!(out, {arg.name()} str(" = "));
+ p!(&mut out, {arg.name()} str(" = "));
}
- p!(out, { arg.expr() });
+ p!(&mut out, { arg.expr() });
let has_more = args.peek().is_some();
if has_more {
p!(out, str(","));
} else {
p!(out, if("trailing comma", multi_line, str(",")));
}
- format_comments(&ele.inline_trivia, CommentLocation::ItemInline, out);
+ format_comments(&ele.inline_trivia, CommentLocation::ItemInline, &mut out);
if has_more {
p!(out, if_else("arg separator", multi_line, nl)(sonl));
}
}
- _out
+
+ out
}
+ let start = LineNumber::new("args start line");
+ let end = LineNumber::new("args end line");
+ let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {
+ is_multiple_lines(condition_context, start, end)
+ });
+
+ let (children, end_comments) = children_between::<Arg>(
+ self.syntax().clone(),
+ self.l_paren_token().map(Into::into).as_ref(),
+ self.r_paren_token().map(Into::into).as_ref(),
+ None,
+ );
+
let args_items = new_line_group(gen_args(children, multi_line.clone())).into_rc_path();
let args_indented = with_indent(pi!(@i; nl items(args_items.into())));
@@ -447,6 +446,7 @@
}
impl Printable for ObjBody {
+ #[allow(clippy::too_many_lines)]
fn print(&self, out: &mut PrintItems) {
match self {
Self::ObjBodyComp(l) => {
@@ -507,6 +507,30 @@
p!(out, nl <i str("}"));
}
Self::ObjBodyMemberList(l) => {
+ fn gen_members(
+ children: Vec<Child<Member>>,
+ multi_line: ConditionResolver,
+ ) -> PrintItems {
+ let mut out = PrintItems::new();
+ let mut members = children.into_iter().peekable();
+ while let Some(mem) = members.next() {
+ if mem.should_start_with_newline {
+ p!(out, nl);
+ }
+ format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);
+ p!(&mut out, { mem.value });
+ let has_more = members.peek().is_some();
+ if has_more {
+ p!(out, str(","));
+ } else {
+ p!(out, if("trailing comma", multi_line, str(",")));
+ }
+ format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);
+ p!(out, if_else("member separator", multi_line, nl)(sonl));
+ }
+ out
+ }
+
let (children, end_comments) = children_between::<Member>(
l.syntax().clone(),
l.l_brace_token().map(Into::into).as_ref(),
@@ -531,31 +555,6 @@
})
};
- fn gen_members(
- children: Vec<Child<Member>>,
- multi_line: ConditionResolver,
- ) -> PrintItems {
- let mut _out = PrintItems::new();
- let out = &mut _out;
- let mut members = children.into_iter().peekable();
- while let Some(mem) = members.next() {
- if mem.should_start_with_newline {
- p!(out, nl);
- }
- format_comments(&mem.before_trivia, CommentLocation::AboveItem, out);
- p!(out, { mem.value });
- let has_more = members.peek().is_some();
- if has_more {
- p!(out, str(","));
- } else {
- p!(out, if("trailing comma", multi_line, str(",")));
- }
- format_comments(&mem.inline_trivia, CommentLocation::ItemInline, out);
- p!(out, if_else("member separator", multi_line, nl)(sonl));
- }
- _out
- }
-
let members_items =
new_line_group(gen_members(children, multi_line.clone())).into_rc_path();
@@ -718,6 +717,27 @@
impl Printable for ExprArray {
fn print(&self, out: &mut PrintItems) {
+ fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {
+ let mut out = PrintItems::new();
+ let mut els = children.into_iter().peekable();
+ while let Some(el) = els.next() {
+ if el.should_start_with_newline {
+ p!(out, nl);
+ }
+ format_comments(&el.before_trivia, CommentLocation::AboveItem, &mut out);
+ p!(&mut out, { el.value });
+ let has_more = els.peek().is_some();
+ if has_more {
+ p!(out, str(","));
+ } else {
+ p!(out, if("trailing comma", multi_line, str(",")));
+ }
+ format_comments(&el.inline_trivia, CommentLocation::ItemInline, &mut out);
+ p!(out, if_else("element separator", multi_line, nl)(sonl));
+ }
+ out
+ }
+
let (children, end_comments) = children_between::<Expr>(
self.syntax().clone(),
self.l_brack_token().map(Into::into).as_ref(),
@@ -740,28 +760,6 @@
Rc::new(move |ctx: &mut ConditionResolverContext| is_multiple_lines(ctx, start, end))
};
- fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {
- let mut _out = PrintItems::new();
- let out = &mut _out;
- let mut els = children.into_iter().peekable();
- while let Some(el) = els.next() {
- if el.should_start_with_newline {
- p!(out, nl);
- }
- format_comments(&el.before_trivia, CommentLocation::AboveItem, out);
- p!(out, { el.value });
- let has_more = els.peek().is_some();
- if has_more {
- p!(out, str(","));
- } else {
- p!(out, if("trailing comma", multi_line, str(",")));
- }
- format_comments(&el.inline_trivia, CommentLocation::ItemInline, out);
- p!(out, if_else("element separator", multi_line, nl)(sonl))
- }
- _out
- }
-
let els_items = new_line_group(gen_elements(children, multi_line.clone())).into_rc_path();
let els = with_indent_eoi(multi_line, els_items.into(), end_comments);
@@ -800,7 +798,7 @@
Self::ExprString(s) => p!(out, { s.text() }),
Self::ExprNumber(n) => p!(out, { n.number() }),
Self::ExprArray(a) => {
- p!(out, { a })
+ p!(out, { a });
}
Self::ExprObject(obj) => {
p!(out, { obj.obj_body() });
@@ -860,6 +858,11 @@
// 0 for hard tabs
pub indent: u8,
}
+
+#[allow(
+ clippy::result_large_err,
+ reason = "TODO: there should be an intermediate representation for such reports"
+)]
pub fn format(input: &str, opts: &FormatOptions) -> Result<String, SnippetBuilder> {
let (parsed, errors) = jrsonnet_rowan_parser::parse(input);
if !errors.is_empty() {
crates/jrsonnet-macros/src/typed.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/typed.rs
+++ b/crates/jrsonnet-macros/src/typed.rs
@@ -156,7 +156,7 @@
// optional flatten is handled in same way as serde
if self.attr.flatten {
return quote! {
- #ident: <#ty as TypedObj>::parse(&obj).ok(),
+ #ident: <#ty as ParseTypedObj>::parse(&obj).ok(),
};
}
@@ -190,7 +190,7 @@
// optional flatten is handled in same way as serde
if self.attr.flatten {
return quote! {
- #ident: <#ty as TypedObj>::parse(&obj)?,
+ #ident: <#ty as ParseTypedObj>::parse(&obj)?,
};
}
@@ -232,12 +232,12 @@
if self.is_option {
quote! {
if let Some(value) = self.#ident {
- <#ty as TypedObj>::serialize(value, out)?;
+ <#ty as SerializeTypedObj>::serialize(value, out)?;
}
}
} else {
quote! {
- <#ty as TypedObj>::serialize(self.#ident, out)?;
+ <#ty as SerializeTypedObj>::serialize(self.#ident, out)?;
}
}
},
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -224,7 +224,8 @@
},
#[cfg(feature = "exp-destruct")]
Object {
- fields: Vec<(IStr, Option<Destruct>, Option<Spanned<Expr>>)>,
+ #[allow(clippy::type_complexity)]
+ fields: Vec<(IStr, Option<Destruct>, Option<Rc<Spanned<Expr>>>)>,
rest: Option<DestructRest>,
},
}
@@ -261,7 +262,7 @@
let mut out = 0;
for (_, into, _) in fields {
match into {
- Some(v) => out += v.capacity_hint(),
+ Some(v) => out += v.binds_len(),
// Field is destructured to default name
None => out += 1,
}
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -119,7 +119,7 @@
}
pub rule destruct_object(s: &ParserSettings) -> expr::Destruct
= "{" _
- fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:expr(s) {v})? {(name, into, default)})**comma()
+ fields:(name:id() into:(_ ":" _ into:destruct(s) {into})? default:(_ "=" _ v:expr(s) {v})? {(name, into, default.map(Rc::new))})**comma()
rest:(
comma() rest:destruct_rest()? {rest}
/ comma()? {None}
crates/jrsonnet-rowan-parser/src/ast.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/ast.rs
+++ b/crates/jrsonnet-rowan-parser/src/ast.rs
@@ -2,8 +2,9 @@
use crate::{SyntaxKind, SyntaxNode, SyntaxNodeChildren, SyntaxToken};
-/// The main trait to go from untyped `SyntaxNode` to a typed ast. The
-/// conversion itself has zero runtime cost: ast and syntax nodes have exactly
+/// The main trait to go from untyped `SyntaxNode` to a typed ast.
+///
+/// The conversion itself has zero runtime cost: ast and syntax nodes have exactly
/// the same representation: a pointer to the tree root and a pointer to the
/// node itself.
pub trait AstNode {
crates/jrsonnet-rowan-parser/src/event.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/event.rs
+++ b/crates/jrsonnet-rowan-parser/src/event.rs
@@ -56,7 +56,7 @@
fn text_offset(&self) -> TextSize {
if self.offset == 0 {
return 0.into();
- };
+ }
self.lexemes.get(self.offset).map_or_else(
|| {
self.lexemes
crates/jrsonnet-rowan-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/lib.rs
+++ b/crates/jrsonnet-rowan-parser/src/lib.rs
@@ -26,7 +26,7 @@
use self::{
ast::support,
- generated::nodes::{Expr, ExprBinary, ExprObjExtend},
+ generated::nodes::{Expr, ExprObjExtend},
};
pub fn parse(input: &str) -> (SourceFile, Vec<LocatedSyntaxError>) {
crates/jrsonnet-rowan-parser/src/marker.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/marker.rs
+++ b/crates/jrsonnet-rowan-parser/src/marker.rs
@@ -141,7 +141,7 @@
new_m
}
/// Create new node around existing marker
- /// If previous_pos is set - the wrapping node would not include everything that happened between wrapped node end and the current position of the parser
+ /// If `previous_pos` is set - the wrapping node would not include everything that happened between wrapped node end and the current position of the parser
fn wrap_raw(
self,
p: &mut Parser,
crates/jrsonnet-rowan-parser/src/parser.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/parser.rs
+++ b/crates/jrsonnet-rowan-parser/src/parser.rs
@@ -52,8 +52,7 @@
write!(f, "unexpected {found:?}, expecting {expected}")
}
SyntaxError::Missing { expected } => write!(f, "missing {expected}"),
- SyntaxError::Custom { error } => write!(f, "{error}"),
- SyntaxError::Hint { error } => write!(f, "{error}"),
+ SyntaxError::Custom { error } | SyntaxError::Hint { error } => write!(f, "{error}"),
}
}
}
@@ -492,7 +491,7 @@
} else {
m.complete(p, MEMBER_FIELD_NORMAL)
};
- };
+ }
while p.at_ts(COMPSPEC) {
compspecs.push(compspec(p));
}
@@ -747,7 +746,7 @@
if p.at(T![:]) {
p.bump();
destruct(p);
- };
+ }
if p.at(T![=]) {
p.bump();
expr(p);
crates/jrsonnet-rowan-parser/src/string_block.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/string_block.rs
+++ b/crates/jrsonnet-rowan-parser/src/string_block.rs
@@ -11,7 +11,7 @@
use crate::SyntaxKind;
-pub(crate) fn lex_str_block_test<'d>(lex: &mut Lexer<'d, SyntaxKind>) {
+pub(crate) fn lex_str_block_test(lex: &mut Lexer<'_, SyntaxKind>) {
let _ = lex_str_block(lex);
}
@@ -48,7 +48,7 @@
}
fn eat_if(&mut self, f: impl Fn(char) -> bool) -> usize {
- if self.peek().map(f).unwrap_or(false) {
+ if self.peek().is_some_and(f) {
self.index += 1;
return 1;
}
@@ -141,9 +141,7 @@
}
}
-pub fn collect_lexed_str_block<'s>(
- input: &'s str,
-) -> Result<CollectStrBlock<'s>, StringBlockError> {
+pub fn collect_lexed_str_block(input: &str) -> Result<CollectStrBlock<'_>, StringBlockError> {
let mut collect = CollectStrBlock {
truncate: false,
lines: vec![],
@@ -179,7 +177,7 @@
}
fn mark_line(&mut self, line: &'d str) {
- self.lines.push(line)
+ self.lines.push(line);
}
}
crates/jrsonnet-rowan-parser/src/tests.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/tests.rs
+++ b/crates/jrsonnet-rowan-parser/src/tests.rs
@@ -2,7 +2,6 @@
#![cfg(test)]
use hi_doc::{Formatting, SnippetBuilder, Text};
-use thiserror::Error;
use crate::{parse, AstNode};
@@ -14,7 +13,7 @@
if !errors.is_empty() && !text.is_empty() {
writeln!(out, "===").unwrap();
for err in &errors {
- writeln!(out, "{:?}", err).unwrap();
+ writeln!(out, "{err:?}").unwrap();
}
let mut code = text.to_string();
crates/jrsonnet-stdlib/src/regex.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/regex.rs
+++ b/crates/jrsonnet-stdlib/src/regex.rs
@@ -4,7 +4,7 @@
use jrsonnet_evaluator::{
error::{ErrorKind::*, Result},
rustc_hash::FxBuildHasher,
- typed::Typed,
+ typed::{IntoUntyped, Typed},
val::StrValue,
IStr, ObjValue, ObjValueBuilder,
};
@@ -41,7 +41,7 @@
}
}
-#[derive(Typed)]
+#[derive(Typed, IntoUntyped)]
pub struct RegexMatch {
string: IStr,
captures: Vec<IStr>,
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -41,6 +41,7 @@
}
#[builtin]
+#[allow(dead_code)]
fn assert_throw(lazy: Thunk<Val>, message: String) -> Result<bool> {
match lazy.evaluate() {
Ok(_) => {
@@ -55,6 +56,7 @@
}
#[builtin]
+#[allow(dead_code)]
fn param_names(fun: FuncVal) -> Vec<String> {
fun.params()
.iter()
tests/tests/typed_obj.rsdiffbeforeafterboth--- a/tests/tests/typed_obj.rs
+++ b/tests/tests/typed_obj.rs
@@ -9,7 +9,7 @@
};
use jrsonnet_stdlib::ContextInitializer;
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct A {
a: u32,
b: u16,
@@ -39,7 +39,7 @@
Ok(())
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct B {
a: u32,
#[typed(rename = "c")]
@@ -62,7 +62,7 @@
Ok(())
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct ObjectKind {
#[typed(rename = "apiVersion")]
api_version: String,
@@ -70,7 +70,7 @@
kind: String,
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct Object {
#[typed(flatten)]
kind: ObjectKind,
@@ -104,7 +104,7 @@
Ok(())
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct C {
a: Option<u32>,
b: u16,
@@ -142,14 +142,14 @@
Ok(())
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct D {
#[typed(flatten(ok))]
e: Option<E>,
b: u16,
}
-#[derive(Clone, Typed, PartialEq, Debug)]
+#[derive(Clone, Typed, FromUntyped, IntoUntyped, PartialEq, Debug)]
struct E {
v: u32,
}
xtask/src/sourcegen/mod.rsdiffbeforeafterboth--- a/xtask/src/sourcegen/mod.rs
+++ b/xtask/src/sourcegen/mod.rs
@@ -65,9 +65,9 @@
is_lexer_error: true,
});
}
- };
+ }
continue;
- };
+ }
let name = to_upper_snake_case(token);
eprintln!("implicit kw: {token}");
kinds.define_token(TokenKind::Keyword {
@@ -447,7 +447,7 @@
let trait_name = format_ident!("{}", trait_name);
let kinds: Vec<_> = nodes
.iter()
- .map(|name| format_ident!("{}", to_upper_snake_case(&name.name.to_string())))
+ .map(|name| format_ident!("{}", to_upper_snake_case(&name.name)))
.collect();
(
@@ -555,10 +555,10 @@
if "{}[]()$".contains(token) {
let c = token.chars().next().unwrap();
quote! { #c }
- } else if token.contains(|v| v == '$') {
+ } else if token.contains('$') {
quote! { #token }
- } else if token.chars().all(|v| ('a'..='z').contains(&v)) {
- let i = Ident::new(&token, Span::call_site());
+ } else if token.chars().all(|v: char| v.is_ascii_lowercase()) {
+ let i = Ident::new(token, Span::call_site());
quote! { #i }
} else {
let cs = token.chars().map(|c| Punct::new(c, Spacing::Joint));