1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_types::ValType;67use crate::{8 cc_ptr_eq,9 error::{Error::*, LocError},10 function::FuncVal,11 gc::TraceBox,12 stdlib::manifest::{13 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,14 },15 throw, ObjValue, Result, State,16};1718pub trait LazyValValue: Trace {19 fn get(self: Box<Self>, s: State) -> Result<Val>;20}2122#[derive(Trace)]23enum LazyValInternals {24 Computed(Val),25 Errored(LocError),26 Waiting(TraceBox<dyn LazyValValue>),27 Pending,28}2930#[allow(clippy::module_name_repetitions)]31#[derive(Clone, Trace)]32pub struct LazyVal(Cc<RefCell<LazyValInternals>>);33impl LazyVal {34 pub fn new(f: TraceBox<dyn LazyValValue>) -> Self {35 Self(Cc::new(RefCell::new(LazyValInternals::Waiting(f))))36 }37 pub fn new_resolved(val: Val) -> Self {38 Self(Cc::new(RefCell::new(LazyValInternals::Computed(val))))39 }40 pub fn force(&self, s: State) -> Result<()> {41 self.evaluate(s)?;42 Ok(())43 }44 pub fn evaluate(&self, s: State) -> Result<Val> {45 match &*self.0.borrow() {46 LazyValInternals::Computed(v) => return Ok(v.clone()),47 LazyValInternals::Errored(e) => return Err(e.clone()),48 LazyValInternals::Pending => return Err(InfiniteRecursionDetected.into()),49 LazyValInternals::Waiting(..) => (),50 };51 let value = if let LazyValInternals::Waiting(value) =52 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)53 {54 value55 } else {56 unreachable!()57 };58 let new_value = match value.0.get(s) {59 Ok(v) => v,60 Err(e) => {61 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());62 return Err(e);63 }64 };65 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());66 Ok(new_value)67 }68}6970impl Debug for LazyVal {71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72 write!(f, "Lazy")73 }74}75impl PartialEq for LazyVal {76 fn eq(&self, other: &Self) -> bool {77 cc_ptr_eq(&self.0, &other.0)78 }79}8081#[derive(Clone)]82pub enum ManifestFormat {83 YamlStream(Box<ManifestFormat>),84 Yaml {85 padding: usize,86 #[cfg(feature = "exp-preserve-order")]87 preserve_order: bool,88 },89 Json {90 padding: usize,91 #[cfg(feature = "exp-preserve-order")]92 preserve_order: bool,93 },94 ToString,95 String,96}97impl ManifestFormat {98 #[cfg(feature = "exp-preserve-order")]99 fn preserve_order(&self) -> bool {100 match self {101 ManifestFormat::YamlStream(s) => s.preserve_order(),102 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,103 ManifestFormat::Json { preserve_order, .. } => *preserve_order,104 ManifestFormat::ToString => false,105 ManifestFormat::String => false,106 }107 }108}109110#[derive(Debug, Clone, Trace)]111pub struct Slice {112 pub(crate) inner: ArrValue,113 pub(crate) from: u32,114 pub(crate) to: u32,115 pub(crate) step: u32,116}117impl Slice {118 const fn from(&self) -> usize {119 self.from as usize120 }121 const fn to(&self) -> usize {122 self.to as usize123 }124 const fn step(&self) -> usize {125 self.step as usize126 }127 const fn len(&self) -> usize {128 129 let diff = self.to() - self.from();130 let rem = diff % self.step();131 let div = diff / self.step();132133 if rem == 0 {134 div135 } else {136 div + 1137 }138 }139}140141#[derive(Debug, Clone, Trace)]142#[force_tracking]143pub enum ArrValue {144 Bytes(#[skip_trace] Rc<[u8]>),145 Lazy(Cc<Vec<LazyVal>>),146 Eager(Cc<Vec<Val>>),147 Extended(Box<(Self, Self)>),148 Range(i32, i32),149 Slice(Box<Slice>),150 Reversed(Box<Self>),151}152impl ArrValue {153 pub fn new_eager() -> Self {154 Self::Eager(Cc::new(Vec::new()))155 }156157 158 159 pub fn new_range(a: i32, b: i32) -> Self {160 assert!(a <= b);161 Self::Range(a, b)162 }163164 165 166 #[must_use]167 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {168 let len = self.len();169 let from = from.unwrap_or(0);170 let to = to.unwrap_or(len).min(len);171 let step = step.unwrap_or(1);172 assert!(from < to);173 assert!(step > 0);174175 Self::Slice(Box::new(Slice {176 inner: self,177 from: from as u32,178 to: to as u32,179 step: step as u32,180 }))181 }182183 pub fn len(&self) -> usize {184 match self {185 Self::Bytes(i) => i.len(),186 Self::Lazy(l) => l.len(),187 Self::Eager(e) => e.len(),188 Self::Extended(v) => v.0.len() + v.1.len(),189 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,190 Self::Reversed(i) => i.len(),191 Self::Slice(s) => s.len(),192 }193 }194195 pub fn is_empty(&self) -> bool {196 self.len() == 0197 }198199 pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {200 match self {201 Self::Bytes(i) => i202 .get(index)203 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),204 Self::Lazy(vec) => {205 if let Some(v) = vec.get(index) {206 Ok(Some(v.evaluate(s)?))207 } else {208 Ok(None)209 }210 }211 Self::Eager(vec) => Ok(vec.get(index).cloned()),212 Self::Extended(v) => {213 let a_len = v.0.len();214 if a_len > index {215 v.0.get(s, index)216 } else {217 v.1.get(s, index - a_len)218 }219 }220 Self::Range(a, _) => {221 if index >= self.len() {222 return Ok(None);223 }224 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))225 }226 Self::Reversed(v) => {227 let len = v.len();228 if index >= len {229 return Ok(None);230 }231 v.get(s, len - index - 1)232 }233 Self::Slice(v) => {234 let index = v.from() + index * v.step();235 if index >= v.to() {236 return Ok(None);237 }238 v.inner.get(s, index as usize)239 }240 }241 }242243 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {244 match self {245 Self::Bytes(i) => i246 .get(index)247 .map(|b| LazyVal::new_resolved(Val::Num(f64::from(*b)))),248 Self::Lazy(vec) => vec.get(index).cloned(),249 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),250 Self::Extended(v) => {251 let a_len = v.0.len();252 if a_len > index {253 v.0.get_lazy(index)254 } else {255 v.1.get_lazy(index - a_len)256 }257 }258 Self::Range(a, _) => {259 if index >= self.len() {260 return None;261 }262 Some(LazyVal::new_resolved(Val::Num(263 ((*a as isize) + index as isize) as f64,264 )))265 }266 Self::Reversed(v) => {267 let len = v.len();268 if index >= len {269 return None;270 }271 v.get_lazy(len - index - 1)272 }273 Self::Slice(s) => {274 let index = s.from() + index * s.step();275 if index >= s.to() {276 return None;277 }278 s.inner.get_lazy(index as usize)279 }280 }281 }282283 pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {284 Ok(match self {285 Self::Bytes(i) => {286 let mut out = Vec::with_capacity(i.len());287 for v in i.iter() {288 out.push(Val::Num(f64::from(*v)));289 }290 Cc::new(out)291 }292 Self::Lazy(vec) => {293 let mut out = Vec::with_capacity(vec.len());294 for item in vec.iter() {295 out.push(item.evaluate(s.clone())?);296 }297 Cc::new(out)298 }299 Self::Eager(vec) => vec.clone(),300 Self::Extended(_v) => {301 let mut out = Vec::with_capacity(self.len());302 for item in self.iter(s) {303 out.push(item?);304 }305 Cc::new(out)306 }307 Self::Range(a, b) => {308 let mut out = Vec::with_capacity(self.len());309 for i in *a..*b {310 out.push(Val::Num(f64::from(i)));311 }312 Cc::new(out)313 }314 Self::Reversed(r) => {315 let mut r = r.evaluated(s)?;316 Cc::update_with(&mut r, |v| v.reverse());317 r318 }319 Self::Slice(v) => {320 let mut out = Vec::with_capacity(v.inner.len());321 for v in v322 .inner323 .iter_lazy()324 .skip(v.from())325 .take(v.to() - v.from())326 .step_by(v.step())327 {328 out.push(v.evaluate(s.clone())?);329 }330 Cc::new(out)331 }332 })333 }334335 pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {336 (0..self.len()).map(move |idx| match self {337 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),338 Self::Lazy(l) => l[idx].evaluate(s.clone()),339 Self::Eager(e) => Ok(e[idx].clone()),340 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {341 self.get(s.clone(), idx).map(|e| e.expect("idx < len"))342 }343 })344 }345346 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {347 (0..self.len()).map(move |idx| match self {348 Self::Bytes(b) => LazyVal::new_resolved(Val::Num(f64::from(b[idx]))),349 Self::Lazy(l) => l[idx].clone(),350 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),351 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {352 self.get_lazy(idx).expect("idx < len")353 }354 })355 }356357 #[must_use]358 pub fn reversed(self) -> Self {359 Self::Reversed(Box::new(self))360 }361362 pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {363 let mut out = Vec::with_capacity(self.len());364365 for value in self.iter(s) {366 out.push(mapper(value?)?);367 }368369 Ok(Self::Eager(Cc::new(out)))370 }371372 pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {373 let mut out = Vec::with_capacity(self.len());374375 for value in self.iter(s) {376 let value = value?;377 if filter(&value)? {378 out.push(value);379 }380 }381382 Ok(Self::Eager(Cc::new(out)))383 }384385 pub fn ptr_eq(a: &Self, b: &Self) -> bool {386 match (a, b) {387 (Self::Lazy(a), Self::Lazy(b)) => cc_ptr_eq(a, b),388 (Self::Eager(a), Self::Eager(b)) => cc_ptr_eq(a, b),389 _ => false,390 }391 }392}393394impl From<Vec<LazyVal>> for ArrValue {395 fn from(v: Vec<LazyVal>) -> Self {396 Self::Lazy(Cc::new(v))397 }398}399400impl From<Vec<Val>> for ArrValue {401 fn from(v: Vec<Val>) -> Self {402 Self::Eager(Cc::new(v))403 }404}405406#[allow(clippy::module_name_repetitions)]407pub enum IndexableVal {408 Str(IStr),409 Arr(ArrValue),410}411412#[derive(Debug, Clone, Trace)]413pub enum Val {414 Bool(bool),415 Null,416 Str(IStr),417 Num(f64),418 Arr(ArrValue),419 Obj(ObjValue),420 Func(FuncVal),421}422423impl Val {424 pub const fn as_bool(&self) -> Option<bool> {425 match self {426 Val::Bool(v) => Some(*v),427 _ => None,428 }429 }430 pub const fn as_null(&self) -> Option<()> {431 match self {432 Val::Null => Some(()),433 _ => None,434 }435 }436 pub fn as_str(&self) -> Option<IStr> {437 match self {438 Val::Str(s) => Some(s.clone()),439 _ => None,440 }441 }442 pub const fn as_num(&self) -> Option<f64> {443 match self {444 Val::Num(n) => Some(*n),445 _ => None,446 }447 }448 pub fn as_arr(&self) -> Option<ArrValue> {449 match self {450 Val::Arr(a) => Some(a.clone()),451 _ => None,452 }453 }454 pub fn as_obj(&self) -> Option<ObjValue> {455 match self {456 Val::Obj(o) => Some(o.clone()),457 _ => None,458 }459 }460 pub fn as_func(&self) -> Option<FuncVal> {461 match self {462 Val::Func(f) => Some(f.clone()),463 _ => None,464 }465 }466467 468 469 pub fn new_checked_num(num: f64) -> Result<Self> {470 if num.is_finite() {471 Ok(Self::Num(num))472 } else {473 throw!(RuntimeError("overflow".into()))474 }475 }476477 pub const fn value_type(&self) -> ValType {478 match self {479 Self::Str(..) => ValType::Str,480 Self::Num(..) => ValType::Num,481 Self::Arr(..) => ValType::Arr,482 Self::Obj(..) => ValType::Obj,483 Self::Bool(_) => ValType::Bool,484 Self::Null => ValType::Null,485 Self::Func(..) => ValType::Func,486 }487 }488489 pub fn to_string(&self, s: State) -> Result<IStr> {490 Ok(match self {491 Self::Bool(true) => "true".into(),492 Self::Bool(false) => "false".into(),493 Self::Null => "null".into(),494 Self::Str(s) => s.clone(),495 v => manifest_json_ex(496 s,497 v,498 &ManifestJsonOptions {499 padding: "",500 mtype: ManifestType::ToString,501 newline: "\n",502 key_val_sep: ": ",503 #[cfg(feature = "exp-preserve-order")]504 preserve_order: false,505 },506 )?507 .into(),508 })509 }510511 512 pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {513 let obj = match self {514 Self::Obj(obj) => obj,515 _ => throw!(MultiManifestOutputIsNotAObject),516 };517 let keys = obj.fields(518 #[cfg(feature = "exp-preserve-order")]519 ty.preserve_order(),520 );521 let mut out = Vec::with_capacity(keys.len());522 for key in keys {523 let value = obj524 .get(s.clone(), key.clone())?525 .expect("item in object")526 .manifest(s.clone(), ty)?;527 out.push((key, value));528 }529 Ok(out)530 }531532 533 pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {534 let arr = match self {535 Self::Arr(a) => a,536 _ => throw!(StreamManifestOutputIsNotAArray),537 };538 let mut out = Vec::with_capacity(arr.len());539 for i in arr.iter(s.clone()) {540 out.push(i?.manifest(s.clone(), ty)?);541 }542 Ok(out)543 }544545 pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {546 Ok(match ty {547 ManifestFormat::YamlStream(format) => {548 let arr = match self {549 Self::Arr(a) => a,550 _ => throw!(StreamManifestOutputIsNotAArray),551 };552 let mut out = String::new();553554 match format as &ManifestFormat {555 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),556 ManifestFormat::String => throw!(StreamManifestCannotNestString),557 _ => {}558 };559560 if !arr.is_empty() {561 for v in arr.iter(s.clone()) {562 out.push_str("---\n");563 out.push_str(&v?.manifest(s.clone(), format)?);564 out.push('\n');565 }566 out.push_str("...");567 }568569 out.into()570 }571 ManifestFormat::Yaml {572 padding,573 #[cfg(feature = "exp-preserve-order")]574 preserve_order,575 } => self.to_yaml(576 s,577 *padding,578 #[cfg(feature = "exp-preserve-order")]579 *preserve_order,580 )?,581 ManifestFormat::Json {582 padding,583 #[cfg(feature = "exp-preserve-order")]584 preserve_order,585 } => self.to_json(586 s,587 *padding,588 #[cfg(feature = "exp-preserve-order")]589 *preserve_order,590 )?,591 ManifestFormat::ToString => self.to_string(s)?,592 ManifestFormat::String => match self {593 Self::Str(s) => s.clone(),594 _ => throw!(StringManifestOutputIsNotAString),595 },596 })597 }598599 600 pub fn to_json(601 &self,602 s: State,603 padding: usize,604 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,605 ) -> Result<IStr> {606 manifest_json_ex(607 s,608 self,609 &ManifestJsonOptions {610 padding: &" ".repeat(padding),611 mtype: if padding == 0 {612 ManifestType::Minify613 } else {614 ManifestType::Manifest615 },616 newline: "\n",617 key_val_sep: ": ",618 #[cfg(feature = "exp-preserve-order")]619 preserve_order,620 },621 )622 .map(Into::into)623 }624625 626 pub fn to_std_json(627 &self,628 s: State,629 padding: usize,630 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,631 ) -> Result<Rc<str>> {632 manifest_json_ex(633 s,634 self,635 &ManifestJsonOptions {636 padding: &" ".repeat(padding),637 mtype: ManifestType::Std,638 newline: "\n",639 key_val_sep: ": ",640 #[cfg(feature = "exp-preserve-order")]641 preserve_order,642 },643 )644 .map(Into::into)645 }646647 pub fn to_yaml(648 &self,649 s: State,650 padding: usize,651 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,652 ) -> Result<IStr> {653 let padding = &" ".repeat(padding);654 manifest_yaml_ex(655 s,656 self,657 &ManifestYamlOptions {658 padding,659 arr_element_padding: padding,660 quote_keys: false,661 #[cfg(feature = "exp-preserve-order")]662 preserve_order,663 },664 )665 .map(Into::into)666 }667 pub fn into_indexable(self) -> Result<IndexableVal> {668 Ok(match self {669 Val::Str(s) => IndexableVal::Str(s),670 Val::Arr(arr) => IndexableVal::Arr(arr),671 _ => throw!(ValueIsNotIndexable(self.value_type())),672 })673 }674}675676const fn is_function_like(val: &Val) -> bool {677 matches!(val, Val::Func(_))678}679680681pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {682 Ok(match (val_a, val_b) {683 (Val::Bool(a), Val::Bool(b)) => a == b,684 (Val::Null, Val::Null) => true,685 (Val::Str(a), Val::Str(b)) => a == b,686 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,687 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(688 "primitiveEquals operates on primitive types, got array".into(),689 )),690 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(691 "primitiveEquals operates on primitive types, got object".into(),692 )),693 (a, b) if is_function_like(a) && is_function_like(b) => {694 throw!(RuntimeError("cannot test equality of functions".into()))695 }696 (_, _) => false,697 })698}699700701pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {702 if val_a.value_type() != val_b.value_type() {703 return Ok(false);704 }705 match (val_a, val_b) {706 (Val::Arr(a), Val::Arr(b)) => {707 if ArrValue::ptr_eq(a, b) {708 return Ok(true);709 }710 if a.len() != b.len() {711 return Ok(false);712 }713 for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {714 if !equals(s.clone(), &a?, &b?)? {715 return Ok(false);716 }717 }718 Ok(true)719 }720 (Val::Obj(a), Val::Obj(b)) => {721 if ObjValue::ptr_eq(a, b) {722 return Ok(true);723 }724 let fields = a.fields(725 #[cfg(feature = "exp-preserve-order")]726 false,727 );728 if fields729 != b.fields(730 #[cfg(feature = "exp-preserve-order")]731 false,732 ) {733 return Ok(false);734 }735 for field in fields {736 if !equals(737 s.clone(),738 &a.get(s.clone(), field.clone())?.expect("field exists"),739 &b.get(s.clone(), field)?.expect("field exists"),740 )? {741 return Ok(false);742 }743 }744 Ok(true)745 }746 (a, b) => Ok(primitive_equals(a, b)?),747 }748}