difftreelog
style fix clippy warnings
in: master
5 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
@@ -466,8 +466,7 @@
0, name: ty!(string) => Val::Str;
1, rest: ty!(any);
], {
-
- Ok(DebugGcTraceValue::new(name, rest))
+ Ok(DebugGcTraceValue::create(name, rest))
})
}
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -127,8 +127,8 @@
impl Bindable for BindableMethod {
fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
Ok(LazyVal::new(Box::new(BindableMethodLazyVal {
- this: this.clone(),
- super_obj: super_obj.clone(),
+ this,
+ super_obj,
context_creator: self.context_creator.clone(),
name: self.name.clone(),
@@ -586,7 +586,7 @@
add: false,
visibility: Visibility::Normal,
invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {
- context: ctx.clone(),
+ context: ctx,
value: obj.value.clone(),
}))),
location: obj.value.1.clone(),
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -1,6 +1,6 @@
use crate::{
error::{Error::*, LocError, Result},
- throw, Context, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
+ throw, LazyBinding, LazyVal, ObjMember, ObjValue, Val,
};
use gc::Gc;
use jrsonnet_parser::Visibility;
@@ -42,7 +42,7 @@
Self::Object(out)
}
Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
- Val::DebugGcTraceValue(v) => Value::try_from(&*v.value as &Val)?,
+ Val::DebugGcTraceValue(v) => Self::try_from(&*v.value as &Val)?,
})
}
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -1,7 +1,7 @@
-use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};
+use crate::{evaluate_add_op, LazyBinding, Result, Val};
use gc::{Finalize, Gc, GcCell, Trace};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};
+use jrsonnet_parser::{ExprLocation, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
use std::hash::{Hash, Hasher};
use std::{fmt::Debug, hash::BuildHasherDefault};
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::{Error::*, LocError},7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use gc::{custom_trace, Finalize, Gc, GcCell, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{collections::HashMap, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19 fn get(self: Box<Self>) -> Result<Val>;20}2122enum LazyValInternals {23 Computed(Val),24 Errored(LocError),25 Waiting(Box<dyn LazyValValue>),26 Pending,27}28impl Finalize for LazyValInternals {}29unsafe impl Trace for LazyValInternals {30 custom_trace!(this, {31 match &this {32 LazyValInternals::Computed(v) => mark(v),33 LazyValInternals::Errored(e) => mark(e),34 LazyValInternals::Waiting(w) => mark(w),35 LazyValInternals::Pending => {}36 }37 });38}3940#[derive(Clone, Trace, Finalize)]41pub struct LazyVal(Gc<GcCell<LazyValInternals>>);42impl LazyVal {43 pub fn new(f: Box<dyn LazyValValue>) -> Self {44 Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))45 }46 pub fn new_resolved(val: Val) -> Self {47 Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))48 }49 pub fn evaluate(&self) -> Result<Val> {50 match &*self.0.borrow() {51 LazyValInternals::Computed(v) => return Ok(v.clone()),52 LazyValInternals::Errored(e) => return Err(e.clone().into()),53 LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),54 _ => (),55 };56 let value = if let LazyValInternals::Waiting(value) =57 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)58 {59 value60 } else {61 unreachable!()62 };63 let new_value = match value.get() {64 Ok(v) => v,65 Err(e) => {66 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());67 return Err(e);68 }69 };70 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());71 Ok(new_value)72 }73}7475impl Debug for LazyVal {76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {77 write!(f, "Lazy")78 }79}80impl PartialEq for LazyVal {81 fn eq(&self, other: &Self) -> bool {82 Gc::ptr_eq(&self.0, &other.0)83 }84}8586#[derive(Debug, PartialEq, Trace, Finalize)]87pub struct FuncDesc {88 pub name: IStr,89 pub ctx: Context,90 pub params: ParamsDesc,91 pub body: LocExpr,92}9394#[derive(Debug, Trace, Finalize)]95pub enum FuncVal {96 /// Plain function implemented in jsonnet97 Normal(FuncDesc),98 /// Standard library function99 Intrinsic(IStr),100 /// Library functions implemented in native101 NativeExt(IStr, Gc<NativeCallback>),102}103104impl PartialEq for FuncVal {105 fn eq(&self, other: &Self) -> bool {106 match (self, other) {107 (Self::Normal(a), Self::Normal(b)) => a == b,108 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,109 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,110 (..) => false,111 }112 }113}114impl FuncVal {115 pub fn is_ident(&self) -> bool {116 matches!(&self, Self::Intrinsic(n) if n as &str == "id")117 }118 pub fn name(&self) -> IStr {119 match self {120 Self::Normal(normal) => normal.name.clone(),121 Self::Intrinsic(name) => format!("std.{}", name).into(),122 Self::NativeExt(n, _) => format!("native.{}", n).into(),123 }124 }125 pub fn evaluate(126 &self,127 call_ctx: Context,128 loc: Option<&ExprLocation>,129 args: &ArgsDesc,130 tailstrict: bool,131 ) -> Result<Val> {132 match self {133 Self::Normal(func) => {134 let ctx = parse_function_call(135 call_ctx,136 Some(func.ctx.clone()),137 &func.params,138 args,139 tailstrict,140 )?;141 evaluate(ctx, &func.body)142 }143 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),144 Self::NativeExt(_name, handler) => {145 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;146 let mut out_args = Vec::with_capacity(handler.params.len());147 for p in handler.params.0.iter() {148 out_args.push(args.binding(p.0.clone())?.evaluate()?);149 }150 Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)151 }152 }153 }154155 pub fn evaluate_map(156 &self,157 call_ctx: Context,158 args: &HashMap<IStr, Val>,159 tailstrict: bool,160 ) -> Result<Val> {161 match self {162 Self::Normal(func) => {163 let ctx = parse_function_call_map(164 call_ctx,165 Some(func.ctx.clone()),166 &func.params,167 args,168 tailstrict,169 )?;170 evaluate(ctx, &func.body)171 }172 Self::Intrinsic(_) => todo!(),173 Self::NativeExt(_, _) => todo!(),174 }175 }176177 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {178 match self {179 Self::Normal(func) => {180 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;181 evaluate(ctx, &func.body)182 }183 Self::Intrinsic(_) => todo!(),184 Self::NativeExt(_, _) => todo!(),185 }186 }187}188189#[derive(Clone)]190pub enum ManifestFormat {191 YamlStream(Box<ManifestFormat>),192 Yaml(usize),193 Json(usize),194 ToString,195 String,196}197198#[derive(Debug, Clone)]199pub enum ArrValue {200 Lazy(Gc<Vec<LazyVal>>),201 Eager(Gc<Vec<Val>>),202 Extended(Box<(Self, Self)>),203}204impl Finalize for ArrValue {}205unsafe impl Trace for ArrValue {206 custom_trace!(this, {207 match &this {208 ArrValue::Lazy(l) => mark(l),209 ArrValue::Eager(e) => mark(e),210 ArrValue::Extended(x) => mark(x),211 }212 });213}214impl ArrValue {215 pub fn new_eager() -> Self {216 Self::Eager(Gc::new(Vec::new()))217 }218219 pub fn len(&self) -> usize {220 match self {221 Self::Lazy(l) => l.len(),222 Self::Eager(e) => e.len(),223 Self::Extended(v) => v.0.len() + v.1.len(),224 }225 }226227 pub fn is_empty(&self) -> bool {228 self.len() == 0229 }230231 pub fn get(&self, index: usize) -> Result<Option<Val>> {232 match self {233 Self::Lazy(vec) => {234 if let Some(v) = vec.get(index) {235 Ok(Some(v.evaluate()?))236 } else {237 Ok(None)238 }239 }240 Self::Eager(vec) => Ok(vec.get(index).cloned()),241 Self::Extended(v) => {242 let a_len = v.0.len();243 if a_len > index {244 v.0.get(index)245 } else {246 v.1.get(index - a_len)247 }248 }249 }250 }251252 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {253 match self {254 Self::Lazy(vec) => vec.get(index).cloned(),255 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),256 Self::Extended(v) => {257 let a_len = v.0.len();258 if a_len > index {259 v.0.get_lazy(index)260 } else {261 v.1.get_lazy(index - a_len)262 }263 }264 }265 }266267 pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {268 Ok(match self {269 Self::Lazy(vec) => {270 let mut out = Vec::with_capacity(vec.len());271 for item in vec.iter() {272 out.push(item.evaluate()?);273 }274 Gc::new(out)275 }276 Self::Eager(vec) => vec.clone(),277 Self::Extended(_v) => {278 let mut out = Vec::with_capacity(self.len());279 for item in self.iter() {280 out.push(item?);281 }282 Gc::new(out)283 }284 })285 }286287 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {288 (0..self.len()).map(move |idx| match self {289 Self::Lazy(l) => l[idx].evaluate(),290 Self::Eager(e) => Ok(e[idx].clone()),291 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),292 })293 }294295 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {296 (0..self.len()).map(move |idx| match self {297 Self::Lazy(l) => l[idx].clone(),298 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),299 Self::Extended(_) => self.get_lazy(idx).unwrap(),300 })301 }302303 pub fn reversed(self) -> Self {304 match self {305 Self::Lazy(vec) => {306 let mut out = (&vec as &Vec<_>).clone();307 out.reverse();308 Self::Lazy(Gc::new(out))309 }310 Self::Eager(vec) => {311 let mut out = (&vec as &Vec<_>).clone();312 out.reverse();313 Self::Eager(Gc::new(out))314 }315 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),316 }317 }318319 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {320 let mut out = Vec::with_capacity(self.len());321322 for value in self.iter() {323 out.push(mapper(value?)?);324 }325326 Ok(Self::Eager(Gc::new(out)))327 }328329 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {330 let mut out = Vec::with_capacity(self.len());331332 for value in self.iter() {333 let value = value?;334 if filter(&value)? {335 out.push(value);336 }337 }338339 Ok(Self::Eager(Gc::new(out)))340 }341342 pub fn ptr_eq(a: &Self, b: &Self) -> bool {343 match (a, b) {344 (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),345 (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),346 _ => false,347 }348 }349}350351impl From<Vec<LazyVal>> for ArrValue {352 fn from(v: Vec<LazyVal>) -> Self {353 Self::Lazy(Gc::new(v))354 }355}356357impl From<Vec<Val>> for ArrValue {358 fn from(v: Vec<Val>) -> Self {359 Self::Eager(Gc::new(v))360 }361}362363#[derive(Debug)]364pub struct DebugGcTraceValue {365 name: IStr,366 pub value: Box<Val>,367}368impl DebugGcTraceValue {369 fn print(&self, action: &str) {370 println!("{} {}#{:?}", action, self.name, &*self.value as *const _)371 }372}373impl Finalize for DebugGcTraceValue {374 fn finalize(&self) {375 self.print("Garbage-collecting")376 }377}378impl Drop for DebugGcTraceValue {379 fn drop(&mut self) {380 self.print("Garbage-collected")381 }382}383unsafe impl Trace for DebugGcTraceValue {384 unsafe fn trace(&self) {385 self.print("Traced");386 self.value.trace()387 }388 unsafe fn root(&self) {389 self.print("Rooted");390 self.value.root()391 }392 unsafe fn unroot(&self) {393 self.print("Unrooted");394 self.value.unroot()395 }396 fn finalize_glue(&self) {397 Finalize::finalize(self)398 }399}400impl Clone for DebugGcTraceValue {401 fn clone(&self) -> Self {402 self.print("Cloned");403 let value = DebugGcTraceValue {404 name: self.name.clone(),405 value: self.value.clone(),406 };407 value.print("I'm clone");408 value409 }410}411impl DebugGcTraceValue {412 pub fn new(name: IStr, value: Val) -> Val {413 let value = Self {414 name,415 value: Box::new(value),416 };417 value.print("Constructed");418 Val::DebugGcTraceValue(value)419 }420}421422#[derive(Debug, Clone)]423pub enum Val {424 Bool(bool),425 Null,426 Str(IStr),427 Num(f64),428 Arr(ArrValue),429 Obj(ObjValue),430 Func(Gc<FuncVal>),431 DebugGcTraceValue(DebugGcTraceValue),432}433impl Finalize for Val {}434unsafe impl Trace for Val {435 custom_trace!(this, {436 match &this {437 Val::Bool(_) => {}438 Val::Null => {}439 Val::Str(_) => {}440 Val::Num(_) => {}441 Val::Arr(a) => mark(a),442 Val::Obj(o) => mark(o),443 Val::Func(f) => mark(f),444 Val::DebugGcTraceValue(v) => mark(v),445 }446 });447}448449macro_rules! matches_unwrap {450 ($e: expr, $p: pat, $r: expr) => {451 match $e {452 $p => $r,453 _ => panic!("no match"),454 }455 };456}457impl Val {458 /// Creates `Val::Num` after checking for numeric overflow.459 /// As numbers are `f64`, we can just check for their finity.460 pub fn new_checked_num(num: f64) -> Result<Self> {461 if num.is_finite() {462 Ok(Self::Num(num))463 } else {464 throw!(RuntimeError("overflow".into()))465 }466 }467468 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {469 let this_type = self.value_type();470 if this_type != val_type {471 throw!(TypeMismatch(context, vec![val_type], this_type))472 } else {473 Ok(())474 }475 }476 pub fn unwrap_num(self) -> Result<f64> {477 Ok(matches_unwrap!(self, Self::Num(v), v))478 }479 pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {480 Ok(matches_unwrap!(self, Self::Func(v), v))481 }482 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {483 self.assert_type(context, ValType::Bool)?;484 Ok(matches_unwrap!(self, Self::Bool(v), v))485 }486 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {487 self.assert_type(context, ValType::Str)?;488 Ok(matches_unwrap!(self, Self::Str(v), v))489 }490 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {491 self.assert_type(context, ValType::Num)?;492 self.unwrap_num()493 }494 pub const fn value_type(&self) -> ValType {495 match self {496 Self::Str(..) => ValType::Str,497 Self::Num(..) => ValType::Num,498 Self::Arr(..) => ValType::Arr,499 Self::Obj(..) => ValType::Obj,500 Self::Bool(_) => ValType::Bool,501 Self::Null => ValType::Null,502 Self::Func(..) => ValType::Func,503 Self::DebugGcTraceValue(v) => v.value.value_type(),504 }505 }506507 pub fn to_string(&self) -> Result<IStr> {508 Ok(match self {509 Self::Bool(true) => "true".into(),510 Self::Bool(false) => "false".into(),511 Self::Null => "null".into(),512 Self::Str(s) => s.clone(),513 v => manifest_json_ex(514 v,515 &ManifestJsonOptions {516 padding: "",517 mtype: ManifestType::ToString,518 },519 )?520 .into(),521 })522 }523524 /// Expects value to be object, outputs (key, manifested value) pairs525 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {526 let obj = match self {527 Self::Obj(obj) => obj,528 _ => throw!(MultiManifestOutputIsNotAObject),529 };530 let keys = obj.fields();531 let mut out = Vec::with_capacity(keys.len());532 for key in keys {533 let value = obj534 .get(key.clone())?535 .expect("item in object")536 .manifest(ty)?;537 out.push((key, value));538 }539 Ok(out)540 }541542 /// Expects value to be array, outputs manifested values543 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {544 let arr = match self {545 Self::Arr(a) => a,546 _ => throw!(StreamManifestOutputIsNotAArray),547 };548 let mut out = Vec::with_capacity(arr.len());549 for i in arr.iter() {550 out.push(i?.manifest(ty)?);551 }552 Ok(out)553 }554555 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {556 Ok(match ty {557 ManifestFormat::YamlStream(format) => {558 let arr = match self {559 Self::Arr(a) => a,560 _ => throw!(StreamManifestOutputIsNotAArray),561 };562 let mut out = String::new();563564 match format as &ManifestFormat {565 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),566 ManifestFormat::String => throw!(StreamManifestCannotNestString),567 _ => {}568 };569570 if !arr.is_empty() {571 for v in arr.iter() {572 out.push_str("---\n");573 out.push_str(&v?.manifest(format)?);574 out.push('\n');575 }576 out.push_str("...");577 }578579 out.into()580 }581 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,582 ManifestFormat::Json(padding) => self.to_json(*padding)?,583 ManifestFormat::ToString => self.to_string()?,584 ManifestFormat::String => match self {585 Self::Str(s) => s.clone(),586 _ => throw!(StringManifestOutputIsNotAString),587 },588 })589 }590591 /// For manifestification592 pub fn to_json(&self, padding: usize) -> Result<IStr> {593 manifest_json_ex(594 self,595 &ManifestJsonOptions {596 padding: &" ".repeat(padding),597 mtype: if padding == 0 {598 ManifestType::Minify599 } else {600 ManifestType::Manifest601 },602 },603 )604 .map(|s| s.into())605 }606607 /// Calls `std.manifestJson`608 #[cfg(feature = "faster")]609 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {610 manifest_json_ex(611 self,612 &ManifestJsonOptions {613 padding: &" ".repeat(padding),614 mtype: ManifestType::Std,615 },616 )617 .map(|s| s.into())618 }619620 /// Calls `std.manifestJson`621 #[cfg(not(feature = "faster"))]622 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {623 with_state(|s| {624 let ctx = s625 .create_default_context()?626 .with_var("__tmp__to_json__".into(), self.clone())?;627 Ok(evaluate(628 ctx,629 &el!(Expr::Apply(630 el!(Expr::Index(631 el!(Expr::Var("std".into())),632 el!(Expr::Str("manifestJsonEx".into()))633 )),634 ArgsDesc(vec![635 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),636 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))637 ]),638 false639 )),640 )?641 .try_cast_str("to json")?)642 })643 }644 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {645 with_state(|s| {646 let ctx = s647 .create_default_context()648 .with_var("__tmp__to_json__".into(), self.clone());649 evaluate(650 ctx,651 &el!(Expr::Apply(652 el!(Expr::Index(653 el!(Expr::Var("std".into())),654 el!(Expr::Str("manifestYamlDoc".into()))655 )),656 ArgsDesc(vec![657 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),658 Arg(659 None,660 el!(Expr::Literal(if padding != 0 {661 LiteralType::True662 } else {663 LiteralType::False664 }))665 )666 ]),667 false668 )),669 )?670 .try_cast_str("to json")671 })672 }673}674675const fn is_function_like(val: &Val) -> bool {676 matches!(val, Val::Func(_))677}678679/// Native implementation of `std.primitiveEquals`680pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {681 Ok(match (val_a, val_b) {682 (Val::Bool(a), Val::Bool(b)) => a == b,683 (Val::Null, Val::Null) => true,684 (Val::Str(a), Val::Str(b)) => a == b,685 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,686 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(687 "primitiveEquals operates on primitive types, got array".into(),688 )),689 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(690 "primitiveEquals operates on primitive types, got object".into(),691 )),692 (a, b) if is_function_like(a) && is_function_like(b) => {693 throw!(RuntimeError("cannot test equality of functions".into()))694 }695 (_, _) => false,696 })697}698699/// Native implementation of `std.equals`700pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {701 if val_a.value_type() != val_b.value_type() {702 return Ok(false);703 }704 match (val_a, val_b) {705 (Val::Arr(a), Val::Arr(b)) => {706 if ArrValue::ptr_eq(a, b) {707 return Ok(true);708 }709 if a.len() != b.len() {710 return Ok(false);711 }712 for (a, b) in a.iter().zip(b.iter()) {713 if !equals(&a?, &b?)? {714 return Ok(false);715 }716 }717 Ok(true)718 }719 (Val::Obj(a), Val::Obj(b)) => {720 if ObjValue::ptr_eq(a, b) {721 return Ok(true);722 }723 let fields = a.fields();724 if fields != b.fields() {725 return Ok(false);726 }727 for field in fields {728 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {729 return Ok(false);730 }731 }732 Ok(true)733 }734 (a, b) => Ok(primitive_equals(a, b)?),735 }736}1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::{Error::*, LocError},7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use gc::{custom_trace, Finalize, Gc, GcCell, Trace};13use jrsonnet_interner::IStr;14use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LiteralType, LocExpr, ParamsDesc};15use jrsonnet_types::ValType;16use std::{collections::HashMap, fmt::Debug, rc::Rc};1718pub trait LazyValValue: Trace {19 fn get(self: Box<Self>) -> Result<Val>;20}2122enum LazyValInternals {23 Computed(Val),24 Errored(LocError),25 Waiting(Box<dyn LazyValValue>),26 Pending,27}28impl Finalize for LazyValInternals {}29unsafe impl Trace for LazyValInternals {30 custom_trace!(this, {31 match &this {32 LazyValInternals::Computed(v) => mark(v),33 LazyValInternals::Errored(e) => mark(e),34 LazyValInternals::Waiting(w) => mark(w),35 LazyValInternals::Pending => {}36 }37 });38}3940#[derive(Clone, Trace, Finalize)]41pub struct LazyVal(Gc<GcCell<LazyValInternals>>);42impl LazyVal {43 pub fn new(f: Box<dyn LazyValValue>) -> Self {44 Self(Gc::new(GcCell::new(LazyValInternals::Waiting(f))))45 }46 pub fn new_resolved(val: Val) -> Self {47 Self(Gc::new(GcCell::new(LazyValInternals::Computed(val))))48 }49 pub fn evaluate(&self) -> Result<Val> {50 match &*self.0.borrow() {51 LazyValInternals::Computed(v) => return Ok(v.clone()),52 LazyValInternals::Errored(e) => return Err(e.clone()),53 LazyValInternals::Pending => return Err(RecursiveLazyValueEvaluation.into()),54 _ => (),55 };56 let value = if let LazyValInternals::Waiting(value) =57 std::mem::replace(&mut *self.0.borrow_mut(), LazyValInternals::Pending)58 {59 value60 } else {61 unreachable!()62 };63 let new_value = match value.get() {64 Ok(v) => v,65 Err(e) => {66 *self.0.borrow_mut() = LazyValInternals::Errored(e.clone());67 return Err(e);68 }69 };70 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());71 Ok(new_value)72 }73}7475impl Debug for LazyVal {76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {77 write!(f, "Lazy")78 }79}80impl PartialEq for LazyVal {81 fn eq(&self, other: &Self) -> bool {82 Gc::ptr_eq(&self.0, &other.0)83 }84}8586#[derive(Debug, PartialEq, Trace, Finalize)]87pub struct FuncDesc {88 pub name: IStr,89 pub ctx: Context,90 pub params: ParamsDesc,91 pub body: LocExpr,92}9394#[derive(Debug, Trace, Finalize)]95pub enum FuncVal {96 /// Plain function implemented in jsonnet97 Normal(FuncDesc),98 /// Standard library function99 Intrinsic(IStr),100 /// Library functions implemented in native101 NativeExt(IStr, Gc<NativeCallback>),102}103104impl PartialEq for FuncVal {105 fn eq(&self, other: &Self) -> bool {106 match (self, other) {107 (Self::Normal(a), Self::Normal(b)) => a == b,108 (Self::Intrinsic(an), Self::Intrinsic(bn)) => an == bn,109 (Self::NativeExt(an, _), Self::NativeExt(bn, _)) => an == bn,110 (..) => false,111 }112 }113}114impl FuncVal {115 pub fn is_ident(&self) -> bool {116 matches!(&self, Self::Intrinsic(n) if n as &str == "id")117 }118 pub fn name(&self) -> IStr {119 match self {120 Self::Normal(normal) => normal.name.clone(),121 Self::Intrinsic(name) => format!("std.{}", name).into(),122 Self::NativeExt(n, _) => format!("native.{}", n).into(),123 }124 }125 pub fn evaluate(126 &self,127 call_ctx: Context,128 loc: Option<&ExprLocation>,129 args: &ArgsDesc,130 tailstrict: bool,131 ) -> Result<Val> {132 match self {133 Self::Normal(func) => {134 let ctx = parse_function_call(135 call_ctx,136 Some(func.ctx.clone()),137 &func.params,138 args,139 tailstrict,140 )?;141 evaluate(ctx, &func.body)142 }143 Self::Intrinsic(name) => call_builtin(call_ctx, loc, name, args),144 Self::NativeExt(_name, handler) => {145 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;146 let mut out_args = Vec::with_capacity(handler.params.len());147 for p in handler.params.0.iter() {148 out_args.push(args.binding(p.0.clone())?.evaluate()?);149 }150 Ok(handler.call(loc.map(|l| l.0.clone()), &out_args)?)151 }152 }153 }154155 pub fn evaluate_map(156 &self,157 call_ctx: Context,158 args: &HashMap<IStr, Val>,159 tailstrict: bool,160 ) -> Result<Val> {161 match self {162 Self::Normal(func) => {163 let ctx = parse_function_call_map(164 call_ctx,165 Some(func.ctx.clone()),166 &func.params,167 args,168 tailstrict,169 )?;170 evaluate(ctx, &func.body)171 }172 Self::Intrinsic(_) => todo!(),173 Self::NativeExt(_, _) => todo!(),174 }175 }176177 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {178 match self {179 Self::Normal(func) => {180 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;181 evaluate(ctx, &func.body)182 }183 Self::Intrinsic(_) => todo!(),184 Self::NativeExt(_, _) => todo!(),185 }186 }187}188189#[derive(Clone)]190pub enum ManifestFormat {191 YamlStream(Box<ManifestFormat>),192 Yaml(usize),193 Json(usize),194 ToString,195 String,196}197198#[derive(Debug, Clone)]199pub enum ArrValue {200 Lazy(Gc<Vec<LazyVal>>),201 Eager(Gc<Vec<Val>>),202 Extended(Box<(Self, Self)>),203}204impl Finalize for ArrValue {}205unsafe impl Trace for ArrValue {206 custom_trace!(this, {207 match &this {208 ArrValue::Lazy(l) => mark(l),209 ArrValue::Eager(e) => mark(e),210 ArrValue::Extended(x) => mark(x),211 }212 });213}214impl ArrValue {215 pub fn new_eager() -> Self {216 Self::Eager(Gc::new(Vec::new()))217 }218219 pub fn len(&self) -> usize {220 match self {221 Self::Lazy(l) => l.len(),222 Self::Eager(e) => e.len(),223 Self::Extended(v) => v.0.len() + v.1.len(),224 }225 }226227 pub fn is_empty(&self) -> bool {228 self.len() == 0229 }230231 pub fn get(&self, index: usize) -> Result<Option<Val>> {232 match self {233 Self::Lazy(vec) => {234 if let Some(v) = vec.get(index) {235 Ok(Some(v.evaluate()?))236 } else {237 Ok(None)238 }239 }240 Self::Eager(vec) => Ok(vec.get(index).cloned()),241 Self::Extended(v) => {242 let a_len = v.0.len();243 if a_len > index {244 v.0.get(index)245 } else {246 v.1.get(index - a_len)247 }248 }249 }250 }251252 pub fn get_lazy(&self, index: usize) -> Option<LazyVal> {253 match self {254 Self::Lazy(vec) => vec.get(index).cloned(),255 Self::Eager(vec) => vec.get(index).cloned().map(LazyVal::new_resolved),256 Self::Extended(v) => {257 let a_len = v.0.len();258 if a_len > index {259 v.0.get_lazy(index)260 } else {261 v.1.get_lazy(index - a_len)262 }263 }264 }265 }266267 pub fn evaluated(&self) -> Result<Gc<Vec<Val>>> {268 Ok(match self {269 Self::Lazy(vec) => {270 let mut out = Vec::with_capacity(vec.len());271 for item in vec.iter() {272 out.push(item.evaluate()?);273 }274 Gc::new(out)275 }276 Self::Eager(vec) => vec.clone(),277 Self::Extended(_v) => {278 let mut out = Vec::with_capacity(self.len());279 for item in self.iter() {280 out.push(item?);281 }282 Gc::new(out)283 }284 })285 }286287 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {288 (0..self.len()).map(move |idx| match self {289 Self::Lazy(l) => l[idx].evaluate(),290 Self::Eager(e) => Ok(e[idx].clone()),291 Self::Extended(_) => self.get(idx).map(|e| e.unwrap()),292 })293 }294295 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = LazyVal> + '_ {296 (0..self.len()).map(move |idx| match self {297 Self::Lazy(l) => l[idx].clone(),298 Self::Eager(e) => LazyVal::new_resolved(e[idx].clone()),299 Self::Extended(_) => self.get_lazy(idx).unwrap(),300 })301 }302303 pub fn reversed(self) -> Self {304 match self {305 Self::Lazy(vec) => {306 let mut out = (&vec as &Vec<_>).clone();307 out.reverse();308 Self::Lazy(Gc::new(out))309 }310 Self::Eager(vec) => {311 let mut out = (&vec as &Vec<_>).clone();312 out.reverse();313 Self::Eager(Gc::new(out))314 }315 Self::Extended(b) => Self::Extended(Box::new((b.1.reversed(), b.0.reversed()))),316 }317 }318319 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {320 let mut out = Vec::with_capacity(self.len());321322 for value in self.iter() {323 out.push(mapper(value?)?);324 }325326 Ok(Self::Eager(Gc::new(out)))327 }328329 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {330 let mut out = Vec::with_capacity(self.len());331332 for value in self.iter() {333 let value = value?;334 if filter(&value)? {335 out.push(value);336 }337 }338339 Ok(Self::Eager(Gc::new(out)))340 }341342 pub fn ptr_eq(a: &Self, b: &Self) -> bool {343 match (a, b) {344 (Self::Lazy(a), Self::Lazy(b)) => Gc::ptr_eq(a, b),345 (Self::Eager(a), Self::Eager(b)) => Gc::ptr_eq(a, b),346 _ => false,347 }348 }349}350351impl From<Vec<LazyVal>> for ArrValue {352 fn from(v: Vec<LazyVal>) -> Self {353 Self::Lazy(Gc::new(v))354 }355}356357impl From<Vec<Val>> for ArrValue {358 fn from(v: Vec<Val>) -> Self {359 Self::Eager(Gc::new(v))360 }361}362363#[derive(Debug)]364pub struct DebugGcTraceValue {365 name: IStr,366 pub value: Box<Val>,367}368impl DebugGcTraceValue {369 fn print(&self, action: &str) {370 println!("{} {}#{:?}", action, self.name, &*self.value as *const _)371 }372}373impl Finalize for DebugGcTraceValue {374 fn finalize(&self) {375 self.print("Garbage-collecting")376 }377}378impl Drop for DebugGcTraceValue {379 fn drop(&mut self) {380 self.print("Garbage-collected")381 }382}383unsafe impl Trace for DebugGcTraceValue {384 unsafe fn trace(&self) {385 self.print("Traced");386 self.value.trace()387 }388 unsafe fn root(&self) {389 self.print("Rooted");390 self.value.root()391 }392 unsafe fn unroot(&self) {393 self.print("Unrooted");394 self.value.unroot()395 }396 fn finalize_glue(&self) {397 Finalize::finalize(self)398 }399}400impl Clone for DebugGcTraceValue {401 fn clone(&self) -> Self {402 self.print("Cloned");403 let value = Self {404 name: self.name.clone(),405 value: self.value.clone(),406 };407 value.print("I'm clone");408 value409 }410}411impl DebugGcTraceValue {412 pub fn create(name: IStr, value: Val) -> Val {413 let value = Self {414 name,415 value: Box::new(value),416 };417 value.print("Constructed");418 Val::DebugGcTraceValue(value)419 }420}421422#[derive(Debug, Clone)]423pub enum Val {424 Bool(bool),425 Null,426 Str(IStr),427 Num(f64),428 Arr(ArrValue),429 Obj(ObjValue),430 Func(Gc<FuncVal>),431 DebugGcTraceValue(DebugGcTraceValue),432}433impl Finalize for Val {}434unsafe impl Trace for Val {435 custom_trace!(this, {436 match &this {437 Val::Bool(_) => {}438 Val::Null => {}439 Val::Str(_) => {}440 Val::Num(_) => {}441 Val::Arr(a) => mark(a),442 Val::Obj(o) => mark(o),443 Val::Func(f) => mark(f),444 Val::DebugGcTraceValue(v) => mark(v),445 }446 });447}448449macro_rules! matches_unwrap {450 ($e: expr, $p: pat, $r: expr) => {451 match $e {452 $p => $r,453 _ => panic!("no match"),454 }455 };456}457impl Val {458 /// Creates `Val::Num` after checking for numeric overflow.459 /// As numbers are `f64`, we can just check for their finity.460 pub fn new_checked_num(num: f64) -> Result<Self> {461 if num.is_finite() {462 Ok(Self::Num(num))463 } else {464 throw!(RuntimeError("overflow".into()))465 }466 }467468 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {469 let this_type = self.value_type();470 if this_type != val_type {471 throw!(TypeMismatch(context, vec![val_type], this_type))472 } else {473 Ok(())474 }475 }476 pub fn unwrap_num(self) -> Result<f64> {477 Ok(matches_unwrap!(self, Self::Num(v), v))478 }479 pub fn unwrap_func(self) -> Result<Gc<FuncVal>> {480 Ok(matches_unwrap!(self, Self::Func(v), v))481 }482 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {483 self.assert_type(context, ValType::Bool)?;484 Ok(matches_unwrap!(self, Self::Bool(v), v))485 }486 pub fn try_cast_str(self, context: &'static str) -> Result<IStr> {487 self.assert_type(context, ValType::Str)?;488 Ok(matches_unwrap!(self, Self::Str(v), v))489 }490 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {491 self.assert_type(context, ValType::Num)?;492 self.unwrap_num()493 }494 pub const fn value_type(&self) -> ValType {495 match self {496 Self::Str(..) => ValType::Str,497 Self::Num(..) => ValType::Num,498 Self::Arr(..) => ValType::Arr,499 Self::Obj(..) => ValType::Obj,500 Self::Bool(_) => ValType::Bool,501 Self::Null => ValType::Null,502 Self::Func(..) => ValType::Func,503 Self::DebugGcTraceValue(v) => v.value.value_type(),504 }505 }506507 pub fn to_string(&self) -> Result<IStr> {508 Ok(match self {509 Self::Bool(true) => "true".into(),510 Self::Bool(false) => "false".into(),511 Self::Null => "null".into(),512 Self::Str(s) => s.clone(),513 v => manifest_json_ex(514 v,515 &ManifestJsonOptions {516 padding: "",517 mtype: ManifestType::ToString,518 },519 )?520 .into(),521 })522 }523524 /// Expects value to be object, outputs (key, manifested value) pairs525 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {526 let obj = match self {527 Self::Obj(obj) => obj,528 _ => throw!(MultiManifestOutputIsNotAObject),529 };530 let keys = obj.fields();531 let mut out = Vec::with_capacity(keys.len());532 for key in keys {533 let value = obj534 .get(key.clone())?535 .expect("item in object")536 .manifest(ty)?;537 out.push((key, value));538 }539 Ok(out)540 }541542 /// Expects value to be array, outputs manifested values543 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {544 let arr = match self {545 Self::Arr(a) => a,546 _ => throw!(StreamManifestOutputIsNotAArray),547 };548 let mut out = Vec::with_capacity(arr.len());549 for i in arr.iter() {550 out.push(i?.manifest(ty)?);551 }552 Ok(out)553 }554555 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {556 Ok(match ty {557 ManifestFormat::YamlStream(format) => {558 let arr = match self {559 Self::Arr(a) => a,560 _ => throw!(StreamManifestOutputIsNotAArray),561 };562 let mut out = String::new();563564 match format as &ManifestFormat {565 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),566 ManifestFormat::String => throw!(StreamManifestCannotNestString),567 _ => {}568 };569570 if !arr.is_empty() {571 for v in arr.iter() {572 out.push_str("---\n");573 out.push_str(&v?.manifest(format)?);574 out.push('\n');575 }576 out.push_str("...");577 }578579 out.into()580 }581 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,582 ManifestFormat::Json(padding) => self.to_json(*padding)?,583 ManifestFormat::ToString => self.to_string()?,584 ManifestFormat::String => match self {585 Self::Str(s) => s.clone(),586 _ => throw!(StringManifestOutputIsNotAString),587 },588 })589 }590591 /// For manifestification592 pub fn to_json(&self, padding: usize) -> Result<IStr> {593 manifest_json_ex(594 self,595 &ManifestJsonOptions {596 padding: &" ".repeat(padding),597 mtype: if padding == 0 {598 ManifestType::Minify599 } else {600 ManifestType::Manifest601 },602 },603 )604 .map(|s| s.into())605 }606607 /// Calls `std.manifestJson`608 #[cfg(feature = "faster")]609 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {610 manifest_json_ex(611 self,612 &ManifestJsonOptions {613 padding: &" ".repeat(padding),614 mtype: ManifestType::Std,615 },616 )617 .map(|s| s.into())618 }619620 /// Calls `std.manifestJson`621 #[cfg(not(feature = "faster"))]622 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {623 with_state(|s| {624 let ctx = s625 .create_default_context()?626 .with_var("__tmp__to_json__".into(), self.clone())?;627 Ok(evaluate(628 ctx,629 &el!(Expr::Apply(630 el!(Expr::Index(631 el!(Expr::Var("std".into())),632 el!(Expr::Str("manifestJsonEx".into()))633 )),634 ArgsDesc(vec![635 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),636 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))637 ]),638 false639 )),640 )?641 .try_cast_str("to json")?)642 })643 }644 pub fn to_yaml(&self, padding: usize) -> Result<IStr> {645 with_state(|s| {646 let ctx = s647 .create_default_context()648 .with_var("__tmp__to_json__".into(), self.clone());649 evaluate(650 ctx,651 &el!(Expr::Apply(652 el!(Expr::Index(653 el!(Expr::Var("std".into())),654 el!(Expr::Str("manifestYamlDoc".into()))655 )),656 ArgsDesc(vec![657 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),658 Arg(659 None,660 el!(Expr::Literal(if padding != 0 {661 LiteralType::True662 } else {663 LiteralType::False664 }))665 )666 ]),667 false668 )),669 )?670 .try_cast_str("to json")671 })672 }673}674675const fn is_function_like(val: &Val) -> bool {676 matches!(val, Val::Func(_))677}678679/// Native implementation of `std.primitiveEquals`680pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {681 Ok(match (val_a, val_b) {682 (Val::Bool(a), Val::Bool(b)) => a == b,683 (Val::Null, Val::Null) => true,684 (Val::Str(a), Val::Str(b)) => a == b,685 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,686 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(687 "primitiveEquals operates on primitive types, got array".into(),688 )),689 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(690 "primitiveEquals operates on primitive types, got object".into(),691 )),692 (a, b) if is_function_like(a) && is_function_like(b) => {693 throw!(RuntimeError("cannot test equality of functions".into()))694 }695 (_, _) => false,696 })697}698699/// Native implementation of `std.equals`700pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {701 if val_a.value_type() != val_b.value_type() {702 return Ok(false);703 }704 match (val_a, val_b) {705 (Val::Arr(a), Val::Arr(b)) => {706 if ArrValue::ptr_eq(a, b) {707 return Ok(true);708 }709 if a.len() != b.len() {710 return Ok(false);711 }712 for (a, b) in a.iter().zip(b.iter()) {713 if !equals(&a?, &b?)? {714 return Ok(false);715 }716 }717 Ok(true)718 }719 (Val::Obj(a), Val::Obj(b)) => {720 if ObjValue::ptr_eq(a, b) {721 return Ok(true);722 }723 let fields = a.fields();724 if fields != b.fields() {725 return Ok(false);726 }727 for field in fields {728 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {729 return Ok(false);730 }731 }732 Ok(true)733 }734 (a, b) => Ok(primitive_equals(a, b)?),735 }736}