difftreelog
refactor move push_frame out of State struct
in: master
14 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, FieldName,7 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use self::destructure::destruct;12use crate::{13 arr::ArrValue,14 bail,15 destructure::evaluate_dest,16 error::{suggest_object_fields, ErrorKind::*},17 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},18 function::{CallLocation, FuncDesc, FuncVal},19 typed::Typed,20 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},21 Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,22 ResultExt, State, Unbound, Val,23};24pub mod destructure;25pub mod operator;2627pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {28 fn is_trivial(expr: &LocExpr) -> bool {29 match expr.expr() {30 Expr::Str(_)31 | Expr::Num(_)32 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,33 Expr::Arr(a) => a.iter().all(is_trivial),34 Expr::Parened(e) => is_trivial(e),35 _ => false,36 }37 }38 Some(match expr.expr() {39 Expr::Str(s) => Val::string(s.clone()),40 Expr::Num(n) => {41 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))42 }43 Expr::Literal(LiteralType::False) => Val::Bool(false),44 Expr::Literal(LiteralType::True) => Val::Bool(true),45 Expr::Literal(LiteralType::Null) => Val::Null,46 Expr::Arr(n) => {47 if n.iter().any(|e| !is_trivial(e)) {48 return None;49 }50 Val::Arr(ArrValue::eager(51 n.iter()52 .map(evaluate_trivial)53 .map(|e| e.expect("checked trivial"))54 .collect(),55 ))56 }57 Expr::Parened(e) => evaluate_trivial(e)?,58 _ => return None,59 })60}6162pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {63 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {64 name,65 ctx,66 params,67 body,68 })))69}7071pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {72 Ok(match field_name {73 FieldName::Fixed(n) => Some(n.clone()),74 FieldName::Dyn(expr) => State::push(75 CallLocation::new(&expr.span()),76 || "evaluating field name".to_string(),77 || {78 let value = evaluate(ctx, expr)?;79 if matches!(value, Val::Null) {80 Ok(None)81 } else {82 Ok(Some(IStr::from_untyped(value)?))83 }84 },85 )?,86 })87}8889pub fn evaluate_comp(90 ctx: Context,91 specs: &[CompSpec],92 callback: &mut impl FnMut(Context) -> Result<()>,93) -> Result<()> {94 match specs.first() {95 None => callback(ctx)?,96 Some(CompSpec::IfSpec(IfSpecData(cond))) => {97 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {98 evaluate_comp(ctx, &specs[1..], callback)?;99 }100 }101 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {102 Val::Arr(list) => {103 for item in list.iter_lazy() {104 let fctx = Pending::new();105 let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());106 destruct(var, item, fctx.clone(), &mut new_bindings)?;107 let ctx = ctx108 .clone()109 .extend(new_bindings, None, None, None)110 .into_future(fctx);111112 evaluate_comp(ctx, &specs[1..], callback)?;113 }114 }115 #[cfg(feature = "exp-object-iteration")]116 Val::Obj(obj) => {117 for field in obj.fields(118 // TODO: Should there be ability to preserve iteration order?119 #[cfg(feature = "exp-preserve-order")]120 false,121 ) {122 #[derive(Trace)]123 struct ObjectFieldThunk {124 obj: ObjValue,125 field: IStr,126 }127 impl ThunkValue for ObjectFieldThunk {128 type Output = Val;129130 fn get(self: Box<Self>) -> Result<Self::Output> {131 self.obj.get(self.field).transpose().expect(132 "field exists, as field name was obtained from object.fields()",133 )134 }135 }136137 let fctx = Pending::new();138 let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());139 let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![140 Thunk::evaluated(Val::string(field.clone())),141 Thunk::new(ObjectFieldThunk {142 field: field.clone(),143 obj: obj.clone(),144 }),145 ])));146 destruct(var, value, fctx.clone(), &mut new_bindings)?;147 let ctx = ctx148 .clone()149 .extend(new_bindings, None, None, None)150 .into_future(fctx);151152 evaluate_comp(ctx, &specs[1..], callback)?;153 }154 }155 _ => bail!(InComprehensionCanOnlyIterateOverArray),156 },157 }158 Ok(())159}160161trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}162impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}163164fn evaluate_object_locals(165 fctx: Pending<Context>,166 locals: Rc<Vec<BindSpec>>,167) -> impl CloneableUnbound<Context> {168 #[derive(Trace, Clone)]169 struct UnboundLocals {170 fctx: Pending<Context>,171 locals: Rc<Vec<BindSpec>>,172 }173 impl Unbound for UnboundLocals {174 type Bound = Context;175176 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {177 let fctx = Context::new_future();178 let mut new_bindings =179 GcHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());180 for b in self.locals.iter() {181 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;182 }183184 let ctx = self.fctx.unwrap();185 let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());186187 let ctx = ctx188 .extend(new_bindings, new_dollar, sup, this)189 .into_future(fctx);190191 Ok(ctx)192 }193 }194195 UnboundLocals { fctx, locals }196}197198pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(199 builder: &mut ObjValueBuilder,200 ctx: Context,201 uctx: B,202 field: &FieldMember,203) -> Result<()> {204 let name = evaluate_field_name(ctx, &field.name)?;205 let Some(name) = name else {206 return Ok(());207 };208209 match field {210 FieldMember {211 plus,212 params: None,213 visibility,214 value,215 ..216 } => {217 #[derive(Trace)]218 struct UnboundValue<B: Trace> {219 uctx: B,220 value: LocExpr,221 name: IStr,222 }223 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {224 type Bound = Val;225 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {226 evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())227 }228 }229230 builder231 .field(name.clone())232 .with_add(*plus)233 .with_visibility(*visibility)234 .with_location(value.span())235 .bindable(UnboundValue {236 uctx,237 value: value.clone(),238 name,239 })?;240 }241 FieldMember {242 params: Some(params),243 visibility,244 value,245 ..246 } => {247 #[derive(Trace)]248 struct UnboundMethod<B: Trace> {249 uctx: B,250 value: LocExpr,251 params: ParamsDesc,252 name: IStr,253 }254 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {255 type Bound = Val;256 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {257 Ok(evaluate_method(258 self.uctx.bind(sup, this)?,259 self.name.clone(),260 self.params.clone(),261 self.value.clone(),262 ))263 }264 }265266 builder267 .field(name.clone())268 .with_visibility(*visibility)269 .with_location(value.span())270 .bindable(UnboundMethod {271 uctx,272 value: value.clone(),273 params: params.clone(),274 name,275 })?;276 }277 }278 Ok(())279}280281#[allow(clippy::too_many_lines)]282pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {283 let mut builder = ObjValueBuilder::new();284 let locals = Rc::new(285 members286 .iter()287 .filter_map(|m| match m {288 Member::BindStmt(bind) => Some(bind.clone()),289 _ => None,290 })291 .collect::<Vec<_>>(),292 );293294 let fctx = Context::new_future();295296 // We have single context for all fields, so we can cache binds297 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));298299 for member in members {300 match member {301 Member::Field(field) => {302 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;303 }304 Member::AssertStmt(stmt) => {305 #[derive(Trace)]306 struct ObjectAssert<B: Trace> {307 uctx: B,308 assert: AssertStmt,309 }310 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {311 fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {312 let ctx = self.uctx.bind(sup, this)?;313 evaluate_assert(ctx, &self.assert)314 }315 }316 builder.assert(ObjectAssert {317 uctx: uctx.clone(),318 assert: stmt.clone(),319 });320 }321 Member::BindStmt(_) => {322 // Already handled323 }324 }325 }326 let this = builder.build();327 fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));328 Ok(this)329}330331pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {332 Ok(match object {333 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,334 ObjBody::ObjComp(obj) => {335 let mut builder = ObjValueBuilder::new();336 let locals = Rc::new(337 obj.pre_locals338 .iter()339 .chain(obj.post_locals.iter())340 .cloned()341 .collect::<Vec<_>>(),342 );343 let mut ctxs = vec![];344 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {345 let fctx = Context::new_future();346 ctxs.push((ctx.clone(), fctx.clone()));347 let uctx = evaluate_object_locals(fctx, locals.clone());348349 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)350 })?;351352 let this = builder.build();353 for (ctx, fctx) in ctxs {354 let _ctx = ctx355 .extend(GcHashMap::new(), None, None, Some(this.clone()))356 .into_future(fctx);357 }358 this359 }360 })361}362363pub fn evaluate_apply(364 ctx: Context,365 value: &LocExpr,366 args: &ArgsDesc,367 loc: CallLocation<'_>,368 tailstrict: bool,369) -> Result<Val> {370 let value = evaluate(ctx.clone(), value)?;371 Ok(match value {372 Val::Func(f) => {373 let body = || f.evaluate(ctx, loc, args, tailstrict);374 if tailstrict {375 body()?376 } else {377 State::push(loc, || format!("function <{}> call", f.name()), body)?378 }379 }380 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),381 })382}383384pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {385 let value = &assertion.0;386 let msg = &assertion.1;387 let assertion_result = State::push(388 CallLocation::new(&value.span()),389 || "assertion condition".to_owned(),390 || bool::from_untyped(evaluate(ctx.clone(), value)?),391 )?;392 if !assertion_result {393 State::push(394 CallLocation::new(&value.span()),395 || "assertion failure".to_owned(),396 || {397 if let Some(msg) = msg {398 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));399 }400 bail!(AssertionFailed(Val::Null.to_string()?));401 },402 )?;403 }404 Ok(())405}406407pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {408 use Expr::*;409 Ok(match expr.expr() {410 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),411 _ => evaluate(ctx, expr)?,412 })413}414415#[allow(clippy::too_many_lines)]416pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {417 use Expr::*;418419 if let Some(trivial) = evaluate_trivial(expr) {420 return Ok(trivial);421 }422 let loc = expr.span();423 Ok(match expr.expr() {424 Literal(LiteralType::This) => {425 Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())426 }427 Literal(LiteralType::Super) => Val::Obj(428 ctx.super_obj().ok_or(NoSuperFound)?.with_this(429 ctx.this()430 .expect("if super exists - then this should too")431 .clone(),432 ),433 ),434 Literal(LiteralType::Dollar) => {435 Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())436 }437 Literal(LiteralType::True) => Val::Bool(true),438 Literal(LiteralType::False) => Val::Bool(false),439 Literal(LiteralType::Null) => Val::Null,440 Parened(e) => evaluate(ctx, e)?,441 Str(v) => Val::string(v.clone()),442 Num(v) => Val::try_num(*v)?,443 // I have tried to remove special behavior from super by implementing standalone-super444 // expresion, but looks like this case still needs special treatment.445 //446 // Note that other jsonnet implementations will fail on `if value in (super)` expression,447 // because the standalone super literal is not supported, that is because in other448 // implementations `in super` treated differently from in `smth_else`.449 BinaryOp(field, BinaryOpType::In, e)450 if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>451 {452 let Some(super_obj) = ctx.super_obj() else {453 return Ok(Val::Bool(false));454 };455 let field = evaluate(ctx.clone(), field)?;456 Val::Bool(super_obj.has_field_ex(field.to_string()?, true))457 }458 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,459 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,460 Var(name) => State::push(461 CallLocation::new(&loc),462 || format!("variable <{name}> access"),463 || ctx.binding(name.clone())?.evaluate(),464 )?,465 Index { indexable, parts } => {466 let mut parts = parts.iter();467 let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {468 let part = parts.next().expect("at least part should exist");469 let Some(super_obj) = ctx.super_obj() else {470 #[cfg(feature = "exp-null-coaelse")]471 if part.null_coaelse {472 return Ok(Val::Null);473 }474 bail!(NoSuperFound)475 };476 let name = evaluate(ctx.clone(), &part.value)?;477478 let Val::Str(name) = name else {479 bail!(ValueIndexMustBeTypeGot(480 ValType::Obj,481 ValType::Str,482 name.value_type(),483 ))484 };485486 let this = ctx487 .this()488 .expect("no this found, while super present, should not happen");489 let name = name.into_flat();490 match super_obj491 .get_for(name.clone(), this.clone())492 .with_description_src(&part.value, || format!("field <{name}> access"))?493 {494 Some(v) => v,495 #[cfg(feature = "exp-null-coaelse")]496 None if part.null_coaelse => return Ok(Val::Null),497 None => {498 let suggestions = suggest_object_fields(super_obj, name.clone());499500 bail!(NoSuchField(name, suggestions))501 }502 }503 } else {504 evaluate(ctx.clone(), indexable)?505 };506507 for part in parts {508 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {509 (Val::Obj(v), Val::Str(key)) => match v510 .get(key.clone().into_flat())511 .with_description_src(&part.value, || format!("field <{key}> access"))?512 {513 Some(v) => v,514 #[cfg(feature = "exp-null-coaelse")]515 None if part.null_coaelse => return Ok(Val::Null),516 None => {517 let suggestions = suggest_object_fields(&v, key.clone().into_flat());518519 return Err(Error::from(NoSuchField(520 key.clone().into_flat(),521 suggestions,522 )))523 .with_description_src(&part.value, || format!("field <{key}> access"));524 }525 },526 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(527 ValType::Obj,528 ValType::Str,529 n.value_type(),530 )),531 (Val::Arr(v), Val::Num(n)) => {532 let n = n.get();533 if n.fract() > f64::EPSILON {534 bail!(FractionalIndex)535 }536 if n < 0.0 {537 bail!(ArrayBoundsError(n as isize, v.len()));538 }539 v.get(n as usize)?540 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?541 }542 (Val::Arr(_), Val::Str(n)) => {543 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))544 }545 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(546 ValType::Arr,547 ValType::Num,548 n.value_type(),549 )),550551 (Val::Str(s), Val::Num(n)) => Val::Str({552 let v: IStr = s553 .clone()554 .into_flat()555 .chars()556 .skip(n.get() as usize)557 .take(1)558 .collect::<String>()559 .into();560 if v.is_empty() {561 let size = s.into_flat().chars().count();562 bail!(StringBoundsError(n.get() as usize, size))563 }564 StrValue::Flat(v)565 }),566 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(567 ValType::Str,568 ValType::Num,569 n.value_type(),570 )),571 #[cfg(feature = "exp-null-coaelse")]572 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),573 (v, _) => bail!(CantIndexInto(v.value_type())),574 };575 }576 indexable577 }578 LocalExpr(bindings, returned) => {579 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =580 GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());581 let fctx = Context::new_future();582 for b in bindings {583 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;584 }585 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);586 evaluate(ctx, &returned.clone())?587 }588 Arr(items) => {589 if items.is_empty() {590 Val::Arr(ArrValue::empty())591 } else if items.len() == 1 {592 #[derive(Trace)]593 struct ArrayElement {594 ctx: Context,595 item: LocExpr,596 }597 impl ThunkValue for ArrayElement {598 type Output = Val;599 fn get(self: Box<Self>) -> Result<Val> {600 evaluate(self.ctx, &self.item)601 }602 }603 Val::Arr(ArrValue::lazy(vec![Thunk::new(ArrayElement {604 ctx,605 item: items[0].clone(),606 })]))607 } else {608 Val::Arr(ArrValue::expr(ctx, items.iter().cloned()))609 }610 }611 ArrComp(expr, comp_specs) => {612 let mut out = Vec::new();613 evaluate_comp(ctx, comp_specs, &mut |ctx| {614 #[derive(Trace)]615 struct EvaluateThunk {616 ctx: Context,617 expr: LocExpr,618 }619 impl ThunkValue for EvaluateThunk {620 type Output = Val;621 fn get(self: Box<Self>) -> Result<Val> {622 evaluate(self.ctx, &self.expr)623 }624 }625 out.push(Thunk::new(EvaluateThunk {626 ctx,627 expr: expr.clone(),628 }));629 Ok(())630 })?;631 Val::Arr(ArrValue::lazy(out))632 }633 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),634 ObjExtend(a, b) => evaluate_add_op(635 &evaluate(ctx.clone(), a)?,636 &Val::Obj(evaluate_object(ctx, b)?),637 )?,638 Apply(value, args, tailstrict) => {639 evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)?640 }641 Function(params, body) => {642 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())643 }644 AssertExpr(assert, returned) => {645 evaluate_assert(ctx.clone(), assert)?;646 evaluate(ctx, returned)?647 }648 ErrorStmt(e) => State::push(649 CallLocation::new(&loc),650 || "error statement".to_owned(),651 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),652 )?,653 IfElse {654 cond,655 cond_then,656 cond_else,657 } => {658 if State::push(659 CallLocation::new(&loc),660 || "if condition".to_owned(),661 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),662 )? {663 evaluate(ctx, cond_then)?664 } else {665 match cond_else {666 Some(v) => evaluate(ctx, v)?,667 None => Val::Null,668 }669 }670 }671 Slice(value, desc) => {672 fn parse_idx<T: Typed>(673 loc: CallLocation<'_>,674 ctx: &Context,675 expr: Option<&LocExpr>,676 desc: &'static str,677 ) -> Result<Option<T>> {678 if let Some(value) = expr {679 Ok(Some(State::push(680 loc,681 || format!("slice {desc}"),682 || T::from_untyped(evaluate(ctx.clone(), value)?),683 )?))684 } else {685 Ok(None)686 }687 }688689 let indexable = evaluate(ctx.clone(), value)?;690 let loc = CallLocation::new(&loc);691692 let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;693 let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;694 let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;695696 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?697 }698 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {699 let Expr::Str(path) = &path.expr() else {700 bail!("computed imports are not supported")701 };702 let tmp = loc.clone().0;703 let s = ctx.state();704 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;705 match i {706 Import(_) => State::push(707 CallLocation::new(&loc),708 || format!("import {:?}", path.clone()),709 || s.import_resolved(resolved_path),710 )?,711 ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),712 ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),713 _ => unreachable!(),714 }715 }716 })717}1use std::rc::Rc;23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, FieldMember, FieldName,7 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc,8};9use jrsonnet_types::ValType;1011use self::destructure::destruct;12use crate::{13 arr::ArrValue,14 bail,15 destructure::evaluate_dest,16 error::{suggest_object_fields, ErrorKind::*},17 evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},18 function::{CallLocation, FuncDesc, FuncVal},19 in_frame,20 typed::Typed,21 val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},22 Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,23 ResultExt, Unbound, Val,24};25pub mod destructure;26pub mod operator;2728pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {29 fn is_trivial(expr: &LocExpr) -> bool {30 match expr.expr() {31 Expr::Str(_)32 | Expr::Num(_)33 | Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,34 Expr::Arr(a) => a.iter().all(is_trivial),35 Expr::Parened(e) => is_trivial(e),36 _ => false,37 }38 }39 Some(match expr.expr() {40 Expr::Str(s) => Val::string(s.clone()),41 Expr::Num(n) => {42 Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))43 }44 Expr::Literal(LiteralType::False) => Val::Bool(false),45 Expr::Literal(LiteralType::True) => Val::Bool(true),46 Expr::Literal(LiteralType::Null) => Val::Null,47 Expr::Arr(n) => {48 if n.iter().any(|e| !is_trivial(e)) {49 return None;50 }51 Val::Arr(ArrValue::eager(52 n.iter()53 .map(evaluate_trivial)54 .map(|e| e.expect("checked trivial"))55 .collect(),56 ))57 }58 Expr::Parened(e) => evaluate_trivial(e)?,59 _ => return None,60 })61}6263pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {64 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {65 name,66 ctx,67 params,68 body,69 })))70}7172pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {73 Ok(match field_name {74 FieldName::Fixed(n) => Some(n.clone()),75 FieldName::Dyn(expr) => in_frame(76 CallLocation::new(&expr.span()),77 || "evaluating field name".to_string(),78 || {79 let value = evaluate(ctx, expr)?;80 if matches!(value, Val::Null) {81 Ok(None)82 } else {83 Ok(Some(IStr::from_untyped(value)?))84 }85 },86 )?,87 })88}8990pub fn evaluate_comp(91 ctx: Context,92 specs: &[CompSpec],93 callback: &mut impl FnMut(Context) -> Result<()>,94) -> Result<()> {95 match specs.first() {96 None => callback(ctx)?,97 Some(CompSpec::IfSpec(IfSpecData(cond))) => {98 if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {99 evaluate_comp(ctx, &specs[1..], callback)?;100 }101 }102 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => match evaluate(ctx.clone(), expr)? {103 Val::Arr(list) => {104 for item in list.iter_lazy() {105 let fctx = Pending::new();106 let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());107 destruct(var, item, fctx.clone(), &mut new_bindings)?;108 let ctx = ctx109 .clone()110 .extend(new_bindings, None, None, None)111 .into_future(fctx);112113 evaluate_comp(ctx, &specs[1..], callback)?;114 }115 }116 #[cfg(feature = "exp-object-iteration")]117 Val::Obj(obj) => {118 for field in obj.fields(119 // TODO: Should there be ability to preserve iteration order?120 #[cfg(feature = "exp-preserve-order")]121 false,122 ) {123 #[derive(Trace)]124 struct ObjectFieldThunk {125 obj: ObjValue,126 field: IStr,127 }128 impl ThunkValue for ObjectFieldThunk {129 type Output = Val;130131 fn get(self: Box<Self>) -> Result<Self::Output> {132 self.obj.get(self.field).transpose().expect(133 "field exists, as field name was obtained from object.fields()",134 )135 }136 }137138 let fctx = Pending::new();139 let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());140 let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(vec![141 Thunk::evaluated(Val::string(field.clone())),142 Thunk::new(ObjectFieldThunk {143 field: field.clone(),144 obj: obj.clone(),145 }),146 ])));147 destruct(var, value, fctx.clone(), &mut new_bindings)?;148 let ctx = ctx149 .clone()150 .extend(new_bindings, None, None, None)151 .into_future(fctx);152153 evaluate_comp(ctx, &specs[1..], callback)?;154 }155 }156 _ => bail!(InComprehensionCanOnlyIterateOverArray),157 },158 }159 Ok(())160}161162trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}163impl<V, T> CloneableUnbound<T> for V where V: Unbound<Bound = T> + Clone {}164165fn evaluate_object_locals(166 fctx: Pending<Context>,167 locals: Rc<Vec<BindSpec>>,168) -> impl CloneableUnbound<Context> {169 #[derive(Trace, Clone)]170 struct UnboundLocals {171 fctx: Pending<Context>,172 locals: Rc<Vec<BindSpec>>,173 }174 impl Unbound for UnboundLocals {175 type Bound = Context;176177 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Context> {178 let fctx = Context::new_future();179 let mut new_bindings =180 GcHashMap::with_capacity(self.locals.iter().map(BindSpec::capacity_hint).sum());181 for b in self.locals.iter() {182 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;183 }184185 let ctx = self.fctx.unwrap();186 let new_dollar = ctx.dollar().cloned().or_else(|| this.clone());187188 let ctx = ctx189 .extend(new_bindings, new_dollar, sup, this)190 .into_future(fctx);191192 Ok(ctx)193 }194 }195196 UnboundLocals { fctx, locals }197}198199pub fn evaluate_field_member<B: Unbound<Bound = Context> + Clone>(200 builder: &mut ObjValueBuilder,201 ctx: Context,202 uctx: B,203 field: &FieldMember,204) -> Result<()> {205 let name = evaluate_field_name(ctx, &field.name)?;206 let Some(name) = name else {207 return Ok(());208 };209210 match field {211 FieldMember {212 plus,213 params: None,214 visibility,215 value,216 ..217 } => {218 #[derive(Trace)]219 struct UnboundValue<B: Trace> {220 uctx: B,221 value: LocExpr,222 name: IStr,223 }224 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {225 type Bound = Val;226 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {227 evaluate_named(self.uctx.bind(sup, this)?, &self.value, self.name.clone())228 }229 }230231 builder232 .field(name.clone())233 .with_add(*plus)234 .with_visibility(*visibility)235 .with_location(value.span())236 .bindable(UnboundValue {237 uctx,238 value: value.clone(),239 name,240 })?;241 }242 FieldMember {243 params: Some(params),244 visibility,245 value,246 ..247 } => {248 #[derive(Trace)]249 struct UnboundMethod<B: Trace> {250 uctx: B,251 value: LocExpr,252 params: ParamsDesc,253 name: IStr,254 }255 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {256 type Bound = Val;257 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Val> {258 Ok(evaluate_method(259 self.uctx.bind(sup, this)?,260 self.name.clone(),261 self.params.clone(),262 self.value.clone(),263 ))264 }265 }266267 builder268 .field(name.clone())269 .with_visibility(*visibility)270 .with_location(value.span())271 .bindable(UnboundMethod {272 uctx,273 value: value.clone(),274 params: params.clone(),275 name,276 })?;277 }278 }279 Ok(())280}281282#[allow(clippy::too_many_lines)]283pub fn evaluate_member_list_object(ctx: Context, members: &[Member]) -> Result<ObjValue> {284 let mut builder = ObjValueBuilder::new();285 let locals = Rc::new(286 members287 .iter()288 .filter_map(|m| match m {289 Member::BindStmt(bind) => Some(bind.clone()),290 _ => None,291 })292 .collect::<Vec<_>>(),293 );294295 let fctx = Context::new_future();296297 // We have single context for all fields, so we can cache binds298 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));299300 for member in members {301 match member {302 Member::Field(field) => {303 evaluate_field_member(&mut builder, ctx.clone(), uctx.clone(), field)?;304 }305 Member::AssertStmt(stmt) => {306 #[derive(Trace)]307 struct ObjectAssert<B: Trace> {308 uctx: B,309 assert: AssertStmt,310 }311 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {312 fn run(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<()> {313 let ctx = self.uctx.bind(sup, this)?;314 evaluate_assert(ctx, &self.assert)315 }316 }317 builder.assert(ObjectAssert {318 uctx: uctx.clone(),319 assert: stmt.clone(),320 });321 }322 Member::BindStmt(_) => {323 // Already handled324 }325 }326 }327 let this = builder.build();328 fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));329 Ok(this)330}331332pub fn evaluate_object(ctx: Context, object: &ObjBody) -> Result<ObjValue> {333 Ok(match object {334 ObjBody::MemberList(members) => evaluate_member_list_object(ctx, members)?,335 ObjBody::ObjComp(obj) => {336 let mut builder = ObjValueBuilder::new();337 let locals = Rc::new(338 obj.pre_locals339 .iter()340 .chain(obj.post_locals.iter())341 .cloned()342 .collect::<Vec<_>>(),343 );344 let mut ctxs = vec![];345 evaluate_comp(ctx, &obj.compspecs, &mut |ctx| {346 let fctx = Context::new_future();347 ctxs.push((ctx.clone(), fctx.clone()));348 let uctx = evaluate_object_locals(fctx, locals.clone());349350 evaluate_field_member(&mut builder, ctx, uctx, &obj.field)351 })?;352353 let this = builder.build();354 for (ctx, fctx) in ctxs {355 let _ctx = ctx356 .extend(GcHashMap::new(), None, None, Some(this.clone()))357 .into_future(fctx);358 }359 this360 }361 })362}363364pub fn evaluate_apply(365 ctx: Context,366 value: &LocExpr,367 args: &ArgsDesc,368 loc: CallLocation<'_>,369 tailstrict: bool,370) -> Result<Val> {371 let value = evaluate(ctx.clone(), value)?;372 Ok(match value {373 Val::Func(f) => {374 let body = || f.evaluate(ctx, loc, args, tailstrict);375 if tailstrict {376 body()?377 } else {378 in_frame(loc, || format!("function <{}> call", f.name()), body)?379 }380 }381 v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),382 })383}384385pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {386 let value = &assertion.0;387 let msg = &assertion.1;388 let assertion_result = in_frame(389 CallLocation::new(&value.span()),390 || "assertion condition".to_owned(),391 || bool::from_untyped(evaluate(ctx.clone(), value)?),392 )?;393 if !assertion_result {394 in_frame(395 CallLocation::new(&value.span()),396 || "assertion failure".to_owned(),397 || {398 if let Some(msg) = msg {399 bail!(AssertionFailed(evaluate(ctx, msg)?.to_string()?));400 }401 bail!(AssertionFailed(Val::Null.to_string()?));402 },403 )?;404 }405 Ok(())406}407408pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {409 use Expr::*;410 Ok(match expr.expr() {411 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),412 _ => evaluate(ctx, expr)?,413 })414}415416#[allow(clippy::too_many_lines)]417pub fn evaluate(ctx: Context, expr: &LocExpr) -> Result<Val> {418 use Expr::*;419420 if let Some(trivial) = evaluate_trivial(expr) {421 return Ok(trivial);422 }423 let loc = expr.span();424 Ok(match expr.expr() {425 Literal(LiteralType::This) => {426 Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())427 }428 Literal(LiteralType::Super) => Val::Obj(429 ctx.super_obj().ok_or(NoSuperFound)?.with_this(430 ctx.this()431 .expect("if super exists - then this should too")432 .clone(),433 ),434 ),435 Literal(LiteralType::Dollar) => {436 Val::Obj(ctx.dollar().ok_or(NoTopLevelObjectFound)?.clone())437 }438 Literal(LiteralType::True) => Val::Bool(true),439 Literal(LiteralType::False) => Val::Bool(false),440 Literal(LiteralType::Null) => Val::Null,441 Parened(e) => evaluate(ctx, e)?,442 Str(v) => Val::string(v.clone()),443 Num(v) => Val::try_num(*v)?,444 // I have tried to remove special behavior from super by implementing standalone-super445 // expresion, but looks like this case still needs special treatment.446 //447 // Note that other jsonnet implementations will fail on `if value in (super)` expression,448 // because the standalone super literal is not supported, that is because in other449 // implementations `in super` treated differently from in `smth_else`.450 BinaryOp(field, BinaryOpType::In, e)451 if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>452 {453 let Some(super_obj) = ctx.super_obj() else {454 return Ok(Val::Bool(false));455 };456 let field = evaluate(ctx.clone(), field)?;457 Val::Bool(super_obj.has_field_ex(field.to_string()?, true))458 }459 BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,460 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,461 Var(name) => in_frame(462 CallLocation::new(&loc),463 || format!("variable <{name}> access"),464 || ctx.binding(name.clone())?.evaluate(),465 )?,466 Index { indexable, parts } => {467 let mut parts = parts.iter();468 let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {469 let part = parts.next().expect("at least part should exist");470 let Some(super_obj) = ctx.super_obj() else {471 #[cfg(feature = "exp-null-coaelse")]472 if part.null_coaelse {473 return Ok(Val::Null);474 }475 bail!(NoSuperFound)476 };477 let name = evaluate(ctx.clone(), &part.value)?;478479 let Val::Str(name) = name else {480 bail!(ValueIndexMustBeTypeGot(481 ValType::Obj,482 ValType::Str,483 name.value_type(),484 ))485 };486487 let this = ctx488 .this()489 .expect("no this found, while super present, should not happen");490 let name = name.into_flat();491 match super_obj492 .get_for(name.clone(), this.clone())493 .with_description_src(&part.value, || format!("field <{name}> access"))?494 {495 Some(v) => v,496 #[cfg(feature = "exp-null-coaelse")]497 None if part.null_coaelse => return Ok(Val::Null),498 None => {499 let suggestions = suggest_object_fields(super_obj, name.clone());500501 bail!(NoSuchField(name, suggestions))502 }503 }504 } else {505 evaluate(ctx.clone(), indexable)?506 };507508 for part in parts {509 indexable = match (indexable, evaluate(ctx.clone(), &part.value)?) {510 (Val::Obj(v), Val::Str(key)) => match v511 .get(key.clone().into_flat())512 .with_description_src(&part.value, || format!("field <{key}> access"))?513 {514 Some(v) => v,515 #[cfg(feature = "exp-null-coaelse")]516 None if part.null_coaelse => return Ok(Val::Null),517 None => {518 let suggestions = suggest_object_fields(&v, key.clone().into_flat());519520 return Err(Error::from(NoSuchField(521 key.clone().into_flat(),522 suggestions,523 )))524 .with_description_src(&part.value, || format!("field <{key}> access"));525 }526 },527 (Val::Obj(_), n) => bail!(ValueIndexMustBeTypeGot(528 ValType::Obj,529 ValType::Str,530 n.value_type(),531 )),532 (Val::Arr(v), Val::Num(n)) => {533 let n = n.get();534 if n.fract() > f64::EPSILON {535 bail!(FractionalIndex)536 }537 if n < 0.0 {538 bail!(ArrayBoundsError(n as isize, v.len()));539 }540 v.get(n as usize)?541 .ok_or_else(|| ArrayBoundsError(n as isize, v.len()))?542 }543 (Val::Arr(_), Val::Str(n)) => {544 bail!(AttemptedIndexAnArrayWithString(n.into_flat()))545 }546 (Val::Arr(_), n) => bail!(ValueIndexMustBeTypeGot(547 ValType::Arr,548 ValType::Num,549 n.value_type(),550 )),551552 (Val::Str(s), Val::Num(n)) => Val::Str({553 let v: IStr = s554 .clone()555 .into_flat()556 .chars()557 .skip(n.get() as usize)558 .take(1)559 .collect::<String>()560 .into();561 if v.is_empty() {562 let size = s.into_flat().chars().count();563 bail!(StringBoundsError(n.get() as usize, size))564 }565 StrValue::Flat(v)566 }),567 (Val::Str(_), n) => bail!(ValueIndexMustBeTypeGot(568 ValType::Str,569 ValType::Num,570 n.value_type(),571 )),572 #[cfg(feature = "exp-null-coaelse")]573 (Val::Null, _) if part.null_coaelse => return Ok(Val::Null),574 (v, _) => bail!(CantIndexInto(v.value_type())),575 };576 }577 indexable578 }579 LocalExpr(bindings, returned) => {580 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =581 GcHashMap::with_capacity(bindings.iter().map(BindSpec::capacity_hint).sum());582 let fctx = Context::new_future();583 for b in bindings {584 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;585 }586 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);587 evaluate(ctx, &returned.clone())?588 }589 Arr(items) => {590 if items.is_empty() {591 Val::Arr(ArrValue::empty())592 } else if items.len() == 1 {593 #[derive(Trace)]594 struct ArrayElement {595 ctx: Context,596 item: LocExpr,597 }598 impl ThunkValue for ArrayElement {599 type Output = Val;600 fn get(self: Box<Self>) -> Result<Val> {601 evaluate(self.ctx, &self.item)602 }603 }604 Val::Arr(ArrValue::lazy(vec![Thunk::new(ArrayElement {605 ctx,606 item: items[0].clone(),607 })]))608 } else {609 Val::Arr(ArrValue::expr(ctx, items.iter().cloned()))610 }611 }612 ArrComp(expr, comp_specs) => {613 let mut out = Vec::new();614 evaluate_comp(ctx, comp_specs, &mut |ctx| {615 #[derive(Trace)]616 struct EvaluateThunk {617 ctx: Context,618 expr: LocExpr,619 }620 impl ThunkValue for EvaluateThunk {621 type Output = Val;622 fn get(self: Box<Self>) -> Result<Val> {623 evaluate(self.ctx, &self.expr)624 }625 }626 out.push(Thunk::new(EvaluateThunk {627 ctx,628 expr: expr.clone(),629 }));630 Ok(())631 })?;632 Val::Arr(ArrValue::lazy(out))633 }634 Obj(body) => Val::Obj(evaluate_object(ctx, body)?),635 ObjExtend(a, b) => evaluate_add_op(636 &evaluate(ctx.clone(), a)?,637 &Val::Obj(evaluate_object(ctx, b)?),638 )?,639 Apply(value, args, tailstrict) => {640 evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)?641 }642 Function(params, body) => {643 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())644 }645 AssertExpr(assert, returned) => {646 evaluate_assert(ctx.clone(), assert)?;647 evaluate(ctx, returned)?648 }649 ErrorStmt(e) => in_frame(650 CallLocation::new(&loc),651 || "error statement".to_owned(),652 || bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),653 )?,654 IfElse {655 cond,656 cond_then,657 cond_else,658 } => {659 if in_frame(660 CallLocation::new(&loc),661 || "if condition".to_owned(),662 || bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),663 )? {664 evaluate(ctx, cond_then)?665 } else {666 match cond_else {667 Some(v) => evaluate(ctx, v)?,668 None => Val::Null,669 }670 }671 }672 Slice(value, desc) => {673 fn parse_idx<T: Typed>(674 loc: CallLocation<'_>,675 ctx: &Context,676 expr: Option<&LocExpr>,677 desc: &'static str,678 ) -> Result<Option<T>> {679 if let Some(value) = expr {680 Ok(Some(in_frame(681 loc,682 || format!("slice {desc}"),683 || T::from_untyped(evaluate(ctx.clone(), value)?),684 )?))685 } else {686 Ok(None)687 }688 }689690 let indexable = evaluate(ctx.clone(), value)?;691 let loc = CallLocation::new(&loc);692693 let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;694 let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;695 let step = parse_idx(loc, &ctx, desc.step.as_ref(), "step")?;696697 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?698 }699 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {700 let Expr::Str(path) = &path.expr() else {701 bail!("computed imports are not supported")702 };703 let tmp = loc.clone().0;704 let s = ctx.state();705 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;706 match i {707 Import(_) => in_frame(708 CallLocation::new(&loc),709 || format!("import {:?}", path.clone()),710 || s.import_resolved(resolved_path),711 )?,712 ImportStr(_) => Val::string(s.import_resolved_str(resolved_path)?),713 ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),714 _ => unreachable!(),715 }716 }717 })718}crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,6 +1,5 @@
use std::{
any::Any,
- cell::RefCell,
env::current_dir,
fs,
io::{ErrorKind, Read},
@@ -41,8 +40,10 @@
/// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]
fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;
- /// For downcasts
+ // For downcasts, will be removed after trait_upcasting_coercion
+ // stabilization.
fn as_any(&self) -> &dyn Any;
+ fn as_any_mut(&mut self) -> &mut dyn Any;
}
/// Dummy resolver, can't resolve/load any file
@@ -56,6 +57,9 @@
fn as_any(&self) -> &dyn Any {
self
}
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
@@ -69,17 +73,15 @@
pub struct FileImportResolver {
/// Library directories to search for file.
/// Referred to as `jpath` in original jsonnet implementation.
- library_paths: RefCell<Vec<PathBuf>>,
+ library_paths: Vec<PathBuf>,
}
impl FileImportResolver {
- pub fn new(jpath: Vec<PathBuf>) -> Self {
- Self {
- library_paths: RefCell::new(jpath),
- }
+ pub fn new(library_paths: Vec<PathBuf>) -> Self {
+ Self { library_paths }
}
/// Dynamically add new jpath, used by bindings
- pub fn add_jpath(&self, path: PathBuf) {
- self.library_paths.borrow_mut().push(path);
+ pub fn add_jpath(&mut self, path: PathBuf) {
+ self.library_paths.push(path);
}
}
@@ -132,7 +134,7 @@
if let Some(direct) = check_path(&direct)? {
return Ok(direct);
}
- for library_path in self.library_paths.borrow().iter() {
+ for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if let Some(cloned) = check_path(&cloned)? {
@@ -165,11 +167,15 @@
Ok(out)
}
+ fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ self.resolve_from(&SourcePath::default(), path)
+ }
+
fn as_any(&self) -> &dyn Any {
self
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
- self.resolve_from(&SourcePath::default(), path)
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
}
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,8 +11,8 @@
};
use crate::{
- arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
- Result, State, Val,
+ arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,
+ ObjValueBuilder, Result, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -173,8 +173,7 @@
let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
- // TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("array index [{i}]"),
|| {
let e = element?;
@@ -199,7 +198,7 @@
) {
let mut serde_error = None;
// TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("object field {field:?}"),
|| {
let v = value?;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
@@ -376,38 +376,6 @@
context_initializer.populate(source, &mut builder);
builder.build()
- }
-
- /// Executes code creating a new stack frame
- pub fn push<T>(
- e: CallLocation<'_>,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
-
- /// Executes code creating a new stack frame
- pub fn push_val(
- &self,
- e: &Span,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<Val>,
- ) -> Result<Val> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
- /// Executes code creating a new stack frame
- pub fn push_description<T>(
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description(frame_desc)
}
}
@@ -417,6 +385,26 @@
self.0.file_cache.borrow_mut()
}
}
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_frame<T>(
+ e: CallLocation<'_>,
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
+}
+
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_description_frame<T>(
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description(frame_desc)
+}
#[derive(Trace)]
pub struct InitialUnderscore(pub Thunk<Val>);
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt::Write, ptr};
-use crate::{bail, Result, ResultExt, State, Val};
+use crate::{bail, in_description_frame, Result, ResultExt, Val};
pub trait ManifestFormat {
fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -242,7 +242,7 @@
Minify | ToString => {}
};
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_json_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -304,7 +304,7 @@
escape_string_json_buf(&key, buf);
buf.push_str(options.key_val_sep);
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_json_ex_buf(&value, buf, cur_padding, options),
)?;
@@ -412,7 +412,7 @@
for (i, v) in arr.iter().enumerate() {
let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
out.push_str("---\n");
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| self.inner.manifest_buf(v, out),
)?;
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -17,10 +17,11 @@
error::{suggest_object_fields, Error, ErrorKind::*},
function::{CallLocation, FuncVal},
gc::{GcHashMap, GcHashSet, TraceBox},
+ in_frame,
operator::evaluate_add_op,
tb,
val::{ArrValue, ThunkValue},
- MaybeUnbound, Result, State, Thunk, Unbound, Val,
+ MaybeUnbound, Result, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -969,7 +970,7 @@
let location = member.location.clone();
let old = receiver.0.map.insert(name.clone(), member);
if old.is_some() {
- State::push(
+ in_frame(
CallLocation(location.as_ref()),
|| format!("field <{}> initializtion", name.clone()),
|| bail!(DuplicateFieldName(name.clone())),
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,12 +3,12 @@
use format::{format_arr, format_obj};
-use crate::{function::CallLocation, Result, State, Val};
+use crate::{function::CallLocation, in_frame, Result, Val};
pub mod format;
pub fn std_format(str: &str, vals: Val) -> Result<String> {
- State::push(
+ in_frame(
CallLocation::native(),
|| format!("std.format of {str}"),
|| {
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -3,12 +3,12 @@
use crate::{
function::{ArgsLike, CallLocation},
- Result, State, Val,
+ in_description_frame, Result, State, Val,
};
pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
- State::push_description(
+ in_description_frame(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -8,7 +8,7 @@
use crate::{
error::{Error, ErrorKind, Result},
- State, Val,
+ in_description_frame, Val,
};
#[derive(Debug, Error, Clone, Trace)]
@@ -89,7 +89,7 @@
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
) -> Result<()> {
- State::push_description(error_reason, || match item() {
+ in_description_frame(error_reason, || match item() {
Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -235,6 +235,7 @@
use crate::{PoolMap, POOL};
+ /// Type-erased interned string pool
pub enum PoolState {}
/// Dump current interned string pool, to be restored by
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -290,7 +290,7 @@
cfg_attrs,
} => {
let name = name.as_ref().map_or("<unnamed>", String::as_str);
- let eval = quote! {jrsonnet_evaluator::State::push_description(
+ let eval = quote! {jrsonnet_evaluator::in_description_frame(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate()?),
)?};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,10 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
val::ArrValue,
- IStr, ObjValue, Result, ResultExt, State, Val,
+ IStr, ObjValue, Result, ResultExt, Val,
};
pub struct TomlFormat<'s> {
@@ -124,7 +124,7 @@
buf.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_value(&e, true, buf, "", options),
)?;
@@ -161,7 +161,7 @@
escape_key_toml_buf(&k, buf);
buf.push_str(" = ");
- State::push_description(
+ in_description_frame(
|| format!("field <{k}> manifestification"),
|| manifest_value(&v, true, buf, "", options),
)?;
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,9 +1,9 @@
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{ManifestFormat, ToStringFormat},
typed::{ComplexValType, Either2, Typed, ValType},
val::ArrValue,
- Either, ObjValue, Result, ResultExt, State, Val,
+ Either, ObjValue, Result, ResultExt, Val,
};
pub struct XmlJsonmlFormat {
@@ -70,7 +70,7 @@
Ok(Self::Tag {
tag,
attrs,
- children: State::push_description(
+ children: in_description_frame(
|| "parsing children".to_owned(),
|| {
Typed::from_untyped(Val::Arr(arr.slice(
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -1,9 +1,9 @@
use std::{borrow::Cow, fmt::Write};
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
- Result, ResultExt, State, Val,
+ Result, ResultExt, Val,
};
pub struct YamlFormat<'s> {
@@ -178,7 +178,7 @@
if extra_padding {
cur_padding.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_yaml_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -225,7 +225,7 @@
}
_ => buf.push(' '),
}
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_yaml_ex_buf(&value, buf, cur_padding, options),
)?;