difftreelog
style rename bindable -> unbound
in: master
4 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use std::rc::Rc;23use gcmodule::{Cc, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{6 ArgsDesc, AssertStmt, BindSpec, CompSpec, Expr, FieldMember, ForSpecData, IfSpecData,7 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 stdlib::{std_slice, BUILTINS},17 tb, throw,18 typed::Typed,19 val::{ArrValue, CachedBindable, Thunk, ThunkValue},20 Bindable, Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,21 State, Val,22};23pub mod destructure;24pub mod operator;2526pub fn evaluate_method(ctx: Context, name: IStr, params: ParamsDesc, body: LocExpr) -> Val {27 Val::Func(FuncVal::Normal(Cc::new(FuncDesc {28 name,29 ctx,30 params,31 body,32 })))33}3435pub fn evaluate_field_name(36 s: State,37 ctx: Context,38 field_name: &jrsonnet_parser::FieldName,39) -> Result<Option<IStr>> {40 Ok(match field_name {41 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),42 jrsonnet_parser::FieldName::Dyn(expr) => s.push(43 CallLocation::new(&expr.1),44 || "evaluating field name".to_string(),45 || {46 let value = evaluate(s.clone(), ctx, expr)?;47 if matches!(value, Val::Null) {48 Ok(None)49 } else {50 Ok(Some(IStr::from_untyped(value, s.clone())?))51 }52 },53 )?,54 })55}5657pub fn evaluate_comp(58 s: State,59 ctx: Context,60 specs: &[CompSpec],61 callback: &mut impl FnMut(Context) -> Result<()>,62) -> Result<()> {63 match specs.get(0) {64 None => callback(ctx)?,65 Some(CompSpec::IfSpec(IfSpecData(cond))) => {66 if bool::from_untyped(evaluate(s.clone(), ctx.clone(), cond)?, s.clone())? {67 evaluate_comp(s, ctx, &specs[1..], callback)?;68 }69 }70 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {71 match evaluate(s.clone(), ctx.clone(), expr)? {72 Val::Arr(list) => {73 for item in list.iter(s.clone()) {74 evaluate_comp(75 s.clone(),76 ctx.clone().with_var(var.clone(), item?.clone()),77 &specs[1..],78 callback,79 )?;80 }81 }82 _ => throw!(InComprehensionCanOnlyIterateOverArray),83 }84 }85 }86 Ok(())87}8889trait CloneableBindable<T>: Bindable<Bound = T> + Clone {}9091fn evaluate_object_locals(92 fctx: Pending<Context>,93 locals: Rc<Vec<BindSpec>>,94) -> impl CloneableBindable<Context> {95 #[derive(Trace, Clone)]96 struct WithObjectLocals {97 fctx: Pending<Context>,98 locals: Rc<Vec<BindSpec>>,99 }100 impl CloneableBindable<Context> for WithObjectLocals {}101 impl Bindable for WithObjectLocals {102 type Bound = Context;103104 fn bind(105 &self,106 _s: State,107 sup: Option<ObjValue>,108 this: Option<ObjValue>,109 ) -> Result<Context> {110 let fctx = Context::new_future();111 let mut new_bindings = GcHashMap::new();112 for b in self.locals.iter() {113 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;114 }115116 let ctx = self.fctx.unwrap();117 let new_dollar = ctx.dollar().clone().or_else(|| this.clone());118119 let ctx = ctx120 .extend(new_bindings, new_dollar, sup, this)121 .into_future(fctx);122123 Ok(ctx)124 }125 }126127 WithObjectLocals { fctx, locals }128}129130#[allow(clippy::too_many_lines)]131pub fn evaluate_member_list_object(s: State, ctx: Context, members: &[Member]) -> Result<ObjValue> {132 let mut builder = ObjValueBuilder::new();133 let locals = Rc::new(134 members135 .iter()136 .filter_map(|m| match m {137 Member::BindStmt(bind) => Some(bind.clone()),138 _ => None,139 })140 .collect::<Vec<_>>(),141 );142143 let fctx = Context::new_future();144145 // We have single context for all fields, so we can cache binds146 let uctx = CachedBindable::new(evaluate_object_locals(fctx.clone(), locals));147148 for member in members.iter() {149 match member {150 Member::Field(FieldMember {151 name,152 plus,153 params: None,154 visibility,155 value,156 }) => {157 #[derive(Trace)]158 struct ObjMemberBinding<B> {159 uctx: B,160 value: LocExpr,161 name: IStr,162 }163 impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {164 type Bound = Thunk<Val>;165 fn bind(166 &self,167 s: State,168 sup: Option<ObjValue>,169 this: Option<ObjValue>,170 ) -> Result<Thunk<Val>> {171 Ok(Thunk::evaluated(evaluate_named(172 s.clone(),173 self.uctx.bind(s, sup, this)?,174 &self.value,175 self.name.clone(),176 )?))177 }178 }179180 let name = evaluate_field_name(s.clone(), ctx.clone(), name)?;181 let name = if let Some(name) = name {182 name183 } else {184 continue;185 };186187 builder188 .member(name.clone())189 .with_add(*plus)190 .with_visibility(*visibility)191 .with_location(value.1.clone())192 .bindable(193 s.clone(),194 tb!(ObjMemberBinding {195 uctx: uctx.clone(),196 value: value.clone(),197 name: name.clone()198 }),199 )?;200 }201 Member::Field(FieldMember {202 name,203 params: Some(params),204 value,205 ..206 }) => {207 #[derive(Trace)]208 struct ObjMemberBinding<B> {209 uctx: B,210 value: LocExpr,211 params: ParamsDesc,212 name: IStr,213 }214 impl<B: Bindable<Bound = Context>> Bindable for ObjMemberBinding<B> {215 type Bound = Thunk<Val>;216 fn bind(217 &self,218 s: State,219 sup: Option<ObjValue>,220 this: Option<ObjValue>,221 ) -> Result<Thunk<Val>> {222 Ok(Thunk::evaluated(evaluate_method(223 self.uctx.bind(s, sup, this)?,224 self.name.clone(),225 self.params.clone(),226 self.value.clone(),227 )))228 }229 }230231 let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {232 name233 } else {234 continue;235 };236237 builder238 .member(name.clone())239 .hide()240 .with_location(value.1.clone())241 .bindable(242 s.clone(),243 tb!(ObjMemberBinding {244 uctx: uctx.clone(),245 value: value.clone(),246 params: params.clone(),247 name: name.clone()248 }),249 )?;250 }251 Member::BindStmt(_) => {}252 Member::AssertStmt(stmt) => {253 #[derive(Trace)]254 struct ObjectAssert<B> {255 uctx: B,256 assert: AssertStmt,257 }258 impl<B: Bindable<Bound = Context>> ObjectAssertion for ObjectAssert<B> {259 fn run(260 &self,261 s: State,262 sup: Option<ObjValue>,263 this: Option<ObjValue>,264 ) -> Result<()> {265 let ctx = self.uctx.bind(s.clone(), sup, this)?;266 evaluate_assert(s, ctx, &self.assert)267 }268 }269 builder.assert(tb!(ObjectAssert {270 uctx: uctx.clone(),271 assert: stmt.clone(),272 }));273 }274 }275 }276 let this = builder.build();277 let _ctx = ctx278 .extend(GcHashMap::new(), None, None, Some(this.clone()))279 .into_future(fctx);280 Ok(this)281}282283pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {284 Ok(match object {285 ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,286 ObjBody::ObjComp(obj) => {287 let mut builder = ObjValueBuilder::new();288 let locals = Rc::new(289 obj.pre_locals290 .iter()291 .chain(obj.post_locals.iter())292 .cloned()293 .collect::<Vec<_>>(),294 );295 let mut ctxs = vec![];296 evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {297 let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;298 let fctx = Context::new_future();299 ctxs.push((ctx, fctx.clone()));300 let uctx = evaluate_object_locals(fctx, locals.clone());301302 match key {303 Val::Null => {}304 Val::Str(n) => {305 #[derive(Trace)]306 struct ObjCompBinding<B> {307 uctx: B,308 value: LocExpr,309 }310 impl<B: Bindable<Bound = Context>> Bindable for ObjCompBinding<B> {311 type Bound = Thunk<Val>;312 fn bind(313 &self,314 s: State,315 sup: Option<ObjValue>,316 this: Option<ObjValue>,317 ) -> Result<Thunk<Val>> {318 Ok(Thunk::evaluated(evaluate(319 s.clone(),320 self.uctx.bind(s, sup, this.clone())?.extend(321 GcHashMap::new(),322 None,323 None,324 this,325 ),326 &self.value,327 )?))328 }329 }330 builder331 .member(n)332 .with_location(obj.value.1.clone())333 .with_add(obj.plus)334 .bindable(335 s.clone(),336 tb!(ObjCompBinding {337 uctx,338 value: obj.value.clone(),339 }),340 )?;341 }342 v => throw!(FieldMustBeStringGot(v.value_type())),343 }344345 Ok(())346 })?;347348 let this = builder.build();349 for (ctx, fctx) in ctxs {350 let _ctx = ctx351 .extend(GcHashMap::new(), None, None, Some(this.clone()))352 .into_future(fctx);353 }354 this355 }356 })357}358359pub fn evaluate_apply(360 s: State,361 ctx: Context,362 value: &LocExpr,363 args: &ArgsDesc,364 loc: CallLocation,365 tailstrict: bool,366) -> Result<Val> {367 let value = evaluate(s.clone(), ctx.clone(), value)?;368 Ok(match value {369 Val::Func(f) => {370 let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);371 if tailstrict {372 body()?373 } else {374 s.push(loc, || format!("function <{}> call", f.name()), body)?375 }376 }377 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),378 })379}380381pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {382 let value = &assertion.0;383 let msg = &assertion.1;384 let assertion_result = s.push(385 CallLocation::new(&value.1),386 || "assertion condition".to_owned(),387 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),388 )?;389 if !assertion_result {390 s.push(391 CallLocation::new(&value.1),392 || "assertion failure".to_owned(),393 || {394 if let Some(msg) = msg {395 throw!(AssertionFailed(396 evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?397 ));398 }399 throw!(AssertionFailed(Val::Null.to_string(s.clone())?));400 },401 )?;402 }403 Ok(())404}405406pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {407 use Expr::*;408 let LocExpr(raw_expr, _loc) = expr;409 Ok(match &**raw_expr {410 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),411 _ => evaluate(s, ctx, expr)?,412 })413}414415#[allow(clippy::too_many_lines)]416pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {417 use Expr::*;418 let LocExpr(expr, loc) = expr;419 // let bp = with_state(|s| s.0.stop_at.borrow().clone());420 Ok(match &**expr {421 Literal(LiteralType::This) => {422 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)423 }424 Literal(LiteralType::Super) => Val::Obj(425 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(426 ctx.this()427 .clone()428 .expect("if super exists - then this should to"),429 ),430 ),431 Literal(LiteralType::Dollar) => {432 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)433 }434 Literal(LiteralType::True) => Val::Bool(true),435 Literal(LiteralType::False) => Val::Bool(false),436 Literal(LiteralType::Null) => Val::Null,437 Parened(e) => evaluate(s, ctx, e)?,438 Str(v) => Val::Str(v.clone()),439 Num(v) => Val::new_checked_num(*v)?,440 BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,442 Var(name) => s.push(443 CallLocation::new(loc),444 || format!("variable <{}> access", name),445 || ctx.binding(name.clone())?.evaluate(s.clone()),446 )?,447 Index(value, index) => {448 match (449 evaluate(s.clone(), ctx.clone(), value)?,450 evaluate(s.clone(), ctx, index)?,451 ) {452 (Val::Obj(v), Val::Str(key)) => s.push(453 CallLocation::new(loc),454 || format!("field <{}> access", key),455 || match v.get(s.clone(), key.clone()) {456 Ok(Some(v)) => Ok(v),457 Ok(None) => throw!(NoSuchField(key.clone())),458 Err(e) if matches!(e.error(), MagicThisFileUsed) => {459 Ok(Val::Str(loc.0.to_string_lossy().into()))460 }461 Err(e) => Err(e),462 },463 )?,464 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(465 ValType::Obj,466 ValType::Str,467 n.value_type(),468 )),469470 (Val::Arr(v), Val::Num(n)) => {471 if n.fract() > f64::EPSILON {472 throw!(FractionalIndex)473 }474 v.get(s, n as usize)?475 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?476 }477 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),478 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(479 ValType::Arr,480 ValType::Num,481 n.value_type(),482 )),483484 (Val::Str(s), Val::Num(n)) => Val::Str({485 let v: IStr = s486 .chars()487 .skip(n as usize)488 .take(1)489 .collect::<String>()490 .into();491 if v.is_empty() {492 let size = s.chars().count();493 throw!(StringBoundsError(n as usize, size))494 }495 v496 }),497 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(498 ValType::Str,499 ValType::Num,500 n.value_type(),501 )),502503 (v, _) => throw!(CantIndexInto(v.value_type())),504 }505 }506 LocalExpr(bindings, returned) => {507 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =508 GcHashMap::with_capacity(bindings.len());509 let fctx = Context::new_future();510 for b in bindings {511 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;512 }513 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);514 evaluate(s, ctx, &returned.clone())?515 }516 Arr(items) => {517 let mut out = Vec::with_capacity(items.len());518 for item in items {519 // TODO: Implement ArrValue::Lazy with same context for every element?520 #[derive(Trace)]521 struct ArrayElement {522 ctx: Context,523 item: LocExpr,524 }525 impl ThunkValue for ArrayElement {526 type Output = Val;527 fn get(self: Box<Self>, s: State) -> Result<Val> {528 evaluate(s, self.ctx, &self.item)529 }530 }531 out.push(Thunk::new(tb!(ArrayElement {532 ctx: ctx.clone(),533 item: item.clone(),534 })));535 }536 Val::Arr(out.into())537 }538 ArrComp(expr, comp_specs) => {539 let mut out = Vec::new();540 evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {541 out.push(evaluate(s.clone(), ctx, expr)?);542 Ok(())543 })?;544 Val::Arr(ArrValue::Eager(Cc::new(out)))545 }546 Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),547 ObjExtend(a, b) => evaluate_add_op(548 s.clone(),549 &evaluate(s.clone(), ctx.clone(), a)?,550 &Val::Obj(evaluate_object(s, ctx, b)?),551 )?,552 Apply(value, args, tailstrict) => {553 evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?554 }555 Function(params, body) => {556 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())557 }558 Intrinsic(name) => Val::Func(FuncVal::StaticBuiltin(559 BUILTINS560 .with(|b| b.get(name).copied())561 .ok_or_else(|| IntrinsicNotFound(name.clone()))?,562 )),563 IntrinsicThisFile => return Err(MagicThisFileUsed.into()),564 IntrinsicId => Val::Func(FuncVal::identity()),565 AssertExpr(assert, returned) => {566 evaluate_assert(s.clone(), ctx.clone(), assert)?;567 evaluate(s, ctx, returned)?568 }569 ErrorStmt(e) => s.push(570 CallLocation::new(loc),571 || "error statement".to_owned(),572 || {573 throw!(RuntimeError(574 evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,575 ))576 },577 )?,578 IfElse {579 cond,580 cond_then,581 cond_else,582 } => {583 if s.push(584 CallLocation::new(loc),585 || "if condition".to_owned(),586 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),587 )? {588 evaluate(s, ctx, cond_then)?589 } else {590 match cond_else {591 Some(v) => evaluate(s, ctx, v)?,592 None => Val::Null,593 }594 }595 }596 Slice(value, desc) => {597 fn parse_idx<T: Typed>(598 loc: CallLocation,599 s: State,600 ctx: &Context,601 expr: &Option<LocExpr>,602 desc: &'static str,603 ) -> Result<Option<T>> {604 if let Some(value) = expr {605 Ok(Some(s.push(606 loc,607 || format!("slice {}", desc),608 || T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),609 )?))610 } else {611 Ok(None)612 }613 }614615 let indexable = evaluate(s.clone(), ctx.clone(), value)?;616 let loc = CallLocation::new(loc);617618 let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;619 let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;620 let step = parse_idx(loc, s, &ctx, &desc.step, "step")?;621622 std_slice(indexable.into_indexable()?, start, end, step)?623 }624 Import(path) => {625 let tmp = loc.clone().0;626 let mut import_location = tmp.to_path_buf();627 import_location.pop();628 s.push(629 CallLocation::new(loc),630 || format!("import {:?}", path),631 || s.import_file(&import_location, path),632 )?633 }634 ImportStr(path) => {635 let tmp = loc.clone().0;636 let mut import_location = tmp.to_path_buf();637 import_location.pop();638 Val::Str(s.import_file_str(&import_location, path)?)639 }640 ImportBin(path) => {641 let tmp = loc.clone().0;642 let mut import_location = tmp.to_path_buf();643 import_location.pop();644 let bytes = s.import_file_bin(&import_location, path)?;645 Val::Arr(ArrValue::Bytes(bytes))646 }647 })648}crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -60,14 +60,14 @@
use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
pub use val::{ManifestFormat, Thunk, Val};
-pub trait Bindable: Trace + 'static {
+pub trait Unbound: Trace {
type Bound;
fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
}
#[derive(Clone, Trace)]
pub enum LazyBinding {
- Bindable(Cc<TraceBox<dyn Bindable<Bound = Thunk<Val>>>>),
+ Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
Bound(Thunk<Val>),
}
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -16,7 +16,7 @@
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
- throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, Result, State, Thunk, Val,
+ throw, weak_ptr_eq, weak_raw, LazyBinding, Result, State, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -589,7 +589,7 @@
pub fn bindable(
self,
s: State,
- bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>,
+ bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
) -> Result<()> {
self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
}
@@ -613,7 +613,7 @@
pub fn value(self, value: Val) {
self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
}
- pub fn bindable(self, bindable: TraceBox<dyn Bindable<Bound = Thunk<Val>>>) {
+ pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
self.binding(LazyBinding::Bindable(Cc::new(bindable)));
}
pub fn binding(self, binding: LazyBinding) {
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -12,7 +12,7 @@
stdlib::manifest::{
manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,
},
- throw, Bindable, ObjValue, Result, State, WeakObjValue,
+ throw, ObjValue, Result, State, Unbound, WeakObjValue,
};
pub trait ThunkValue: Trace {
@@ -74,14 +74,14 @@
type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);
#[derive(Trace, Clone)]
-pub struct CachedBindable<I, T>
+pub struct CachedUnbound<I, T>
where
- I: Bindable<Bound = T>,
+ I: Unbound<Bound = T>,
{
cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,
value: I,
}
-impl<I: Bindable<Bound = T>, T: Trace> CachedBindable<I, T> {
+impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {
pub fn new(value: I) -> Self {
Self {
cache: Cc::new(RefCell::new(GcHashMap::new())),
@@ -89,7 +89,7 @@
}
}
}
-impl<I: Bindable<Bound = T>, T: Clone + Trace> Bindable for CachedBindable<I, T> {
+impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {
type Bound = T;
fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {
let cache_key = (