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(s: State, 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(s.clone(), ctx, expr)?;42 if matches!(value, Val::Null) {43 Ok(None)44 } else {45 Ok(Some(IStr::from_untyped(value, s.clone())?))46 }47 },48 )?,49 })50}5152pub fn evaluate_comp(53 s: State,54 ctx: Context,55 specs: &[CompSpec],56 callback: &mut impl FnMut(Context) -> Result<()>,57) -> Result<()> {58 match specs.get(0) {59 None => callback(ctx)?,60 Some(CompSpec::IfSpec(IfSpecData(cond))) => {61 if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {62 evaluate_comp(s, ctx, &specs[1..], callback)?;63 }64 }65 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {66 match evaluate(s.clone(), ctx.clone(), expr)? {67 Val::Arr(list) => {68 for item in list.iter(s.clone()) {69 evaluate_comp(70 s.clone(),71 ctx.clone().with_var(var.clone(), item?.clone()),72 &specs[1..],73 callback,74 )?;75 }76 }77 _ => throw!(InComprehensionCanOnlyIterateOverArray),78 }79 }80 }81 Ok(())82}8384trait CloneableUnbound<T>: Unbound<Bound = T> + Clone {}8586fn evaluate_object_locals(87 fctx: Pending<Context>,88 locals: Rc<Vec<BindSpec>>,89) -> impl CloneableUnbound<Context> {90 #[derive(Trace, Clone)]91 struct UnboundLocals {92 fctx: Pending<Context>,93 locals: Rc<Vec<BindSpec>>,94 }95 impl CloneableUnbound<Context> for UnboundLocals {}96 impl Unbound for UnboundLocals {97 type Bound = Context;9899 fn bind(100 &self,101 _s: State,102 sup: Option<ObjValue>,103 this: Option<ObjValue>,104 ) -> Result<Context> {105 let fctx = Context::new_future();106 let mut new_bindings = GcHashMap::new();107 for b in self.locals.iter() {108 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;109 }110111 let ctx = self.fctx.unwrap();112 let new_dollar = ctx.dollar().clone().or_else(|| this.clone());113114 let ctx = ctx115 .extend(new_bindings, new_dollar, sup, this)116 .into_future(fctx);117118 Ok(ctx)119 }120 }121122 UnboundLocals { fctx, locals }123}124125#[allow(clippy::too_many_lines)]126pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {127 let mut builder = ObjValueBuilder::new();128 let locals = Rc::new(129 members130 .iter()131 .filter_map(|m| match m {132 Member::BindStmt(bind) => Some(bind.clone()),133 _ => None,134 })135 .collect::<Vec<_>>(),136 );137138 let fctx = Context::new_future();139140 141 let uctx = CachedUnbound::new(evaluate_object_locals(fctx.clone(), locals));142143 for member in members.iter() {144 match member {145 Member::Field(FieldMember {146 name,147 plus,148 params: None,149 visibility,150 value,151 }) => {152 #[derive(Trace)]153 struct UnboundValue<B: Trace> {154 uctx: B,155 value: LocExpr,156 name: IStr,157 }158 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {159 type Bound = Thunk<Val>;160 fn bind(161 &self,162 s: State,163 sup: Option<ObjValue>,164 this: Option<ObjValue>,165 ) -> Result<Thunk<Val>> {166 Ok(Thunk::evaluated(evaluate_named(167 s.clone(),168 self.uctx.bind(s, sup, this)?,169 &self.value,170 self.name.clone(),171 )?))172 }173 }174175 let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;176 let name = if let Some(name) = name {177 name178 } else {179 continue;180 };181182 builder183 .member(name.clone())184 .with_add(*plus)185 .with_visibility(*visibility)186 .with_location(value.1.clone())187 .bindable(tb!(UnboundValue {188 uctx: uctx.clone(),189 value: value.clone(),190 name: name.clone()191 }))?;192 }193 Member::Field(FieldMember {194 name,195 params: Some(params),196 value,197 ..198 }) => {199 #[derive(Trace)]200 struct UnboundMethod<B: Trace> {201 uctx: B,202 value: LocExpr,203 params: ParamsDesc,204 name: IStr,205 }206 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {207 type Bound = Thunk<Val>;208 fn bind(209 &self,210 s: State,211 sup: Option<ObjValue>,212 this: Option<ObjValue>,213 ) -> Result<Thunk<Val>> {214 Ok(Thunk::evaluated(evaluate_method(215 self.uctx.bind(s, sup, this)?,216 self.name.clone(),217 self.params.clone(),218 self.value.clone(),219 )))220 }221 }222223 let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {224 name225 } else {226 continue;227 };228229 builder230 .member(name.clone())231 .hide()232 .with_location(value.1.clone())233 .bindable(tb!(UnboundMethod {234 uctx: uctx.clone(),235 value: value.clone(),236 params: params.clone(),237 name: name.clone()238 }))?;239 }240 Member::BindStmt(_) => {}241 Member::AssertStmt(stmt) => {242 #[derive(Trace)]243 struct ObjectAssert<B: Trace> {244 uctx: B,245 assert: AssertStmt,246 }247 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {248 fn run(249 &self,250 s: State,251 sup: Option<ObjValue>,252 this: Option<ObjValue>,253 ) -> Result<()> {254 let ctx = self.uctx.bind(s.clone(), sup, this)?;255 evaluate_assert(s, ctx, &self.assert)256 }257 }258 builder.assert(tb!(ObjectAssert {259 uctx: uctx.clone(),260 assert: stmt.clone(),261 }));262 }263 }264 }265 let this = builder.build();266 fctx.fill(ctx.extend(GcHashMap::new(), None, None, Some(this.clone())));267 Ok(this)268}269270pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {271 Ok(match object {272 ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,273 ObjBody::ObjComp(obj) => {274 let mut builder = ObjValueBuilder::new();275 let locals = Rc::new(276 obj.pre_locals277 .iter()278 .chain(obj.post_locals.iter())279 .cloned()280 .collect::<Vec<_>>(),281 );282 let mut ctxs = vec![];283 evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {284 let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;285 let fctx = Context::new_future();286 ctxs.push((ctx, fctx.clone()));287 let uctx = evaluate_object_locals(fctx, locals.clone());288289 match key {290 Val::Null => {}291 Val::Str(n) => {292 #[derive(Trace)]293 struct UnboundValue<B: Trace> {294 uctx: B,295 value: LocExpr,296 }297 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {298 type Bound = Thunk<Val>;299 fn bind(300 &self,301 s: State,302 sup: Option<ObjValue>,303 this: Option<ObjValue>,304 ) -> Result<Thunk<Val>> {305 Ok(Thunk::evaluated(evaluate(306 s.clone(),307 self.uctx.bind(s, sup, this.clone())?.extend(308 GcHashMap::new(),309 None,310 None,311 this,312 ),313 &self.value,314 )?))315 }316 }317 builder318 .member(n)319 .with_location(obj.value.1.clone())320 .with_add(obj.plus)321 .bindable(tb!(UnboundValue {322 uctx,323 value: obj.value.clone(),324 }))?;325 }326 v => throw!(FieldMustBeStringGot(v.value_type())),327 }328329 Ok(())330 })?;331332 let this = builder.build();333 for (ctx, fctx) in ctxs {334 let _ctx = ctx335 .extend(GcHashMap::new(), None, None, Some(this.clone()))336 .into_future(fctx);337 }338 this339 }340 })341}342343pub fn evaluate_apply(344 s: State,345 ctx: Context,346 value: &LocExpr,347 args: &ArgsDesc,348 loc: CallLocation<'_>,349 tailstrict: bool,350) -> Result<Val> {351 let value = evaluate(s.clone(), ctx.clone(), value)?;352 Ok(match value {353 Val::Func(f) => {354 let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);355 if tailstrict {356 body()?357 } else {358 State::push(loc, || format!("function <{}> call", f.name()), body)?359 }360 }361 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),362 })363}364365pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {366 let value = &assertion.0;367 let msg = &assertion.1;368 let assertion_result = State::push(369 CallLocation::new(&value.1),370 || "assertion condition".to_owned(),371 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),372 )?;373 if !assertion_result {374 State::push(375 CallLocation::new(&value.1),376 || "assertion failure".to_owned(),377 || {378 if let Some(msg) = msg {379 throw!(AssertionFailed(380 evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?381 ));382 }383 throw!(AssertionFailed(Val::Null.to_string(s.clone())?));384 },385 )?;386 }387 Ok(())388}389390pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {391 use Expr::*;392 let LocExpr(raw_expr, _loc) = expr;393 Ok(match &**raw_expr {394 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),395 _ => evaluate(s, ctx, expr)?,396 })397}398399#[allow(clippy::too_many_lines)]400pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {401 use Expr::*;402 let LocExpr(expr, loc) = expr;403 404 Ok(match &**expr {405 Literal(LiteralType::This) => {406 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)407 }408 Literal(LiteralType::Super) => Val::Obj(409 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(410 ctx.this()411 .clone()412 .expect("if super exists - then this should to"),413 ),414 ),415 Literal(LiteralType::Dollar) => {416 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)417 }418 Literal(LiteralType::True) => Val::Bool(true),419 Literal(LiteralType::False) => Val::Bool(false),420 Literal(LiteralType::Null) => Val::Null,421 Parened(e) => evaluate(s, ctx, e)?,422 Str(v) => Val::Str(v.clone()),423 Num(v) => Val::new_checked_num(*v)?,424 BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,425 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,426 Var(name) => State::push(427 CallLocation::new(loc),428 || format!("variable <{name}> access"),429 || ctx.binding(name.clone())?.evaluate(s.clone()),430 )?,431 Index(value, index) => {432 match (433 evaluate(s.clone(), ctx.clone(), value)?,434 evaluate(s.clone(), ctx, index)?,435 ) {436 (Val::Obj(v), Val::Str(key)) => State::push(437 CallLocation::new(loc),438 || format!("field <{key}> access"),439 || match v.get(s.clone(), key.clone()) {440 Ok(Some(v)) => Ok(v),441 #[cfg(not(feature = "friendly-errors"))]442 Ok(None) => throw!(NoSuchField(key.clone(), vec![])),443 #[cfg(feature = "friendly-errors")]444 Ok(None) => {445 let mut heap = Vec::new();446 for field in v.fields_ex(447 true,448 #[cfg(feature = "exp-preserve-order")]449 false,450 ) {451 let conf = strsim::jaro_winkler(&field as &str, &key as &str);452 if conf < 0.8 {453 continue;454 }455 heap.push((conf, field));456 }457 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));458459 throw!(NoSuchField(460 key.clone(),461 heap.into_iter().map(|(_, v)| v).collect()462 ))463 }464 Err(e) => Err(e),465 },466 )?,467 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(468 ValType::Obj,469 ValType::Str,470 n.value_type(),471 )),472473 (Val::Arr(v), Val::Num(n)) => {474 if n.fract() > f64::EPSILON {475 throw!(FractionalIndex)476 }477 v.get(s, n as usize)?478 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?479 }480 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),481 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(482 ValType::Arr,483 ValType::Num,484 n.value_type(),485 )),486487 (Val::Str(s), Val::Num(n)) => Val::Str({488 let v: IStr = s489 .chars()490 .skip(n as usize)491 .take(1)492 .collect::<String>()493 .into();494 if v.is_empty() {495 let size = s.chars().count();496 throw!(StringBoundsError(n as usize, size))497 }498 v499 }),500 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(501 ValType::Str,502 ValType::Num,503 n.value_type(),504 )),505506 (v, _) => throw!(CantIndexInto(v.value_type())),507 }508 }509 LocalExpr(bindings, returned) => {510 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =511 GcHashMap::with_capacity(bindings.len());512 let fctx = Context::new_future();513 for b in bindings {514 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;515 }516 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);517 evaluate(s, ctx, &returned.clone())?518 }519 Arr(items) => {520 let mut out = Vec::with_capacity(items.len());521 for item in items {522 523 #[derive(Trace)]524 struct ArrayElement {525 ctx: Context,526 item: LocExpr,527 }528 impl ThunkValue for ArrayElement {529 type Output = Val;530 fn get(self: Box<Self>, s: State) -> Result<Val> {531 evaluate(s, self.ctx, &self.item)532 }533 }534 out.push(Thunk::new(tb!(ArrayElement {535 ctx: ctx.clone(),536 item: item.clone(),537 })));538 }539 Val::Arr(out.into())540 }541 ArrComp(expr, comp_specs) => {542 let mut out = Vec::new();543 evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {544 out.push(evaluate(s.clone(), ctx, expr)?);545 Ok(())546 })?;547 Val::Arr(ArrValue::Eager(Cc::new(out)))548 }549 Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),550 ObjExtend(a, b) => evaluate_add_op(551 s.clone(),552 &evaluate(s.clone(), ctx.clone(), a)?,553 &Val::Obj(evaluate_object(s, ctx, b)?),554 )?,555 Apply(value, args, tailstrict) => {556 evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?557 }558 Function(params, body) => {559 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())560 }561 AssertExpr(assert, returned) => {562 evaluate_assert(s.clone(), ctx.clone(), assert)?;563 evaluate(s, ctx, returned)?564 }565 ErrorStmt(e) => State::push(566 CallLocation::new(loc),567 || "error statement".to_owned(),568 || {569 throw!(RuntimeError(570 evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,571 ))572 },573 )?,574 IfElse {575 cond,576 cond_then,577 cond_else,578 } => {579 if State::push(580 CallLocation::new(loc),581 || "if condition".to_owned(),582 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),583 )? {584 evaluate(s, ctx, cond_then)?585 } else {586 match cond_else {587 Some(v) => evaluate(s, ctx, v)?,588 None => Val::Null,589 }590 }591 }592 Slice(value, desc) => {593 fn parse_idx<T: Typed>(594 loc: CallLocation<'_>,595 s: State,596 ctx: &Context,597 expr: &Option<LocExpr>,598 desc: &'static str,599 ) -> Result<Option<T>> {600 if let Some(value) = expr {601 Ok(Some(State::push(602 loc,603 || format!("slice {desc}"),604 || T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),605 )?))606 } else {607 Ok(None)608 }609 }610611 let indexable = evaluate(s.clone(), ctx.clone(), value)?;612 let loc = CallLocation::new(loc);613614 let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;615 let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;616 let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;617618 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?619 }620 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {621 let tmp = loc.clone().0;622 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;623 match i {624 Import(_) => State::push(625 CallLocation::new(loc),626 || format!("import {:?}", path.clone()),627 || s.import_resolved(resolved_path),628 )?,629 ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),630 ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),631 _ => unreachable!(),632 }633 }634 })635}