difftreelog
refactor split evaluation code
in: master
5 files changed
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ /dev/null
@@ -1,830 +0,0 @@
-use crate::{
- equals, error::Error::*, push, throw, with_state, ArrValue, Bindable, Context, ContextCreator,
- FuncDesc, FuncVal, FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue,
- ObjectAssertion, Result, Val,
-};
-use jrsonnet_gc::{Gc, Trace};
-use jrsonnet_interner::IStr;
-use jrsonnet_parser::{
- ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,
- ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,
- Visibility,
-};
-use jrsonnet_types::ValType;
-use rustc_hash::{FxHashMap, FxHasher};
-use std::{collections::HashMap, hash::BuildHasherDefault};
-
-pub fn evaluate_binding_in_future(
- b: &BindSpec,
- context_creator: FutureWrapper<Context>,
-) -> LazyVal {
- let b = b.clone();
- if let Some(params) = &b.params {
- let params = params.clone();
-
- #[derive(Trace)]
- #[trivially_drop]
- struct LazyMethodBinding {
- context_creator: FutureWrapper<Context>,
- name: IStr,
- params: ParamsDesc,
- value: LocExpr,
- }
- impl LazyValValue for LazyMethodBinding {
- fn get(self: Box<Self>) -> Result<Val> {
- Ok(evaluate_method(
- self.context_creator.unwrap(),
- self.name,
- self.params,
- self.value,
- ))
- }
- }
-
- LazyVal::new(Box::new(LazyMethodBinding {
- context_creator,
- name: b.name.clone(),
- params,
- value: b.value.clone(),
- }))
- } else {
- #[derive(Trace)]
- #[trivially_drop]
- struct LazyNamedBinding {
- context_creator: FutureWrapper<Context>,
- name: IStr,
- value: LocExpr,
- }
- impl LazyValValue for LazyNamedBinding {
- fn get(self: Box<Self>) -> Result<Val> {
- evaluate_named(self.context_creator.unwrap(), &self.value, self.name)
- }
- }
- LazyVal::new(Box::new(LazyNamedBinding {
- context_creator,
- name: b.name.clone(),
- value: b.value,
- }))
- }
-}
-
-pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {
- let b = b.clone();
- if let Some(params) = &b.params {
- let params = params.clone();
-
- #[derive(Trace)]
- #[trivially_drop]
- struct BindableMethodLazyVal {
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
-
- context_creator: ContextCreator,
- name: IStr,
- params: ParamsDesc,
- value: LocExpr,
- }
- impl LazyValValue for BindableMethodLazyVal {
- fn get(self: Box<Self>) -> Result<Val> {
- Ok(evaluate_method(
- self.context_creator.create(self.this, self.super_obj)?,
- self.name,
- self.params,
- self.value,
- ))
- }
- }
-
- #[derive(Trace)]
- #[trivially_drop]
- struct BindableMethod {
- context_creator: ContextCreator,
- name: IStr,
- params: ParamsDesc,
- value: LocExpr,
- }
- impl Bindable for BindableMethod {
- fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
- Ok(LazyVal::new(Box::new(BindableMethodLazyVal {
- this,
- super_obj,
-
- context_creator: self.context_creator.clone(),
- name: self.name.clone(),
- params: self.params.clone(),
- value: self.value.clone(),
- })))
- }
- }
-
- (
- b.name.clone(),
- LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {
- context_creator,
- name: b.name.clone(),
- params,
- value: b.value.clone(),
- }))),
- )
- } else {
- #[derive(Trace)]
- #[trivially_drop]
- struct BindableNamedLazyVal {
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
-
- context_creator: ContextCreator,
- name: IStr,
- value: LocExpr,
- }
- impl LazyValValue for BindableNamedLazyVal {
- fn get(self: Box<Self>) -> Result<Val> {
- evaluate_named(
- self.context_creator.create(self.this, self.super_obj)?,
- &self.value,
- self.name,
- )
- }
- }
-
- #[derive(Trace)]
- #[trivially_drop]
- struct BindableNamed {
- context_creator: ContextCreator,
- name: IStr,
- value: LocExpr,
- }
- impl Bindable for BindableNamed {
- fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
- Ok(LazyVal::new(Box::new(BindableNamedLazyVal {
- this,
- super_obj,
-
- context_creator: self.context_creator.clone(),
- name: self.name.clone(),
- value: self.value.clone(),
- })))
- }
- }
-
- (
- b.name.clone(),
- LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {
- context_creator,
- name: b.name.clone(),
- value: b.value.clone(),
- }))),
- )
- }
-}
-
-pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
- Val::Func(Gc::new(FuncVal::Normal(FuncDesc {
- name,
- ctx,
- params,
- body,
- })))
-}
-
-pub fn evaluate_field_name(
- context: Context,
- field_name: &jrsonnet_parser::FieldName,
-) -> Result<Option<IStr>> {
- Ok(match field_name {
- jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
- jrsonnet_parser::FieldName::Dyn(expr) => {
- let value = evaluate(context, expr)?;
- if matches!(value, Val::Null) {
- None
- } else {
- Some(value.try_cast_str("dynamic field name")?)
- }
- }
- })
-}
-
-pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
- Ok(match (op, b) {
- (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),
- (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),
- (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),
- (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
- })
-}
-
-pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
- Ok(match (a, b) {
- (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + v2).into()),
-
- // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
- (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),
- (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),
-
- (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),
- (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),
-
- (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.extend_from(v1.clone())),
- (Val::Arr(a), Val::Arr(b)) => {
- let mut out = Vec::with_capacity(a.len() + b.len());
- out.extend(a.iter_lazy());
- out.extend(b.iter_lazy());
- Val::Arr(out.into())
- }
- (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,
- _ => throw!(BinaryOperatorDoesNotOperateOnValues(
- BinaryOpType::Add,
- a.value_type(),
- b.value_type(),
- )),
- })
-}
-
-pub fn evaluate_binary_op_special(
- context: Context,
- a: &LocExpr,
- op: BinaryOpType,
- b: &LocExpr,
-) -> Result<Val> {
- Ok(match (evaluate(context.clone(), a)?, op, b) {
- (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),
- (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),
- (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,
- })
-}
-
-pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
- Ok(match (a, op, b) {
- (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,
-
- (a, BinaryOpType::Eq, b) => Val::Bool(equals(a, b)?),
- (a, BinaryOpType::Neq, b) => Val::Bool(!equals(a, b)?),
-
- (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),
-
- // Bool X Bool
- (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),
- (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),
-
- // Str X Str
- (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),
- (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),
- (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),
- (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),
-
- // Num X Num
- (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,
- (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {
- if *v2 <= f64::EPSILON {
- throw!(DivisionByZero)
- }
- Val::new_checked_num(v1 / v2)?
- }
-
- (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,
-
- (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),
- (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),
- (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),
- (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),
-
- (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {
- Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)
- }
- (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {
- Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)
- }
- (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {
- Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)
- }
- (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {
- if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
- }
- Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)
- }
- (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {
- if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
- }
- Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)
- }
-
- _ => throw!(BinaryOperatorDoesNotOperateOnValues(
- op,
- a.value_type(),
- b.value_type(),
- )),
- })
-}
-
-pub fn evaluate_comp(
- context: Context,
- specs: &[CompSpec],
- callback: &mut impl FnMut(Context) -> Result<()>,
-) -> Result<()> {
- match specs.get(0) {
- None => callback(context)?,
- Some(CompSpec::IfSpec(IfSpecData(cond))) => {
- if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
- evaluate_comp(context, &specs[1..], callback)?
- }
- }
- Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {
- Val::Arr(list) => {
- for item in list.iter() {
- evaluate_comp(
- context.clone().with_var(var.clone(), item?.clone()),
- &specs[1..],
- callback,
- )?
- }
- }
- _ => throw!(InComprehensionCanOnlyIterateOverArray),
- },
- }
- Ok(())
-}
-
-pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {
- let new_bindings = FutureWrapper::new();
- let future_this = FutureWrapper::new();
- let context_creator = ContextCreator(context.clone(), new_bindings.clone());
- {
- let mut bindings: FxHashMap<IStr, LazyBinding> =
- FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());
- for (n, b) in members
- .iter()
- .filter_map(|m| match m {
- Member::BindStmt(b) => Some(b.clone()),
- _ => None,
- })
- .map(|b| evaluate_binding(&b, context_creator.clone()))
- {
- bindings.insert(n, b);
- }
- new_bindings.fill(bindings);
- }
-
- let mut new_members = FxHashMap::default();
- let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();
- for member in members.iter() {
- match member {
- Member::Field(FieldMember {
- name,
- plus,
- params: None,
- visibility,
- value,
- }) => {
- let name = evaluate_field_name(context.clone(), name)?;
- if name.is_none() {
- continue;
- }
- let name = name.unwrap();
-
- #[derive(Trace)]
- #[trivially_drop]
- struct ObjMemberBinding {
- context_creator: ContextCreator,
- value: LocExpr,
- name: IStr,
- }
- impl Bindable for ObjMemberBinding {
- fn bind(
- &self,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<LazyVal> {
- Ok(LazyVal::new_resolved(evaluate_named(
- self.context_creator.create(this, super_obj)?,
- &self.value,
- self.name.clone(),
- )?))
- }
- }
- new_members.insert(
- name.clone(),
- ObjMember {
- add: *plus,
- visibility: *visibility,
- invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
- context_creator: context_creator.clone(),
- value: value.clone(),
- name,
- }))),
- location: value.1.clone(),
- },
- );
- }
- Member::Field(FieldMember {
- name,
- params: Some(params),
- value,
- ..
- }) => {
- let name = evaluate_field_name(context.clone(), name)?;
- if name.is_none() {
- continue;
- }
- let name = name.unwrap();
- #[derive(Trace)]
- #[trivially_drop]
- struct ObjMemberBinding {
- context_creator: ContextCreator,
- value: LocExpr,
- params: ParamsDesc,
- name: IStr,
- }
- impl Bindable for ObjMemberBinding {
- fn bind(
- &self,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<LazyVal> {
- Ok(LazyVal::new_resolved(evaluate_method(
- self.context_creator.create(this, super_obj)?,
- self.name.clone(),
- self.params.clone(),
- self.value.clone(),
- )))
- }
- }
- new_members.insert(
- name.clone(),
- ObjMember {
- add: false,
- visibility: Visibility::Hidden,
- invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
- context_creator: context_creator.clone(),
- value: value.clone(),
- params: params.clone(),
- name,
- }))),
- location: value.1.clone(),
- },
- );
- }
- Member::BindStmt(_) => {}
- Member::AssertStmt(stmt) => {
- #[derive(Trace)]
- #[trivially_drop]
- struct ObjectAssert {
- context_creator: ContextCreator,
- assert: AssertStmt,
- }
- impl ObjectAssertion for ObjectAssert {
- fn run(
- &self,
- this: Option<ObjValue>,
- super_obj: Option<ObjValue>,
- ) -> Result<()> {
- let ctx = self.context_creator.create(this, super_obj)?;
- evaluate_assert(ctx, &self.assert)
- }
- }
- assertions.push(Box::new(ObjectAssert {
- context_creator: context_creator.clone(),
- assert: stmt.clone(),
- }));
- }
- }
- }
- let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));
- future_this.fill(this.clone());
- Ok(this)
-}
-
-pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {
- Ok(match object {
- ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,
- ObjBody::ObjComp(obj) => {
- let future_this = FutureWrapper::new();
- let mut new_members = FxHashMap::default();
- evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {
- let new_bindings = FutureWrapper::new();
- let context_creator = ContextCreator(context.clone(), new_bindings.clone());
- let mut bindings: FxHashMap<IStr, LazyBinding> =
- FxHashMap::with_capacity_and_hasher(
- obj.pre_locals.len() + obj.post_locals.len(),
- BuildHasherDefault::default(),
- );
- for (n, b) in obj
- .pre_locals
- .iter()
- .chain(obj.post_locals.iter())
- .map(|b| evaluate_binding(b, context_creator.clone()))
- {
- bindings.insert(n, b);
- }
- new_bindings.fill(bindings.clone());
- let ctx = ctx.extend_unbound(bindings, None, None, None)?;
- let key = evaluate(ctx.clone(), &obj.key)?;
-
- match key {
- Val::Null => {}
- Val::Str(n) => {
- #[derive(Trace)]
- #[trivially_drop]
- struct ObjCompBinding {
- context: Context,
- value: LocExpr,
- }
- impl Bindable for ObjCompBinding {
- fn bind(
- &self,
- this: Option<ObjValue>,
- _super_obj: Option<ObjValue>,
- ) -> Result<LazyVal> {
- Ok(LazyVal::new_resolved(evaluate(
- self.context.clone().extend(
- FxHashMap::default(),
- None,
- this,
- None,
- ),
- &self.value,
- )?))
- }
- }
- new_members.insert(
- n,
- ObjMember {
- add: false,
- visibility: Visibility::Normal,
- invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {
- context: ctx,
- value: obj.value.clone(),
- }))),
- location: obj.value.1.clone(),
- },
- );
- }
- v => throw!(FieldMustBeStringGot(v.value_type())),
- }
-
- Ok(())
- })?;
-
- let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));
- future_this.fill(this.clone());
- this
- }
- })
-}
-
-pub fn evaluate_apply(
- context: Context,
- value: &LocExpr,
- args: &ArgsDesc,
- loc: Option<&ExprLocation>,
- tailstrict: bool,
-) -> Result<Val> {
- let value = evaluate(context.clone(), value)?;
- Ok(match value {
- Val::Func(f) => {
- let body = || f.evaluate(context, loc, args, tailstrict);
- if tailstrict {
- body()?
- } else {
- push(loc, || format!("function <{}> call", f.name()), body)?
- }
- }
- v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
- })
-}
-
-pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {
- let value = &assertion.0;
- let msg = &assertion.1;
- let assertion_result = push(
- value.1.as_ref(),
- || "assertion condition".to_owned(),
- || {
- evaluate(context.clone(), value)?
- .try_cast_bool("assertion condition should be of type `boolean`")
- },
- )?;
- if !assertion_result {
- push(
- value.1.as_ref(),
- || "assertion failure".to_owned(),
- || {
- if let Some(msg) = msg {
- throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));
- } else {
- throw!(AssertionFailed(Val::Null.to_string()?));
- }
- },
- )?
- }
- Ok(())
-}
-
-pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
- use Expr::*;
- let LocExpr(expr, _loc) = lexpr;
- Ok(match &**expr {
- Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),
- _ => evaluate(context, lexpr)?,
- })
-}
-
-pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
- use Expr::*;
- let LocExpr(expr, loc) = expr;
- Ok(match &**expr {
- Literal(LiteralType::This) => {
- Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
- }
- Literal(LiteralType::Super) => Val::Obj(
- context
- .super_obj()
- .clone()
- .ok_or(NoSuperFound)?
- .with_this(context.this().clone().unwrap()),
- ),
- Literal(LiteralType::Dollar) => {
- Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)
- }
- Literal(LiteralType::True) => Val::Bool(true),
- Literal(LiteralType::False) => Val::Bool(false),
- Literal(LiteralType::Null) => Val::Null,
- Parened(e) => evaluate(context, e)?,
- Str(v) => Val::Str(v.clone()),
- Num(v) => Val::new_checked_num(*v)?,
- BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
- UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
- Var(name) => push(
- loc.as_ref(),
- || format!("variable <{}>", name),
- || context.binding(name.clone())?.evaluate(),
- )?,
- Index(value, index) => {
- match (evaluate(context.clone(), value)?, evaluate(context, index)?) {
- (Val::Obj(v), Val::Str(s)) => {
- let sn = s.clone();
- push(
- loc.as_ref(),
- || format!("field <{}> access", sn),
- || {
- if let Some(v) = v.get(s.clone())? {
- Ok(v)
- } else if v.get("__intrinsic_namespace__".into())?.is_some() {
- Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))
- } else {
- throw!(NoSuchField(s))
- }
- },
- )?
- }
- (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
- ValType::Obj,
- ValType::Str,
- n.value_type(),
- )),
-
- (Val::Arr(v), Val::Num(n)) => {
- if n.fract() > f64::EPSILON {
- throw!(FractionalIndex)
- }
- v.get(n as usize)?
- .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
- }
- (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
- (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
- ValType::Arr,
- ValType::Num,
- n.value_type(),
- )),
-
- (Val::Str(s), Val::Num(n)) => Val::Str(
- s.chars()
- .skip(n as usize)
- .take(1)
- .collect::<String>()
- .into(),
- ),
- (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
- ValType::Str,
- ValType::Num,
- n.value_type(),
- )),
-
- (v, _) => throw!(CantIndexInto(v.value_type())),
- }
- }
- LocalExpr(bindings, returned) => {
- let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(
- bindings.len(),
- BuildHasherDefault::<FxHasher>::default(),
- );
- let future_context = Context::new_future();
- for b in bindings {
- new_bindings.insert(
- b.name.clone(),
- evaluate_binding_in_future(b, future_context.clone()),
- );
- }
- let context = context
- .extend_bound(new_bindings)
- .into_future(future_context);
- evaluate(context, &returned.clone())?
- }
- Arr(items) => {
- let mut out = Vec::with_capacity(items.len());
- for item in items {
- // TODO: Implement ArrValue::Lazy with same context for every element?
- #[derive(Trace)]
- #[trivially_drop]
- struct ArrayElement {
- context: Context,
- item: LocExpr,
- }
- impl LazyValValue for ArrayElement {
- fn get(self: Box<Self>) -> Result<Val> {
- evaluate(self.context, &self.item)
- }
- }
- out.push(LazyVal::new(Box::new(ArrayElement {
- context: context.clone(),
- item: item.clone(),
- })));
- }
- Val::Arr(out.into())
- }
- ArrComp(expr, comp_specs) => {
- let mut out = Vec::new();
- evaluate_comp(context, comp_specs, &mut |ctx| {
- out.push(evaluate(ctx, expr)?);
- Ok(())
- })?;
- Val::Arr(ArrValue::Eager(Gc::new(out)))
- }
- Obj(body) => Val::Obj(evaluate_object(context, body)?),
- ObjExtend(s, t) => evaluate_add_op(
- &evaluate(context.clone(), s)?,
- &Val::Obj(evaluate_object(context, t)?),
- )?,
- Apply(value, args, tailstrict) => {
- evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?
- }
- Function(params, body) => {
- evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
- }
- Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),
- AssertExpr(assert, returned) => {
- evaluate_assert(context.clone(), assert)?;
- evaluate(context, returned)?
- }
- ErrorStmt(e) => push(
- loc.as_ref(),
- || "error statement".to_owned(),
- || {
- throw!(RuntimeError(
- evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
- ))
- },
- )?,
- IfElse {
- cond,
- cond_then,
- cond_else,
- } => {
- if push(
- loc.as_ref(),
- || "if condition".to_owned(),
- || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
- )? {
- evaluate(context, cond_then)?
- } else {
- match cond_else {
- Some(v) => evaluate(context, v)?,
- None => Val::Null,
- }
- }
- }
- Import(path) => {
- let tmp = loc
- .clone()
- .expect("imports cannot be used without loc_data")
- .0;
- let mut import_location = tmp.to_path_buf();
- import_location.pop();
- push(
- loc.as_ref(),
- || format!("import {:?}", path),
- || with_state(|s| s.import_file(&import_location, path)),
- )?
- }
- ImportStr(path) => {
- let tmp = loc
- .clone()
- .expect("imports cannot be used without loc_data")
- .0;
- let mut import_location = tmp.to_path_buf();
- import_location.pop();
- Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
- }
- })
-}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -0,0 +1,718 @@
+use crate::{
+ error::Error::*,
+ evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
+ push, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
+ FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjMember, ObjValue, ObjectAssertion,
+ Result, Val,
+};
+use jrsonnet_gc::{Gc, Trace};
+use jrsonnet_interner::IStr;
+use jrsonnet_parser::{
+ ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, ExprLocation, FieldMember, ForSpecData,
+ IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, Visibility,
+};
+use jrsonnet_types::ValType;
+use rustc_hash::{FxHashMap, FxHasher};
+use std::{collections::HashMap, hash::BuildHasherDefault};
+pub mod operator;
+
+pub fn evaluate_binding_in_future(
+ b: &BindSpec,
+ context_creator: FutureWrapper<Context>,
+) -> LazyVal {
+ let b = b.clone();
+ if let Some(params) = &b.params {
+ let params = params.clone();
+
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct LazyMethodBinding {
+ context_creator: FutureWrapper<Context>,
+ name: IStr,
+ params: ParamsDesc,
+ value: LocExpr,
+ }
+ impl LazyValValue for LazyMethodBinding {
+ fn get(self: Box<Self>) -> Result<Val> {
+ Ok(evaluate_method(
+ self.context_creator.unwrap(),
+ self.name,
+ self.params,
+ self.value,
+ ))
+ }
+ }
+
+ LazyVal::new(Box::new(LazyMethodBinding {
+ context_creator,
+ name: b.name.clone(),
+ params,
+ value: b.value.clone(),
+ }))
+ } else {
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct LazyNamedBinding {
+ context_creator: FutureWrapper<Context>,
+ name: IStr,
+ value: LocExpr,
+ }
+ impl LazyValValue for LazyNamedBinding {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate_named(self.context_creator.unwrap(), &self.value, self.name)
+ }
+ }
+ LazyVal::new(Box::new(LazyNamedBinding {
+ context_creator,
+ name: b.name.clone(),
+ value: b.value,
+ }))
+ }
+}
+
+pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (IStr, LazyBinding) {
+ let b = b.clone();
+ if let Some(params) = &b.params {
+ let params = params.clone();
+
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct BindableMethodLazyVal {
+ this: Option<ObjValue>,
+ super_obj: Option<ObjValue>,
+
+ context_creator: ContextCreator,
+ name: IStr,
+ params: ParamsDesc,
+ value: LocExpr,
+ }
+ impl LazyValValue for BindableMethodLazyVal {
+ fn get(self: Box<Self>) -> Result<Val> {
+ Ok(evaluate_method(
+ self.context_creator.create(self.this, self.super_obj)?,
+ self.name,
+ self.params,
+ self.value,
+ ))
+ }
+ }
+
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct BindableMethod {
+ context_creator: ContextCreator,
+ name: IStr,
+ params: ParamsDesc,
+ value: LocExpr,
+ }
+ impl Bindable for BindableMethod {
+ fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
+ Ok(LazyVal::new(Box::new(BindableMethodLazyVal {
+ this,
+ super_obj,
+
+ context_creator: self.context_creator.clone(),
+ name: self.name.clone(),
+ params: self.params.clone(),
+ value: self.value.clone(),
+ })))
+ }
+ }
+
+ (
+ b.name.clone(),
+ LazyBinding::Bindable(Gc::new(Box::new(BindableMethod {
+ context_creator,
+ name: b.name.clone(),
+ params,
+ value: b.value.clone(),
+ }))),
+ )
+ } else {
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct BindableNamedLazyVal {
+ this: Option<ObjValue>,
+ super_obj: Option<ObjValue>,
+
+ context_creator: ContextCreator,
+ name: IStr,
+ value: LocExpr,
+ }
+ impl LazyValValue for BindableNamedLazyVal {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate_named(
+ self.context_creator.create(self.this, self.super_obj)?,
+ &self.value,
+ self.name,
+ )
+ }
+ }
+
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct BindableNamed {
+ context_creator: ContextCreator,
+ name: IStr,
+ value: LocExpr,
+ }
+ impl Bindable for BindableNamed {
+ fn bind(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<LazyVal> {
+ Ok(LazyVal::new(Box::new(BindableNamedLazyVal {
+ this,
+ super_obj,
+
+ context_creator: self.context_creator.clone(),
+ name: self.name.clone(),
+ value: self.value.clone(),
+ })))
+ }
+ }
+
+ (
+ b.name.clone(),
+ LazyBinding::Bindable(Gc::new(Box::new(BindableNamed {
+ context_creator,
+ name: b.name.clone(),
+ value: b.value.clone(),
+ }))),
+ )
+ }
+}
+
+pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {
+ Val::Func(Gc::new(FuncVal::Normal(FuncDesc {
+ name,
+ ctx,
+ params,
+ body,
+ })))
+}
+
+pub fn evaluate_field_name(
+ context: Context,
+ field_name: &jrsonnet_parser::FieldName,
+) -> Result<Option<IStr>> {
+ Ok(match field_name {
+ jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),
+ jrsonnet_parser::FieldName::Dyn(expr) => {
+ let value = evaluate(context, expr)?;
+ if matches!(value, Val::Null) {
+ None
+ } else {
+ Some(value.try_cast_str("dynamic field name")?)
+ }
+ }
+ })
+}
+
+pub fn evaluate_comp(
+ context: Context,
+ specs: &[CompSpec],
+ callback: &mut impl FnMut(Context) -> Result<()>,
+) -> Result<()> {
+ match specs.get(0) {
+ None => callback(context)?,
+ Some(CompSpec::IfSpec(IfSpecData(cond))) => {
+ if evaluate(context.clone(), cond)?.try_cast_bool("if spec")? {
+ evaluate_comp(context, &specs[1..], callback)?
+ }
+ }
+ Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(context.clone(), expr)? {
+ Val::Arr(list) => {
+ for item in list.iter() {
+ evaluate_comp(
+ context.clone().with_var(var.clone(), item?.clone()),
+ &specs[1..],
+ callback,
+ )?
+ }
+ }
+ _ => throw!(InComprehensionCanOnlyIterateOverArray),
+ },
+ }
+ Ok(())
+}
+
+pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {
+ let new_bindings = FutureWrapper::new();
+ let future_this = FutureWrapper::new();
+ let context_creator = ContextCreator(context.clone(), new_bindings.clone());
+ {
+ let mut bindings: FxHashMap<IStr, LazyBinding> =
+ FxHashMap::with_capacity_and_hasher(members.len(), BuildHasherDefault::default());
+ for (n, b) in members
+ .iter()
+ .filter_map(|m| match m {
+ Member::BindStmt(b) => Some(b.clone()),
+ _ => None,
+ })
+ .map(|b| evaluate_binding(&b, context_creator.clone()))
+ {
+ bindings.insert(n, b);
+ }
+ new_bindings.fill(bindings);
+ }
+
+ let mut new_members = FxHashMap::default();
+ let mut assertions: Vec<Box<dyn ObjectAssertion>> = Vec::new();
+ for member in members.iter() {
+ match member {
+ Member::Field(FieldMember {
+ name,
+ plus,
+ params: None,
+ visibility,
+ value,
+ }) => {
+ let name = evaluate_field_name(context.clone(), name)?;
+ if name.is_none() {
+ continue;
+ }
+ let name = name.unwrap();
+
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct ObjMemberBinding {
+ context_creator: ContextCreator,
+ value: LocExpr,
+ name: IStr,
+ }
+ impl Bindable for ObjMemberBinding {
+ fn bind(
+ &self,
+ this: Option<ObjValue>,
+ super_obj: Option<ObjValue>,
+ ) -> Result<LazyVal> {
+ Ok(LazyVal::new_resolved(evaluate_named(
+ self.context_creator.create(this, super_obj)?,
+ &self.value,
+ self.name.clone(),
+ )?))
+ }
+ }
+ new_members.insert(
+ name.clone(),
+ ObjMember {
+ add: *plus,
+ visibility: *visibility,
+ invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
+ context_creator: context_creator.clone(),
+ value: value.clone(),
+ name,
+ }))),
+ location: value.1.clone(),
+ },
+ );
+ }
+ Member::Field(FieldMember {
+ name,
+ params: Some(params),
+ value,
+ ..
+ }) => {
+ let name = evaluate_field_name(context.clone(), name)?;
+ if name.is_none() {
+ continue;
+ }
+ let name = name.unwrap();
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct ObjMemberBinding {
+ context_creator: ContextCreator,
+ value: LocExpr,
+ params: ParamsDesc,
+ name: IStr,
+ }
+ impl Bindable for ObjMemberBinding {
+ fn bind(
+ &self,
+ this: Option<ObjValue>,
+ super_obj: Option<ObjValue>,
+ ) -> Result<LazyVal> {
+ Ok(LazyVal::new_resolved(evaluate_method(
+ self.context_creator.create(this, super_obj)?,
+ self.name.clone(),
+ self.params.clone(),
+ self.value.clone(),
+ )))
+ }
+ }
+ new_members.insert(
+ name.clone(),
+ ObjMember {
+ add: false,
+ visibility: Visibility::Hidden,
+ invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjMemberBinding {
+ context_creator: context_creator.clone(),
+ value: value.clone(),
+ params: params.clone(),
+ name,
+ }))),
+ location: value.1.clone(),
+ },
+ );
+ }
+ Member::BindStmt(_) => {}
+ Member::AssertStmt(stmt) => {
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct ObjectAssert {
+ context_creator: ContextCreator,
+ assert: AssertStmt,
+ }
+ impl ObjectAssertion for ObjectAssert {
+ fn run(
+ &self,
+ this: Option<ObjValue>,
+ super_obj: Option<ObjValue>,
+ ) -> Result<()> {
+ let ctx = self.context_creator.create(this, super_obj)?;
+ evaluate_assert(ctx, &self.assert)
+ }
+ }
+ assertions.push(Box::new(ObjectAssert {
+ context_creator: context_creator.clone(),
+ assert: stmt.clone(),
+ }));
+ }
+ }
+ }
+ let this = ObjValue::new(None, Gc::new(new_members), Gc::new(assertions));
+ future_this.fill(this.clone());
+ Ok(this)
+}
+
+pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {
+ Ok(match object {
+ ObjBody::MemberList(members) => evaluate_member_list_object(context, members)?,
+ ObjBody::ObjComp(obj) => {
+ let future_this = FutureWrapper::new();
+ let mut new_members = FxHashMap::default();
+ evaluate_comp(context.clone(), &obj.compspecs, &mut |ctx| {
+ let new_bindings = FutureWrapper::new();
+ let context_creator = ContextCreator(context.clone(), new_bindings.clone());
+ let mut bindings: FxHashMap<IStr, LazyBinding> =
+ FxHashMap::with_capacity_and_hasher(
+ obj.pre_locals.len() + obj.post_locals.len(),
+ BuildHasherDefault::default(),
+ );
+ for (n, b) in obj
+ .pre_locals
+ .iter()
+ .chain(obj.post_locals.iter())
+ .map(|b| evaluate_binding(b, context_creator.clone()))
+ {
+ bindings.insert(n, b);
+ }
+ new_bindings.fill(bindings.clone());
+ let ctx = ctx.extend_unbound(bindings, None, None, None)?;
+ let key = evaluate(ctx.clone(), &obj.key)?;
+
+ match key {
+ Val::Null => {}
+ Val::Str(n) => {
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct ObjCompBinding {
+ context: Context,
+ value: LocExpr,
+ }
+ impl Bindable for ObjCompBinding {
+ fn bind(
+ &self,
+ this: Option<ObjValue>,
+ _super_obj: Option<ObjValue>,
+ ) -> Result<LazyVal> {
+ Ok(LazyVal::new_resolved(evaluate(
+ self.context.clone().extend(
+ FxHashMap::default(),
+ None,
+ this,
+ None,
+ ),
+ &self.value,
+ )?))
+ }
+ }
+ new_members.insert(
+ n,
+ ObjMember {
+ add: false,
+ visibility: Visibility::Normal,
+ invoke: LazyBinding::Bindable(Gc::new(Box::new(ObjCompBinding {
+ context: ctx,
+ value: obj.value.clone(),
+ }))),
+ location: obj.value.1.clone(),
+ },
+ );
+ }
+ v => throw!(FieldMustBeStringGot(v.value_type())),
+ }
+
+ Ok(())
+ })?;
+
+ let this = ObjValue::new(None, Gc::new(new_members), Gc::new(Vec::new()));
+ future_this.fill(this.clone());
+ this
+ }
+ })
+}
+
+pub fn evaluate_apply(
+ context: Context,
+ value: &LocExpr,
+ args: &ArgsDesc,
+ loc: Option<&ExprLocation>,
+ tailstrict: bool,
+) -> Result<Val> {
+ let value = evaluate(context.clone(), value)?;
+ Ok(match value {
+ Val::Func(f) => {
+ let body = || f.evaluate(context, loc, args, tailstrict);
+ if tailstrict {
+ body()?
+ } else {
+ push(loc, || format!("function <{}> call", f.name()), body)?
+ }
+ }
+ v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
+ })
+}
+
+pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {
+ let value = &assertion.0;
+ let msg = &assertion.1;
+ let assertion_result = push(
+ value.1.as_ref(),
+ || "assertion condition".to_owned(),
+ || {
+ evaluate(context.clone(), value)?
+ .try_cast_bool("assertion condition should be of type `boolean`")
+ },
+ )?;
+ if !assertion_result {
+ push(
+ value.1.as_ref(),
+ || "assertion failure".to_owned(),
+ || {
+ if let Some(msg) = msg {
+ throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));
+ } else {
+ throw!(AssertionFailed(Val::Null.to_string()?));
+ }
+ },
+ )?
+ }
+ Ok(())
+}
+
+pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: IStr) -> Result<Val> {
+ use Expr::*;
+ let LocExpr(expr, _loc) = lexpr;
+ Ok(match &**expr {
+ Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),
+ _ => evaluate(context, lexpr)?,
+ })
+}
+
+pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
+ use Expr::*;
+ let LocExpr(expr, loc) = expr;
+ Ok(match &**expr {
+ Literal(LiteralType::This) => {
+ Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
+ }
+ Literal(LiteralType::Super) => Val::Obj(
+ context
+ .super_obj()
+ .clone()
+ .ok_or(NoSuperFound)?
+ .with_this(context.this().clone().unwrap()),
+ ),
+ Literal(LiteralType::Dollar) => {
+ Val::Obj(context.dollar().clone().ok_or(NoTopLevelObjectFound)?)
+ }
+ Literal(LiteralType::True) => Val::Bool(true),
+ Literal(LiteralType::False) => Val::Bool(false),
+ Literal(LiteralType::Null) => Val::Null,
+ Parened(e) => evaluate(context, e)?,
+ Str(v) => Val::Str(v.clone()),
+ Num(v) => Val::new_checked_num(*v)?,
+ BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
+ UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
+ Var(name) => push(
+ loc.as_ref(),
+ || format!("variable <{}>", name),
+ || context.binding(name.clone())?.evaluate(),
+ )?,
+ Index(value, index) => {
+ match (evaluate(context.clone(), value)?, evaluate(context, index)?) {
+ (Val::Obj(v), Val::Str(s)) => {
+ let sn = s.clone();
+ push(
+ loc.as_ref(),
+ || format!("field <{}> access", sn),
+ || {
+ if let Some(v) = v.get(s.clone())? {
+ Ok(v)
+ } else if v.get("__intrinsic_namespace__".into())?.is_some() {
+ Ok(Val::Func(Gc::new(FuncVal::Intrinsic(s))))
+ } else {
+ throw!(NoSuchField(s))
+ }
+ },
+ )?
+ }
+ (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(
+ ValType::Obj,
+ ValType::Str,
+ n.value_type(),
+ )),
+
+ (Val::Arr(v), Val::Num(n)) => {
+ if n.fract() > f64::EPSILON {
+ throw!(FractionalIndex)
+ }
+ v.get(n as usize)?
+ .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
+ }
+ (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
+ (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
+ ValType::Arr,
+ ValType::Num,
+ n.value_type(),
+ )),
+
+ (Val::Str(s), Val::Num(n)) => Val::Str(
+ s.chars()
+ .skip(n as usize)
+ .take(1)
+ .collect::<String>()
+ .into(),
+ ),
+ (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
+ ValType::Str,
+ ValType::Num,
+ n.value_type(),
+ )),
+
+ (v, _) => throw!(CantIndexInto(v.value_type())),
+ }
+ }
+ LocalExpr(bindings, returned) => {
+ let mut new_bindings: FxHashMap<IStr, LazyVal> = HashMap::with_capacity_and_hasher(
+ bindings.len(),
+ BuildHasherDefault::<FxHasher>::default(),
+ );
+ let future_context = Context::new_future();
+ for b in bindings {
+ new_bindings.insert(
+ b.name.clone(),
+ evaluate_binding_in_future(b, future_context.clone()),
+ );
+ }
+ let context = context
+ .extend_bound(new_bindings)
+ .into_future(future_context);
+ evaluate(context, &returned.clone())?
+ }
+ Arr(items) => {
+ let mut out = Vec::with_capacity(items.len());
+ for item in items {
+ // TODO: Implement ArrValue::Lazy with same context for every element?
+ #[derive(Trace)]
+ #[trivially_drop]
+ struct ArrayElement {
+ context: Context,
+ item: LocExpr,
+ }
+ impl LazyValValue for ArrayElement {
+ fn get(self: Box<Self>) -> Result<Val> {
+ evaluate(self.context, &self.item)
+ }
+ }
+ out.push(LazyVal::new(Box::new(ArrayElement {
+ context: context.clone(),
+ item: item.clone(),
+ })));
+ }
+ Val::Arr(out.into())
+ }
+ ArrComp(expr, comp_specs) => {
+ let mut out = Vec::new();
+ evaluate_comp(context, comp_specs, &mut |ctx| {
+ out.push(evaluate(ctx, expr)?);
+ Ok(())
+ })?;
+ Val::Arr(ArrValue::Eager(Gc::new(out)))
+ }
+ Obj(body) => Val::Obj(evaluate_object(context, body)?),
+ ObjExtend(s, t) => evaluate_add_op(
+ &evaluate(context.clone(), s)?,
+ &Val::Obj(evaluate_object(context, t)?),
+ )?,
+ Apply(value, args, tailstrict) => {
+ evaluate_apply(context, value, args, loc.as_ref(), *tailstrict)?
+ }
+ Function(params, body) => {
+ evaluate_method(context, "anonymous".into(), params.clone(), body.clone())
+ }
+ Intrinsic(name) => Val::Func(Gc::new(FuncVal::Intrinsic(name.clone()))),
+ AssertExpr(assert, returned) => {
+ evaluate_assert(context.clone(), assert)?;
+ evaluate(context, returned)?
+ }
+ ErrorStmt(e) => push(
+ loc.as_ref(),
+ || "error statement".to_owned(),
+ || {
+ throw!(RuntimeError(
+ evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
+ ))
+ },
+ )?,
+ IfElse {
+ cond,
+ cond_then,
+ cond_else,
+ } => {
+ if push(
+ loc.as_ref(),
+ || "if condition".to_owned(),
+ || evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
+ )? {
+ evaluate(context, cond_then)?
+ } else {
+ match cond_else {
+ Some(v) => evaluate(context, v)?,
+ None => Val::Null,
+ }
+ }
+ }
+ Import(path) => {
+ let tmp = loc
+ .clone()
+ .expect("imports cannot be used without loc_data")
+ .0;
+ let mut import_location = tmp.to_path_buf();
+ import_location.pop();
+ push(
+ loc.as_ref(),
+ || format!("import {:?}", path),
+ || with_state(|s| s.import_file(&import_location, path)),
+ )?
+ }
+ ImportStr(path) => {
+ let tmp = loc
+ .clone()
+ .expect("imports cannot be used without loc_data")
+ .0;
+ let mut import_location = tmp.to_path_buf();
+ import_location.pop();
+ Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
+ }
+ })
+}
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -0,0 +1,118 @@
+use crate::{equals, evaluate, Context, Val};
+use crate::{error::Error::*, throw, Result};
+use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
+
+pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
+ use UnaryOpType::*;
+ use Val::*;
+ Ok(match (op, b) {
+ (Not, Bool(v)) => Bool(!v),
+ (Minus, Num(n)) => Num(-*n),
+ (BitNot, Num(n)) => Num(!(*n as i32) as f64),
+ (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type())),
+ })
+}
+
+pub fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {
+ use Val::*;
+ Ok(match (a, b) {
+ (Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),
+
+ // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
+ (Num(n), Str(o)) => Str(format!("{}{}", n, o).into()),
+ (Str(o), Num(n)) => Str(format!("{}{}", o, n).into()),
+
+ (Str(s), o) => Str(format!("{}{}", s, o.clone().to_string()?).into()),
+ (o, Str(s)) => Str(format!("{}{}", o.clone().to_string()?, s).into()),
+
+ (Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
+ (Arr(a), Arr(b)) => {
+ let mut out = Vec::with_capacity(a.len() + b.len());
+ out.extend(a.iter_lazy());
+ out.extend(b.iter_lazy());
+ Arr(out.into())
+ }
+ (Num(v1), Num(v2)) => Val::new_checked_num(v1 + v2)?,
+ _ => throw!(BinaryOperatorDoesNotOperateOnValues(
+ BinaryOpType::Add,
+ a.value_type(),
+ b.value_type(),
+ )),
+ })
+}
+
+pub fn evaluate_binary_op_special(
+ context: Context,
+ a: &LocExpr,
+ op: BinaryOpType,
+ b: &LocExpr,
+) -> Result<Val> {
+ use BinaryOpType::*;
+ use Val::*;
+ Ok(match (evaluate(context.clone(), a)?, op, b) {
+ (Bool(true), Or, _o) => Val::Bool(true),
+ (Bool(false), And, _o) => Val::Bool(false),
+ (a, op, eb) => evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?)?,
+ })
+}
+
+pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {
+ use BinaryOpType::*;
+ use Val::*;
+ Ok(match (a, op, b) {
+ (a, Add, b) => evaluate_add_op(a, b)?,
+
+ (a, Eq, b) => Bool(equals(a, b)?),
+ (a, Neq, b) => Bool(!equals(a, b)?),
+
+ (Str(v1), Mul, Num(v2)) => Str(v1.repeat(*v2 as usize).into()),
+
+ // Bool X Bool
+ (Bool(a), And, Bool(b)) => Bool(*a && *b),
+ (Bool(a), Or, Bool(b)) => Bool(*a || *b),
+
+ // Str X Str
+ (Str(v1), Lt, Str(v2)) => Bool(v1 < v2),
+ (Str(v1), Gt, Str(v2)) => Bool(v1 > v2),
+ (Str(v1), Lte, Str(v2)) => Bool(v1 <= v2),
+ (Str(v1), Gte, Str(v2)) => Bool(v1 >= v2),
+
+ // Num X Num
+ (Num(v1), Mul, Num(v2)) => Val::new_checked_num(v1 * v2)?,
+ (Num(v1), Div, Num(v2)) => {
+ if *v2 <= f64::EPSILON {
+ throw!(DivisionByZero)
+ }
+ Val::new_checked_num(v1 / v2)?
+ }
+
+ (Num(v1), Sub, Num(v2)) => Val::new_checked_num(v1 - v2)?,
+
+ (Num(v1), Lt, Num(v2)) => Bool(v1 < v2),
+ (Num(v1), Gt, Num(v2)) => Bool(v1 > v2),
+ (Num(v1), Lte, Num(v2)) => Bool(v1 <= v2),
+ (Num(v1), Gte, Num(v2)) => Bool(v1 >= v2),
+
+ (Num(v1), BitAnd, Num(v2)) => Num(((*v1 as i32) & (*v2 as i32)) as f64),
+ (Num(v1), BitOr, Num(v2)) => Num(((*v1 as i32) | (*v2 as i32)) as f64),
+ (Num(v1), BitXor, Num(v2)) => Num(((*v1 as i32) ^ (*v2 as i32)) as f64),
+ (Num(v1), Lhs, Num(v2)) => {
+ if *v2 < 0.0 {
+ throw!(RuntimeError("shift by negative exponent".into()))
+ }
+ Num(((*v1 as i32) << (*v2 as i32)) as f64)
+ }
+ (Num(v1), Rhs, Num(v2)) => {
+ if *v2 < 0.0 {
+ throw!(RuntimeError("shift by negative exponent".into()))
+ }
+ Num(((*v1 as i32) >> (*v2 as i32)) as f64)
+ }
+
+ _ => throw!(BinaryOperatorDoesNotOperateOnValues(
+ op,
+ a.value_type(),
+ b.value_type(),
+ )),
+ })
+}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1033,7 +1033,7 @@
local conf = {
n: ""
};
-
+
local result = conf + {
assert std.isNumber(self.n): "is number"
};
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth1use crate::{evaluate_add_op, LazyBinding, Result, Val};2use jrsonnet_gc::{Gc, GcCell, Trace};3use jrsonnet_interner::IStr;4use jrsonnet_parser::{ExprLocation, Visibility};5use rustc_hash::{FxHashMap, FxHashSet};6use std::hash::{Hash, Hasher};7use std::{fmt::Debug, hash::BuildHasherDefault};89#[derive(Debug, Trace)]10#[trivially_drop]11pub struct ObjMember {12 pub add: bool,13 pub visibility: Visibility,14 pub invoke: LazyBinding,15 pub location: Option<ExprLocation>,16}1718pub trait ObjectAssertion: Trace {19 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;20}2122// Field => This23type CacheKey = (IStr, ObjValue);24#[derive(Trace)]25#[trivially_drop]26pub struct ObjValueInternals {27 super_obj: Option<ObjValue>,28 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,29 assertions_ran: GcCell<FxHashSet<ObjValue>>,30 this_obj: Option<ObjValue>,31 this_entries: Gc<FxHashMap<IStr, ObjMember>>,32 value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,33}3435#[derive(Clone, Trace)]36#[trivially_drop]37pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);38impl Debug for ObjValue {39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {40 if let Some(super_obj) = self.0.super_obj.as_ref() {41 if f.alternate() {42 write!(f, "{:#?}", super_obj)?;43 } else {44 write!(f, "{:?}", super_obj)?;45 }46 write!(f, " + ")?;47 }48 let mut debug = f.debug_struct("ObjValue");49 for (name, member) in self.0.this_entries.iter() {50 debug.field(name, member);51 }52 #[cfg(feature = "unstable")]53 {54 debug.finish_non_exhaustive()55 }56 #[cfg(not(feature = "unstable"))]57 {58 debug.finish()59 }60 }61}6263impl ObjValue {64 pub fn new(65 super_obj: Option<Self>,66 this_entries: Gc<FxHashMap<IStr, ObjMember>>,67 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,68 ) -> Self {69 Self(Gc::new(ObjValueInternals {70 super_obj,71 assertions,72 assertions_ran: GcCell::new(FxHashSet::default()),73 this_obj: None,74 this_entries,75 value_cache: GcCell::new(FxHashMap::default()),76 }))77 }78 pub fn new_empty() -> Self {79 Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))80 }81 pub fn extend_from(&self, super_obj: Self) -> Self {82 match &self.0.super_obj {83 None => Self::new(84 Some(super_obj),85 self.0.this_entries.clone(),86 self.0.assertions.clone(),87 ),88 Some(v) => Self::new(89 Some(v.extend_from(super_obj)),90 self.0.this_entries.clone(),91 self.0.assertions.clone(),92 ),93 }94 }95 pub fn with_this(&self, this_obj: Self) -> Self {96 Self(Gc::new(ObjValueInternals {97 super_obj: self.0.super_obj.clone(),98 assertions: self.0.assertions.clone(),99 assertions_ran: GcCell::new(FxHashSet::default()),100 this_obj: Some(this_obj),101 this_entries: self.0.this_entries.clone(),102 value_cache: GcCell::new(FxHashMap::default()),103 }))104 }105106 /// Run callback for every field found in object107 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {108 if let Some(s) = &self.0.super_obj {109 if s.enum_fields(handler) {110 return true;111 }112 }113 for (name, member) in self.0.this_entries.iter() {114 if handler(name, &member.visibility) {115 return true;116 }117 }118 false119 }120121 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {122 let mut out = FxHashMap::default();123 self.enum_fields(&mut |name, visibility| {124 match visibility {125 Visibility::Normal => {126 let entry = out.entry(name.to_owned());127 entry.or_insert(true);128 }129 Visibility::Hidden => {130 out.insert(name.to_owned(), false);131 }132 Visibility::Unhide => {133 out.insert(name.to_owned(), true);134 }135 };136 false137 });138 out139 }140 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {141 let mut fields: Vec<_> = self142 .fields_visibility()143 .into_iter()144 .filter(|(_k, v)| include_hidden || *v)145 .map(|(k, _)| k)146 .collect();147 fields.sort_unstable();148 fields149 }150 pub fn fields(&self) -> Vec<IStr> {151 self.fields_ex(false)152 }153154 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {155 if let Some(m) = self.0.this_entries.get(&name) {156 Some(match &m.visibility {157 Visibility::Normal => self158 .0159 .super_obj160 .as_ref()161 .and_then(|super_obj| super_obj.field_visibility(name))162 .unwrap_or(Visibility::Normal),163 v => *v,164 })165 } else if let Some(super_obj) = &self.0.super_obj {166 super_obj.field_visibility(name)167 } else {168 None169 }170 }171172 fn has_field_include_hidden(&self, name: IStr) -> bool {173 if self.0.this_entries.contains_key(&name) {174 true175 } else if let Some(super_obj) = &self.0.super_obj {176 super_obj.has_field_include_hidden(name)177 } else {178 false179 }180 }181182 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {183 if include_hidden {184 self.has_field_include_hidden(name)185 } else {186 self.has_field(name)187 }188 }189 pub fn has_field(&self, name: IStr) -> bool {190 self.field_visibility(name)191 .map(|v| v.is_visible())192 .unwrap_or(false)193 }194195 pub fn get(&self, key: IStr) -> Result<Option<Val>> {196 self.run_assertions()?;197 self.get_raw(key, self.0.this_obj.as_ref())198 }199200 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {201 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());202 new.insert(key, value);203 Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))204 }205206 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {207 let real_this = real_this.unwrap_or(self);208 let cache_key = (key.clone(), real_this.clone());209210 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {211 return Ok(v.clone());212 }213 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {214 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),215 (Some(k), Some(s)) => {216 let our = self.evaluate_this(k, real_this)?;217 if k.add {218 s.get_raw(key, Some(real_this))?219 .map_or(Ok(Some(our.clone())), |v| {220 Ok(Some(evaluate_add_op(&v, &our)?))221 })222 } else {223 Ok(Some(our))224 }225 }226 (None, Some(s)) => s.get_raw(key, Some(real_this)),227 (None, None) => Ok(None),228 }?;229 self.0230 .value_cache231 .borrow_mut()232 .insert(cache_key, value.clone());233 Ok(value)234 }235 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {236 v.invoke237 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?238 .evaluate()239 }240241 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {242 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {243 for assertion in self.0.assertions.iter() {244 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {245 self.0.assertions_ran.borrow_mut().remove(real_this);246 return Err(e);247 }248 }249 if let Some(super_obj) = &self.0.super_obj {250 super_obj.run_assertions_raw(real_this)?;251 }252 }253 Ok(())254 }255 pub fn run_assertions(&self) -> Result<()> {256 self.run_assertions_raw(self)257 }258259 pub fn ptr_eq(a: &Self, b: &Self) -> bool {260 Gc::ptr_eq(&a.0, &b.0)261 }262}263264impl PartialEq for ObjValue {265 fn eq(&self, other: &Self) -> bool {266 Gc::ptr_eq(&self.0, &other.0)267 }268}269270impl Eq for ObjValue {}271impl Hash for ObjValue {272 fn hash<H: Hasher>(&self, hasher: &mut H) {273 hasher.write_usize(&*self.0 as *const _ as usize)274 }275}1use crate::operator::evaluate_add_op;2use crate::{LazyBinding, Result, Val};3use jrsonnet_gc::{Gc, GcCell, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{ExprLocation, Visibility};6use rustc_hash::{FxHashMap, FxHashSet};7use std::hash::{Hash, Hasher};8use std::{fmt::Debug, hash::BuildHasherDefault};910#[derive(Debug, Trace)]11#[trivially_drop]12pub struct ObjMember {13 pub add: bool,14 pub visibility: Visibility,15 pub invoke: LazyBinding,16 pub location: Option<ExprLocation>,17}1819pub trait ObjectAssertion: Trace {20 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;21}2223// Field => This24type CacheKey = (IStr, ObjValue);25#[derive(Trace)]26#[trivially_drop]27pub struct ObjValueInternals {28 super_obj: Option<ObjValue>,29 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,30 assertions_ran: GcCell<FxHashSet<ObjValue>>,31 this_obj: Option<ObjValue>,32 this_entries: Gc<FxHashMap<IStr, ObjMember>>,33 value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,34}3536#[derive(Clone, Trace)]37#[trivially_drop]38pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);39impl Debug for ObjValue {40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {41 if let Some(super_obj) = self.0.super_obj.as_ref() {42 if f.alternate() {43 write!(f, "{:#?}", super_obj)?;44 } else {45 write!(f, "{:?}", super_obj)?;46 }47 write!(f, " + ")?;48 }49 let mut debug = f.debug_struct("ObjValue");50 for (name, member) in self.0.this_entries.iter() {51 debug.field(name, member);52 }53 #[cfg(feature = "unstable")]54 {55 debug.finish_non_exhaustive()56 }57 #[cfg(not(feature = "unstable"))]58 {59 debug.finish()60 }61 }62}6364impl ObjValue {65 pub fn new(66 super_obj: Option<Self>,67 this_entries: Gc<FxHashMap<IStr, ObjMember>>,68 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,69 ) -> Self {70 Self(Gc::new(ObjValueInternals {71 super_obj,72 assertions,73 assertions_ran: GcCell::new(FxHashSet::default()),74 this_obj: None,75 this_entries,76 value_cache: GcCell::new(FxHashMap::default()),77 }))78 }79 pub fn new_empty() -> Self {80 Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))81 }82 pub fn extend_from(&self, super_obj: Self) -> Self {83 match &self.0.super_obj {84 None => Self::new(85 Some(super_obj),86 self.0.this_entries.clone(),87 self.0.assertions.clone(),88 ),89 Some(v) => Self::new(90 Some(v.extend_from(super_obj)),91 self.0.this_entries.clone(),92 self.0.assertions.clone(),93 ),94 }95 }96 pub fn with_this(&self, this_obj: Self) -> Self {97 Self(Gc::new(ObjValueInternals {98 super_obj: self.0.super_obj.clone(),99 assertions: self.0.assertions.clone(),100 assertions_ran: GcCell::new(FxHashSet::default()),101 this_obj: Some(this_obj),102 this_entries: self.0.this_entries.clone(),103 value_cache: GcCell::new(FxHashMap::default()),104 }))105 }106107 /// Run callback for every field found in object108 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {109 if let Some(s) = &self.0.super_obj {110 if s.enum_fields(handler) {111 return true;112 }113 }114 for (name, member) in self.0.this_entries.iter() {115 if handler(name, &member.visibility) {116 return true;117 }118 }119 false120 }121122 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {123 let mut out = FxHashMap::default();124 self.enum_fields(&mut |name, visibility| {125 match visibility {126 Visibility::Normal => {127 let entry = out.entry(name.to_owned());128 entry.or_insert(true);129 }130 Visibility::Hidden => {131 out.insert(name.to_owned(), false);132 }133 Visibility::Unhide => {134 out.insert(name.to_owned(), true);135 }136 };137 false138 });139 out140 }141 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {142 let mut fields: Vec<_> = self143 .fields_visibility()144 .into_iter()145 .filter(|(_k, v)| include_hidden || *v)146 .map(|(k, _)| k)147 .collect();148 fields.sort_unstable();149 fields150 }151 pub fn fields(&self) -> Vec<IStr> {152 self.fields_ex(false)153 }154155 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {156 if let Some(m) = self.0.this_entries.get(&name) {157 Some(match &m.visibility {158 Visibility::Normal => self159 .0160 .super_obj161 .as_ref()162 .and_then(|super_obj| super_obj.field_visibility(name))163 .unwrap_or(Visibility::Normal),164 v => *v,165 })166 } else if let Some(super_obj) = &self.0.super_obj {167 super_obj.field_visibility(name)168 } else {169 None170 }171 }172173 fn has_field_include_hidden(&self, name: IStr) -> bool {174 if self.0.this_entries.contains_key(&name) {175 true176 } else if let Some(super_obj) = &self.0.super_obj {177 super_obj.has_field_include_hidden(name)178 } else {179 false180 }181 }182183 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {184 if include_hidden {185 self.has_field_include_hidden(name)186 } else {187 self.has_field(name)188 }189 }190 pub fn has_field(&self, name: IStr) -> bool {191 self.field_visibility(name)192 .map(|v| v.is_visible())193 .unwrap_or(false)194 }195196 pub fn get(&self, key: IStr) -> Result<Option<Val>> {197 self.run_assertions()?;198 self.get_raw(key, self.0.this_obj.as_ref())199 }200201 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {202 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());203 new.insert(key, value);204 Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))205 }206207 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {208 let real_this = real_this.unwrap_or(self);209 let cache_key = (key.clone(), real_this.clone());210211 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {212 return Ok(v.clone());213 }214 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {215 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),216 (Some(k), Some(s)) => {217 let our = self.evaluate_this(k, real_this)?;218 if k.add {219 s.get_raw(key, Some(real_this))?220 .map_or(Ok(Some(our.clone())), |v| {221 Ok(Some(evaluate_add_op(&v, &our)?))222 })223 } else {224 Ok(Some(our))225 }226 }227 (None, Some(s)) => s.get_raw(key, Some(real_this)),228 (None, None) => Ok(None),229 }?;230 self.0231 .value_cache232 .borrow_mut()233 .insert(cache_key, value.clone());234 Ok(value)235 }236 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {237 v.invoke238 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?239 .evaluate()240 }241242 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {243 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {244 for assertion in self.0.assertions.iter() {245 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {246 self.0.assertions_ran.borrow_mut().remove(real_this);247 return Err(e);248 }249 }250 if let Some(super_obj) = &self.0.super_obj {251 super_obj.run_assertions_raw(real_this)?;252 }253 }254 Ok(())255 }256 pub fn run_assertions(&self) -> Result<()> {257 self.run_assertions_raw(self)258 }259260 pub fn ptr_eq(a: &Self, b: &Self) -> bool {261 Gc::ptr_eq(&a.0, &b.0)262 }263}264265impl PartialEq for ObjValue {266 fn eq(&self, other: &Self) -> bool {267 Gc::ptr_eq(&self.0, &other.0)268 }269}270271impl Eq for ObjValue {}272impl Hash for ObjValue {273 fn hash<H: Hasher>(&self, hasher: &mut H) {274 hasher.write_usize(&*self.0 as *const _ as usize)275 }276}