difftreelog
refactor unwrap Unbound thunk value
in: master
3 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7 IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12 destructure::evaluate_dest,13 error::Error::*,14 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15 function::{CallLocation, FuncDesc, FuncVal},16 tb, throw,17 typed::Typed,18 val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19 Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,20 Unbound, Val,21};22pub mod destructure;23pub mod operator;2425pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {26 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {27 name,28 ctx,29 params,30 body,31 })))32}3334pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {35 Ok(match field_name {36 FieldName::Fixed(n) => Some(n.clone()),37 FieldName::Dyn(expr) => State::push(38 CallLocation::new(&expr.1),39 || "evaluating field name".to_string(),40 || {41 let value = evaluate(ctx, expr)?;42 if matches!(value, Val::Null) {43 Ok(None)44 } else {45 Ok(Some(IStr::from_untyped(value)?))46 }47 },48 )?,49 })50}5152pub fn evaluate_comp(53 ctx: Context,54 specs: &[CompSpec],55 callback: &mut impl FnMut(Context) -> Result<()>,56) -> Result<()> {57 match specs.get(0) {58 None => callback(ctx)?,59 Some(CompSpec::IfSpec(IfSpecData(cond))) => {60 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {61 evaluate_comp(ctx, &specs[1..], callback)?;62 }63 }64 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {65 Val::Arr(list) => {66 for item in list.iter() {67 evaluate_comp(68 ctx.clone().with_var(var.clone(), item?.clone()),69 &specs[1..],70 callback,71 )?;72 }73 }74 _ => throw!(InComprehensionCanOnlyIterateOverArray),75 },76 }77 Ok(())78}7980trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8182fn evaluate_object_locals(83 fctx: Pending<Context>,84 locals: Rc<Vec<BindSpec>>,85) -> impl CloneableUnbound<Context> {86 #[derive(Trace, Clone)]87 struct UnboundLocals {88 fctx: Pending<Context>,89 locals: Rc<Vec<BindSpec>>,90 }91 impl CloneableUnbound<Context> for UnboundLocals {}92 impl Unbound for UnboundLocals {93 type Bound = Context;9495 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {96 let fctx = Context::new_future();97 let mut new_bindings = GcHashMap::new();98 for b in self.locals.iter() {99 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;100 }101102 let ctx = self.fctx.unwrap();103 let new_dollar = ctx.dollar().clone().or_else(|| this.clone());104105 let ctx = ctx106 .extend(new_bindings, new_dollar, sup, this)107 .into_future(fctx);108109 Ok(ctx)110 }111 }112113 UnboundLocals { fctx, locals }114}115116#[allow(clippy::too_many_lines)]117pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {118 let mut builder = ObjValueBuilder::new();119 let locals = Rc::new(120 members121 .iter()122 .filter_map(|m| match m {123 Member::BindStmt(bind) => Some(bind.clone()),124 _ => None,125 })126 .collect::<Vec<_>>(),127 );128129 let fctx = Context::new_future();130131 // We have single context for all fields, so we can cache binds132 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));133134 for member in members.iter() {135 match member {136 Member::Field(FieldMember {137 name,138 plus,139 params: None,140 visibility,141 value,142 }) => {143 #[derive(Trace)]144 struct UnboundValue<B: Trace> {145 uctx: B,146 value: LocExpr,147 name: IStr,148 }149 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {150 type Bound = Thunk<Val>;151 fn bind(152 &self,153 sup: Option<ObjValue>,154 this: Option<ObjValue>,155 ) -> Result<Thunk<Val>> {156 Ok(Thunk::evaluated(evaluate_named(157 self.uctx.bind(sup, this)?,158 &self.value,159 self.name.clone(),160 )?))161 }162 }163164 let name = evaluate_field_name(ctx.clone(), name)?;165 let Some(name) = name else {166 continue;167 };168169 builder170 .member(name.clone())171 .with_add(*plus)172 .with_visibility(*visibility)173 .with_location(value.1.clone())174 .bindable(tb!(UnboundValue {175 uctx: uctx.clone(),176 value: value.clone(),177 name: name.clone()178 }))?;179 }180 Member::Field(FieldMember {181 name,182 params: Some(params),183 value,184 ..185 }) => {186 #[derive(Trace)]187 struct UnboundMethod<B: Trace> {188 uctx: B,189 value: LocExpr,190 params: ParamsDesc,191 name: IStr,192 }193 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {194 type Bound = Thunk<Val>;195 fn bind(196 &self,197 sup: Option<ObjValue>,198 this: Option<ObjValue>,199 ) -> Result<Thunk<Val>> {200 Ok(Thunk::evaluated(evaluate_method(201 self.uctx.bind(sup, this)?,202 self.name.clone(),203 self.params.clone(),204 self.value.clone(),205 )))206 }207 }208209 let name = if let Some(name) = evaluate_field_name(ctx.clone(), name)? {210 name211 } else {212 continue;213 };214215 builder216 .member(name.clone())217 .hide()218 .with_location(value.1.clone())219 .bindable(tb!(UnboundMethod {220 uctx: uctx.clone(),221 value: value.clone(),222 params: params.clone(),223 name: name.clone()224 }))?;225 }226 Member::BindStmt(_) => {}227 Member::AssertStmt(stmt) => {228 #[derive(Trace)]229 struct ObjectAssert<B: Trace> {230 uctx: B,231 assert: AssertStmt,232 }233 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {234 fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {235 let ctx = self.uctx.bind(sup, this)?;236 evaluate_assert(ctx, &self.assert)237 }238 }239 builder.assert(tb!(ObjectAssert {240 uctx: uctx.clone(),241 assert: stmt.clone(),242 }));243 }244 }245 }246 let this = builder.build();247 fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));248 Ok(this)249}250251pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {252 Ok(match object {253 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,254 ObjBody::ObjComp(obj) => {255 let mut builder = ObjValueBuilder::new();256 let locals = Rc::new(257 obj.pre_locals258 .iter()259 .chain(obj.post_locals.iter())260 .cloned()261 .collect::<Vec<_>>(),262 );263 let mut ctxs = vec![];264 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {265 let key = evaluate(ctx.clone(), &obj.key)?;266 let fctx = Context::new_future();267 ctxs.push((ctx, fctx.clone()));268 let uctx = evaluate_object_locals(fctx, locals.clone());269270 match key {271 Val::Null => {}272 Val::Str(n) => {273 #[derive(Trace)]274 struct UnboundValue<B: Trace> {275 uctx: B,276 value: LocExpr,277 }278 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {279 type Bound = Thunk<Val>;280 fn bind(281 &self,282 sup: Option<ObjValue>,283 this: Option<ObjValue>,284 ) -> Result<Thunk<Val>> {285 Ok(Thunk::evaluated(evaluate(286 self.uctx.bind(sup, this.clone())?.extend(287 GcHashMap::new(),288 None,289 None,290 this,291 ),292 &self.value,293 )?))294 }295 }296 builder297 .member(n)298 .with_location(obj.value.1.clone())299 .with_add(obj.plus)300 .bindable(tb!(UnboundValue {301 uctx,302 value: obj.value.clone(),303 }))?;304 }305 v => throw!(FieldMustBeStringGot(v.value_type())),306 }307308 Ok(())309 })?;310311 let this = builder.build();312 for (ctx, fctx) in ctxs {313 let _ctx = ctx314 .extend(GcHashMap::new(), None, None, Some(this.clone()))315 .into_future(fctx);316 }317 this318 }319 })320}321322pub fn evaluate_apply(323 ctx: Context,324 value: &LocExpr,325 args: &ArgsDesc,326 loc: CallLocation<'_>,327 tailstrict: bool,328) -> Result<Val> {329 let value = evaluate(ctx.clone(), value)?;330 Ok(match value {331 Val::Func(f) => {332 let body = || f.evaluate(ctx, loc, args, tailstrict);333 if tailstrict {334 body()?335 } else {336 State::push(loc, || format!("function <{}> call", f.name()), body)?337 }338 }339 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),340 })341}342343pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {344 let value = &assertion.0;345 let msg = &assertion.1;346 let assertion_result = State::push(347 CallLocation::new(&value.1),348 || "assertion condition".to_owned(),349 || bool::from_untyped(evaluate(ctx.clone(), value)?),350 )?;351 if !assertion_result {352 State::push(353 CallLocation::new(&value.1),354 || "assertion failure".to_owned(),355 || {356 if let Some(msg) = msg {357 throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));358 }359 throw!(AssertionFailed(Val::Null.to_string()?));360 },361 )?;362 }363 Ok(())364}365366pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {367 use Expr::*;368 let LocExpr(raw_expr, _loc) = expr;369 Ok(match &**raw_expr {370 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),371 _ => evaluate(ctx, expr)?,372 })373}374375#[allow(clippy::too_many_lines)]376pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {377 use Expr::*;378 let LocExpr(expr, loc) = expr;379 // let bp = with_state(|s| s.0.stop_at.borrow().clone());380 Ok(match &**expr {381 Literal(LiteralType::This) => {382 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)383 }384 Literal(LiteralType::Super) => Val::Obj(385 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(386 ctx.this()387 .clone()388 .expect("if super exists - then this should to"),389 ),390 ),391 Literal(LiteralType::Dollar) => {392 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)393 }394 Literal(LiteralType::True) => Val::Bool(true),395 Literal(LiteralType::False) => Val::Bool(false),396 Literal(LiteralType::Null) => Val::Null,397 Parened(e) => evaluate(ctx, e)?,398 Str(v) => Val::Str(v.clone()),399 Num(v) => Val::new_checked_num(*v)?,400 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,401 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,402 Var(name) => State::push(403 CallLocation::new(loc),404 || format!("variable <{name}> access"),405 || ctx.binding(name.clone())?.evaluate(),406 )?,407 Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {408 (Val::Obj(v), Val::Str(key)) => State::push(409 CallLocation::new(loc),410 || format!("field <{key}> access"),411 || match v.get(key.clone()) {412 Ok(Some(v)) => Ok(v),413 #[cfg(not(feature = "friendly-errors"))]414 Ok(None) => throw!(NoSuchField(key.clone(), vec![])),415 #[cfg(feature = "friendly-errors")]416 Ok(None) => {417 let mut heap = Vec::new();418 for field in v.fields_ex(419 true,420 #[cfg(feature = "exp-preserve-order")]421 false,422 ) {423 let conf = strsim::jaro_winkler(&field as &str, &key as &str);424 if conf < 0.8 {425 continue;426 }427 heap.push((conf, field));428 }429 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));430431 throw!(NoSuchField(432 key.clone(),433 heap.into_iter().map(|(_, v)| v).collect()434 ))435 }436 Err(e) => Err(e),437 },438 )?,439 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(440 ValType::Obj,441 ValType::Str,442 n.value_type(),443 )),444445 (Val::Arr(v), Val::Num(n)) => {446 if n.fract() > f64::EPSILON {447 throw!(FractionalIndex)448 }449 v.get(n as usize)?450 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?451 }452 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),453 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(454 ValType::Arr,455 ValType::Num,456 n.value_type(),457 )),458459 (Val::Str(s), Val::Num(n)) => Val::Str({460 let v: IStr = s461 .chars()462 .skip(n as usize)463 .take(1)464 .collect::<String>()465 .into();466 if v.is_empty() {467 let size = s.chars().count();468 throw!(StringBoundsError(n as usize, size))469 }470 v471 }),472 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(473 ValType::Str,474 ValType::Num,475 n.value_type(),476 )),477478 (v, _) => throw!(CantIndexInto(v.value_type())),479 },480 LocalExpr(bindings, returned) => {481 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =482 GcHashMap::with_capacity(bindings.len());483 let fctx = Context::new_future();484 for b in bindings {485 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;486 }487 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);488 evaluate(ctx, &returned.clone())?489 }490 Arr(items) => {491 let mut out = Vec::with_capacity(items.len());492 for item in items {493 // TODO: Implement ArrValue::Lazy with same context for every element?494 #[derive(Trace)]495 struct ArrayElement {496 ctx: Context,497 item: LocExpr,498 }499 impl ThunkValue for ArrayElement {500 type Output = Val;501 fn get(self: Box<Self>) -> Result<Val> {502 evaluate(self.ctx, &self.item)503 }504 }505 out.push(Thunk::new(tb!(ArrayElement {506 ctx: ctx.clone(),507 item: item.clone(),508 })));509 }510 Val::Arr(out.into())511 }512 ArrComp(expr, comp_specs) => {513 let mut out = Vec::new();514 evaluate_comp(ctx, comp_specs, &mut |ctx| {515 out.push(evaluate(ctx, expr)?);516 Ok(())517 })?;518 Val::Arr(ArrValue::Eager(Cc::new(out)))519 }520 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),521 ObjExtend(a, b) => evaluate_add_op(522 &evaluate(ctx.clone(), a)?,523 &Val::Obj(evaluate_object(ctx, b)?),524 )?,525 Apply(value, args, tailstrict) => {526 evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?527 }528 Function(params, body) => {529 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())530 }531 AssertExpr(assert, returned) => {532 evaluate_assert(ctx.clone(), assert)?;533 evaluate(ctx, returned)?534 }535 ErrorStmt(e) => State::push(536 CallLocation::new(loc),537 || "error statement".to_owned(),538 || throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),539 )?,540 IfElse {541 cond,542 cond_then,543 cond_else,544 } => {545 if State::push(546 CallLocation::new(loc),547 || "if condition".to_owned(),548 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),549 )? {550 evaluate(ctx, cond_then)?551 } else {552 match cond_else {553 Some(v) => evaluate(ctx, v)?,554 None => Val::Null,555 }556 }557 }558 Slice(value, desc) => {559 fn parse_idx<T: Typed>(560 loc: CallLocation<'_>,561 ctx: &Context,562 expr: &Option<LocExpr>,563 desc: &'static str,564 ) -> Result<Option<T>> {565 if let Some(value) = expr {566 Ok(Some(State::push(567 loc,568 || format!("slice {desc}"),569 || T::from_untyped(evaluate(ctx.clone(), value)?),570 )?))571 } else {572 Ok(None)573 }574 }575576 let indexable = evaluate(ctx.clone(), value)?;577 let loc = CallLocation::new(loc);578579 let start = parse_idx(loc, &ctx, &desc.start, "start")?;580 let end = parse_idx(loc, &ctx, &desc.end, "end")?;581 let step = parse_idx(loc, &ctx, &desc.step, "step")?;582583 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?584 }585 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {586 let tmp = loc.clone().0;587 let s = ctx.state();588 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;589 match i {590 Import(_) => State::push(591 CallLocation::new(loc),592 || format!("import {:?}", path.clone()),593 || s.import_resolved(resolved_path),594 )?,595 ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),596 ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),597 _ => unreachable!(),598 }599 }600 })601}1use std::{cmp::Ordering, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, FieldName, ForSpecData,7 IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use crate::{12 destructure::evaluate_dest,13 error::Error::*,14 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},15 function::{CallLocation, FuncDesc, FuncVal},16 tb, throw,17 typed::Typed,18 val::{ArrValue, CachedUnbound, IndexableVal, Thunk, ThunkValue},19 Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,20 Unbound, Val,21};22pub mod destructure;23pub mod operator;2425pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {26 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {27 name,28 ctx,29 params,30 body,31 })))32}3334pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {35 Ok(match field_name {36 FieldName::Fixed(n) => Some(n.clone()),37 FieldName::Dyn(expr) => State::push(38 CallLocation::new(&expr.1),39 || "evaluating field name".to_string(),40 || {41 let value = evaluate(ctx, expr)?;42 if matches!(value, Val::Null) {43 Ok(None)44 } else {45 Ok(Some(IStr::from_untyped(value)?))46 }47 },48 )?,49 })50}5152pub fn evaluate_comp(53 ctx: Context,54 specs: &[CompSpec],55 callback: &mut impl FnMut(Context) -> Result<()>,56) -> Result<()> {57 match specs.get(0) {58 None => callback(ctx)?,59 Some(CompSpec::IfSpec(IfSpecData(cond))) => {60 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {61 evaluate_comp(ctx, &specs[1..], callback)?;62 }63 }64 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {65 Val::Arr(list) => {66 for item in list.iter() {67 evaluate_comp(68 ctx.clone().with_var(var.clone(), item?.clone()),69 &specs[1..],70 callback,71 )?;72 }73 }74 _ => throw!(InComprehensionCanOnlyIterateOverArray),75 },76 }77 Ok(())78}7980trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8182fn evaluate_object_locals(83 fctx: Pending<Context>,84 locals: Rc<Vec<BindSpec>>,85) -> impl CloneableUnbound<Context> {86 #[derive(Trace, Clone)]87 struct UnboundLocals {88 fctx: Pending<Context>,89 locals: Rc<Vec<BindSpec>>,90 }91 impl CloneableUnbound<Context> for UnboundLocals {}92 impl Unbound for UnboundLocals {93 type Bound = Context;9495 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {96 let fctx = Context::new_future();97 let mut new_bindings = GcHashMap::new();98 for b in self.locals.iter() {99 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;100 }101102 let ctx = self.fctx.unwrap();103 let new_dollar = ctx.dollar().clone().or_else(|| this.clone());104105 let ctx = ctx106 .extend(new_bindings, new_dollar, sup, this)107 .into_future(fctx);108109 Ok(ctx)110 }111 }112113 UnboundLocals { fctx, locals }114}115116#[allow(clippy::too_many_lines)]117pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {118 let mut builder = ObjValueBuilder::new();119 let locals = Rc::new(120 members121 .iter()122 .filter_map(|m| match m {123 Member::BindStmt(bind) => Some(bind.clone()),124 _ => None,125 })126 .collect::<Vec<_>>(),127 );128129 let fctx = Context::new_future();130131 // We have single context for all fields, so we can cache binds132 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));133134 for member in members.iter() {135 match member {136 Member::Field(FieldMember {137 name,138 plus,139 params: None,140 visibility,141 value,142 }) => {143 #[derive(Trace)]144 struct UnboundValue<B: Trace> {145 uctx: B,146 value: LocExpr,147 name: IStr,148 }149 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {150 type Bound = Val;151 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {152 Ok(evaluate_named(153 self.uctx.bind(sup, this)?,154 &self.value,155 self.name.clone(),156 )?)157 }158 }159160 let name = evaluate_field_name(ctx.clone(), name)?;161 let Some(name) = name else {162 continue;163 };164165 builder166 .member(name.clone())167 .with_add(*plus)168 .with_visibility(*visibility)169 .with_location(value.1.clone())170 .bindable(tb!(UnboundValue {171 uctx: uctx.clone(),172 value: value.clone(),173 name: name.clone()174 }))?;175 }176 Member::Field(FieldMember {177 name,178 params: Some(params),179 value,180 ..181 }) => {182 #[derive(Trace)]183 struct UnboundMethod<B: Trace> {184 uctx: B,185 value: LocExpr,186 params: ParamsDesc,187 name: IStr,188 }189 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {190 type Bound = Val;191 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {192 Ok(evaluate_method(193 self.uctx.bind(sup, this)?,194 self.name.clone(),195 self.params.clone(),196 self.value.clone(),197 ))198 }199 }200201 let Some(name) = evaluate_field_name(ctx.clone(), name)? else {202 continue;203 };204205 builder206 .member(name.clone())207 .hide()208 .with_location(value.1.clone())209 .bindable(tb!(UnboundMethod {210 uctx: uctx.clone(),211 value: value.clone(),212 params: params.clone(),213 name: name.clone()214 }))?;215 }216 Member::BindStmt(_) => {}217 Member::AssertStmt(stmt) => {218 #[derive(Trace)]219 struct ObjectAssert<B: Trace> {220 uctx: B,221 assert: AssertStmt,222 }223 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {224 fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {225 let ctx = self.uctx.bind(sup, this)?;226 evaluate_assert(ctx, &self.assert)227 }228 }229 builder.assert(tb!(ObjectAssert {230 uctx: uctx.clone(),231 assert: stmt.clone(),232 }));233 }234 }235 }236 let this = builder.build();237 fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));238 Ok(this)239}240241pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {242 Ok(match object {243 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,244 ObjBody::ObjComp(obj) => {245 let mut builder = ObjValueBuilder::new();246 let locals = Rc::new(247 obj.pre_locals248 .iter()249 .chain(obj.post_locals.iter())250 .cloned()251 .collect::<Vec<_>>(),252 );253 let mut ctxs = vec![];254 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {255 let key = evaluate(ctx.clone(), &obj.key)?;256 let fctx = Context::new_future();257 ctxs.push((ctx, fctx.clone()));258 let uctx = evaluate_object_locals(fctx, locals.clone());259260 match key {261 Val::Null => {}262 Val::Str(n) => {263 #[derive(Trace)]264 struct UnboundValue<B: Trace> {265 uctx: B,266 value: LocExpr,267 }268 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {269 type Bound = Val;270 fn bind(271 &self,272 sup: Option<ObjValue>,273 this: Option<ObjValue>,274 ) -> Result<Val> {275 Ok(evaluate(276 self.uctx.bind(sup, this.clone())?.extend(277 GcHashMap::new(),278 None,279 None,280 this,281 ),282 &self.value,283 )?)284 }285 }286 builder287 .member(n)288 .with_location(obj.value.1.clone())289 .with_add(obj.plus)290 .bindable(tb!(UnboundValue {291 uctx,292 value: obj.value.clone(),293 }))?;294 }295 v => throw!(FieldMustBeStringGot(v.value_type())),296 }297298 Ok(())299 })?;300301 let this = builder.build();302 for (ctx, fctx) in ctxs {303 let _ctx = ctx304 .extend(GcHashMap::new(), None, None, Some(this.clone()))305 .into_future(fctx);306 }307 this308 }309 })310}311312pub fn evaluate_apply(313 ctx: Context,314 value: &LocExpr,315 args: &ArgsDesc,316 loc: CallLocation<'_>,317 tailstrict: bool,318) -> Result<Val> {319 let value = evaluate(ctx.clone(), value)?;320 Ok(match value {321 Val::Func(f) => {322 let body = || f.evaluate(ctx, loc, args, tailstrict);323 if tailstrict {324 body()?325 } else {326 State::push(loc, || format!("function <{}> call", f.name()), body)?327 }328 }329 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),330 })331}332333pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {334 let value = &assertion.0;335 let msg = &assertion.1;336 let assertion_result = State::push(337 CallLocation::new(&value.1),338 || "assertion condition".to_owned(),339 || bool::from_untyped(evaluate(ctx.clone(), value)?),340 )?;341 if !assertion_result {342 State::push(343 CallLocation::new(&value.1),344 || "assertion failure".to_owned(),345 || {346 if let Some(msg) = msg {347 throw!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));348 }349 throw!(AssertionFailed(Val::Null.to_string()?));350 },351 )?;352 }353 Ok(())354}355356pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {357 use Expr::*;358 let LocExpr(raw_expr, _loc) = expr;359 Ok(match &**raw_expr {360 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),361 _ => evaluate(ctx, expr)?,362 })363}364365#[allow(clippy::too_many_lines)]366pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {367 use Expr::*;368 let LocExpr(expr, loc) = expr;369 // let bp = with_state(|s| s.0.stop_at.borrow().clone());370 Ok(match &**expr {371 Literal(LiteralType::This) => {372 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)373 }374 Literal(LiteralType::Super) => Val::Obj(375 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(376 ctx.this()377 .clone()378 .expect("if super exists - then this should to"),379 ),380 ),381 Literal(LiteralType::Dollar) => {382 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)383 }384 Literal(LiteralType::True) => Val::Bool(true),385 Literal(LiteralType::False) => Val::Bool(false),386 Literal(LiteralType::Null) => Val::Null,387 Parened(e) => evaluate(ctx, e)?,388 Str(v) => Val::Str(v.clone()),389 Num(v) => Val::new_checked_num(*v)?,390 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,391 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,392 Var(name) => State::push(393 CallLocation::new(loc),394 || format!("variable <{name}> access"),395 || ctx.binding(name.clone())?.evaluate(),396 )?,397 Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {398 (Val::Obj(v), Val::Str(key)) => State::push(399 CallLocation::new(loc),400 || format!("field <{key}> access"),401 || match v.get(key.clone()) {402 Ok(Some(v)) => Ok(v),403 #[cfg(not(feature = "friendly-errors"))]404 Ok(None) => throw!(NoSuchField(key.clone(), vec![])),405 #[cfg(feature = "friendly-errors")]406 Ok(None) => {407 let mut heap = Vec::new();408 for field in v.fields_ex(409 true,410 #[cfg(feature = "exp-preserve-order")]411 false,412 ) {413 let conf = strsim::jaro_winkler(&field as &str, &key as &str);414 if conf < 0.8 {415 continue;416 }417 heap.push((conf, field));418 }419 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));420421 throw!(NoSuchField(422 key.clone(),423 heap.into_iter().map(|(_, v)| v).collect()424 ))425 }426 Err(e) => Err(e),427 },428 )?,429 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(430 ValType::Obj,431 ValType::Str,432 n.value_type(),433 )),434435 (Val::Arr(v), Val::Num(n)) => {436 if n.fract() > f64::EPSILON {437 throw!(FractionalIndex)438 }439 v.get(n as usize)?440 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?441 }442 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),443 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(444 ValType::Arr,445 ValType::Num,446 n.value_type(),447 )),448449 (Val::Str(s), Val::Num(n)) => Val::Str({450 let v: IStr = s451 .chars()452 .skip(n as usize)453 .take(1)454 .collect::<String>()455 .into();456 if v.is_empty() {457 let size = s.chars().count();458 throw!(StringBoundsError(n as usize, size))459 }460 v461 }),462 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(463 ValType::Str,464 ValType::Num,465 n.value_type(),466 )),467468 (v, _) => throw!(CantIndexInto(v.value_type())),469 },470 LocalExpr(bindings, returned) => {471 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =472 GcHashMap::with_capacity(bindings.len());473 let fctx = Context::new_future();474 for b in bindings {475 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;476 }477 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);478 evaluate(ctx, &returned.clone())?479 }480 Arr(items) => {481 let mut out = Vec::with_capacity(items.len());482 for item in items {483 // TODO: Implement ArrValue::Lazy with same context for every element?484 #[derive(Trace)]485 struct ArrayElement {486 ctx: Context,487 item: LocExpr,488 }489 impl ThunkValue for ArrayElement {490 type Output = Val;491 fn get(self: Box<Self>) -> Result<Val> {492 evaluate(self.ctx, &self.item)493 }494 }495 out.push(Thunk::new(tb!(ArrayElement {496 ctx: ctx.clone(),497 item: item.clone(),498 })));499 }500 Val::Arr(out.into())501 }502 ArrComp(expr, comp_specs) => {503 let mut out = Vec::new();504 evaluate_comp(ctx, comp_specs, &mut |ctx| {505 out.push(evaluate(ctx, expr)?);506 Ok(())507 })?;508 Val::Arr(ArrValue::Eager(Cc::new(out)))509 }510 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),511 ObjExtend(a, b) => evaluate_add_op(512 &evaluate(ctx.clone(), a)?,513 &Val::Obj(evaluate_object(ctx, b)?),514 )?,515 Apply(value, args, tailstrict) => {516 evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?517 }518 Function(params, body) => {519 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())520 }521 AssertExpr(assert, returned) => {522 evaluate_assert(ctx.clone(), assert)?;523 evaluate(ctx, returned)?524 }525 ErrorStmt(e) => State::push(526 CallLocation::new(loc),527 || "error statement".to_owned(),528 || throw!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),529 )?,530 IfElse {531 cond,532 cond_then,533 cond_else,534 } => {535 if State::push(536 CallLocation::new(loc),537 || "if condition".to_owned(),538 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),539 )? {540 evaluate(ctx, cond_then)?541 } else {542 match cond_else {543 Some(v) => evaluate(ctx, v)?,544 None => Val::Null,545 }546 }547 }548 Slice(value, desc) => {549 fn parse_idx<T: Typed>(550 loc: CallLocation<'_>,551 ctx: &Context,552 expr: &Option<LocExpr>,553 desc: &'static str,554 ) -> Result<Option<T>> {555 if let Some(value) = expr {556 Ok(Some(State::push(557 loc,558 || format!("slice {desc}"),559 || T::from_untyped(evaluate(ctx.clone(), value)?),560 )?))561 } else {562 Ok(None)563 }564 }565566 let indexable = evaluate(ctx.clone(), value)?;567 let loc = CallLocation::new(loc);568569 let start = parse_idx(loc, &ctx, &desc.start, "start")?;570 let end = parse_idx(loc, &ctx, &desc.end, "end")?;571 let step = parse_idx(loc, &ctx, &desc.step, "step")?;572573 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?574 }575 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {576 let tmp = loc.clone().0;577 let s = ctx.state();578 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;579 match i {580 Import(_) => State::push(581 CallLocation::new(loc),582 || format!("import {:?}", path.clone()),583 || s.import_resolved(resolved_path),584 )?,585 ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),586 ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),587 _ => unreachable!(),588 }589 }590 })591}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -98,7 +98,7 @@
#[derive(Clone, Trace)]
pub enum MaybeUnbound {
/// Value needs to be bound to `this`/`super`
- Unbound(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+ Unbound(Cc<TraceBox<dyn Unbound<Bound = Val>>>),
/// Value is object-independent
Bound(Thunk<Val>),
}
@@ -110,10 +110,10 @@
}
impl MaybeUnbound {
/// Attach object context to value, if required
- pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Thunk<Val>> {
+ pub fn evaluate(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {
match self {
Self::Unbound(v) => v.bind(sup, this),
- Self::Bound(v) => Ok(v.clone()),
+ Self::Bound(v) => Ok(v.evaluate()?),
}
}
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -440,9 +440,7 @@
}
}
fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {
- v.invoke
- .evaluate(self.0.sup.clone(), Some(real_this))?
- .evaluate()
+ v.invoke.evaluate(self.0.sup.clone(), Some(real_this))
}
fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {
@@ -605,7 +603,7 @@
pub fn thunk(self, value: Thunk<Val>) -> Result<()> {
self.binding(MaybeUnbound::Bound(value))
}
- pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) -> Result<()> {
+ pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) -> Result<()> {
self.binding(MaybeUnbound::Unbound(Cc::new(bindable)))
}
pub fn binding(self, binding: MaybeUnbound) -> Result<()> {
@@ -628,7 +626,7 @@
pub fn value(self, value: Val) {
self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
}
- pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
+ pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {
self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
}
pub fn binding(self, binding: MaybeUnbound) {