difftreelog
feat grow os stack on demand
in: master
3 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -486,6 +486,7 @@
"pathdiff",
"rustc-hash",
"serde",
+ "stacker",
"static_assertions",
"strsim",
"thiserror",
@@ -851,6 +852,15 @@
]
[[package]]
+name = "psm"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5787f7cda34e3033a72192c018bc5883100330f362ef279a8cbccfce8bb4e874"
+dependencies = [
+ "cc",
+]
+
+[[package]]
name = "quote"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1077,6 +1087,19 @@
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
+name = "stacker"
+version = "0.1.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c886bd4480155fd3ef527d45e9ac8dd7118a898a46530b7b94c3e21866259fce"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "libc",
+ "psm",
+ "winapi",
+]
+
+[[package]]
name = "static_assertions"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -1203,6 +1226,28 @@
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -60,3 +60,4 @@
# Bigint
num-bigint = { workspace = true, features = ["serde"], optional = true }
derivative.workspace = true
+stacker = "0.1.15"
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 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}