difftreelog
docs cleanup evaluator's docs
in: master
7 files changed
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -2,7 +2,7 @@
use std::{path::PathBuf, rc::Rc};
thread_local! {
- /// To avoid parsing again when issued from same thread
+ /// To avoid parsing again when issued from the same thread
#[allow(unreachable_code)]
static PARSED_STDLIB: LocExpr = {
#[cfg(feature = "codegenerated-stdlib")]
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth1use crate::{2 context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,3 ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4 ValType,5};6use closure::closure;7use jrsonnet_parser::{8 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,11};12use rustc_hash::FxHashMap;13use std::{collections::HashMap, rc::Rc};1415pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {16 let b = b.clone();17 if let Some(params) = &b.params {18 let params = params.clone();19 (20 b.name.clone(),21 LazyBinding::Bindable(Rc::new(move |this, super_obj| {22 Ok(lazy_val!(23 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(24 context_creator.0(this.clone(), super_obj.clone())?,25 b.name.clone(),26 params.clone(),27 b.value.clone(),28 )))29 ))30 })),31 )32 } else {33 (34 b.name.clone(),35 LazyBinding::Bindable(Rc::new(move |this, super_obj| {36 Ok(lazy_val!(closure!(clone context_creator, clone b, ||37 evaluate_named(38 context_creator.0(this.clone(), super_obj.clone())?,39 &b.value,40 b.name.clone()41 )42 )))43 })),44 )45 }46}4748pub fn evaluate_method(ctx: Context, name: Rc<str>, params: ParamsDesc, body: LocExpr) -> Val {49 Val::Func(Rc::new(FuncVal::Normal(FuncDesc {50 name,51 ctx,52 params,53 body,54 })))55}5657pub fn evaluate_field_name(58 context: Context,59 field_name: &jrsonnet_parser::FieldName,60) -> Result<Option<Rc<str>>> {61 Ok(match field_name {62 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),63 jrsonnet_parser::FieldName::Dyn(expr) => {64 let lazy = evaluate(context, expr)?;65 let value = lazy.unwrap_if_lazy()?;66 if matches!(value, Val::Null) {67 None68 } else {69 Some(value.try_cast_str("dynamic field name")?)70 }71 }72 })73}7475pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76 Ok(match (op, b) {77 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,78 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),79 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),80 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),81 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),82 })83}8485pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {86 Ok(match (a, b) {87 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8889 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)90 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),91 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9293 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),94 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9596 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),97 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),98 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,99 _ => throw!(BinaryOperatorDoesNotOperateOnValues(100 BinaryOpType::Add,101 a.value_type()?,102 b.value_type()?,103 )),104 })105}106107pub fn evaluate_binary_op_special(108 context: Context,109 a: &LocExpr,110 op: BinaryOpType,111 b: &LocExpr,112) -> Result<Val> {113 Ok(114 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117 (a, op, eb) => {118 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?119 }120 },121 )122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125 Ok(match (a, op, b) {126 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130 // Bool X Bool131 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134 // Str X Str135 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140 // Num X Num141 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,142 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143 if *v2 <= f64::EPSILON {144 throw!(DivisionByZero)145 }146 Val::new_checked_num(v1 / v2)?147 }148149 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,150151 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158 }159 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161 }162 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164 }165 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166 if *v2 < 0.0 {167 throw!(RuntimeError("shift by negative exponent".into()))168 }169 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)170 }171 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {172 if *v2 < 0.0 {173 throw!(RuntimeError("shift by negative exponent".into()))174 }175 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)176 }177178 _ => throw!(BinaryOperatorDoesNotOperateOnValues(179 op,180 a.value_type()?,181 b.value_type()?,182 )),183 })184}185186future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);187future_wrapper!(ObjValue, FutureObjValue);188189pub fn evaluate_comp<T>(190 context: Context,191 value: &impl Fn(Context) -> Result<T>,192 specs: &[CompSpec],193) -> Result<Option<Vec<T>>> {194 Ok(match specs.get(0) {195 None => Some(vec![value(context)?]),196 Some(CompSpec::IfSpec(IfSpecData(cond))) => {197 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {198 evaluate_comp(context, value, &specs[1..])?199 } else {200 None201 }202 }203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {204 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {205 Val::Arr(list) => {206 let mut out = Vec::new();207 for item in list.iter() {208 let item = item.unwrap_if_lazy()?;209 out.push(evaluate_comp(210 context.clone().with_var(var.clone(), item.clone()),211 value,212 &specs[1..],213 )?);214 }215 Some(out.into_iter().flatten().flatten().collect())216 }217 _ => throw!(InComprehensionCanOnlyIterateOverArray),218 }219 }220 })221}222223pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {224 let new_bindings = FutureNewBindings::new();225 let future_this = FutureObjValue::new();226 let context_creator = context_creator!(227 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {228 Ok(context.clone().extend_unbound(229 new_bindings.clone().unwrap(),230 context.dollar().clone().or_else(||this.clone()),231 Some(this.unwrap()),232 super_obj233 )?)234 })235 );236 {237 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();238 for (n, b) in members239 .iter()240 .filter_map(|m| match m {241 Member::BindStmt(b) => Some(b.clone()),242 _ => None,243 })244 .map(|b| evaluate_binding(&b, context_creator.clone()))245 {246 bindings.insert(n, b);247 }248 new_bindings.fill(bindings);249 }250251 let mut new_members = HashMap::new();252 for member in members.iter() {253 match member {254 Member::Field(FieldMember {255 name,256 plus,257 params: None,258 visibility,259 value,260 }) => {261 let name = evaluate_field_name(context.clone(), &name)?;262 if name.is_none() {263 continue;264 }265 let name = name.unwrap();266 new_members.insert(267 name.clone(),268 ObjMember {269 add: *plus,270 visibility: *visibility,271 invoke: LazyBinding::Bindable(Rc::new(272 closure!(clone name, clone value, clone context_creator, |this, super_obj| {273 Ok(LazyVal::new_resolved(evaluate(274 context_creator.0(this, super_obj)?,275 &value,276 )?))277 }),278 )),279 location: value.1.clone(),280 },281 );282 }283 Member::Field(FieldMember {284 name,285 params: Some(params),286 value,287 ..288 }) => {289 let name = evaluate_field_name(context.clone(), &name)?;290 if name.is_none() {291 continue;292 }293 let name = name.unwrap();294 new_members.insert(295 name.clone(),296 ObjMember {297 add: false,298 visibility: Visibility::Hidden,299 invoke: LazyBinding::Bindable(Rc::new(300 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {301 // TODO: Assert302 Ok(LazyVal::new_resolved(evaluate_method(303 context_creator.0(this, super_obj)?,304 name.clone(),305 params.clone(),306 value.clone(),307 )))308 }),309 )),310 location: value.1.clone(),311 },312 );313 }314 Member::BindStmt(_) => {}315 Member::AssertStmt(_) => {}316 }317 }318 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))319}320321pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,324 ObjBody::ObjComp(obj) => {325 let future_this = FutureObjValue::new();326 let mut new_members = HashMap::new();327 for (k, v) in evaluate_comp(328 context.clone(),329 &|ctx| {330 let new_bindings = FutureNewBindings::new();331 let context_creator = context_creator!(332 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {333 Ok(context.clone().extend_unbound(334 new_bindings.clone().unwrap(),335 context.dollar().clone().or_else(||this.clone()),336 None,337 super_obj338 )?)339 })340 );341 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();342 for (n, b) in obj343 .pre_locals344 .iter()345 .chain(obj.post_locals.iter())346 .map(|b| evaluate_binding(b, context_creator.clone()))347 {348 bindings.insert(n, b);349 }350 let bindings = new_bindings.fill(bindings);351 let ctx = ctx.extend_unbound(bindings, None, None, None)?;352 let key = evaluate(ctx.clone(), &obj.key)?;353 let value = LazyBinding::Bindable(Rc::new(354 closure!(clone ctx, clone obj.value, |this, _super_obj| {355 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))356 }),357 ));358359 Ok((key, value))360 },361 &obj.compspecs,362 )?363 .unwrap()364 {365 match k {366 Val::Null => {}367 Val::Str(n) => {368 new_members.insert(369 n,370 ObjMember {371 add: false,372 visibility: Visibility::Normal,373 invoke: v,374 location: obj.value.1.clone(),375 },376 );377 }378 v => throw!(FieldMustBeStringGot(v.value_type()?)),379 }380 }381382 future_this.fill(ObjValue::new(None, Rc::new(new_members)))383 }384 })385}386387pub fn evaluate_apply(388 context: Context,389 value: &LocExpr,390 args: &ArgsDesc,391 loc: &Option<ExprLocation>,392 tailstrict: bool,393) -> Result<Val> {394 let lazy = evaluate(context.clone(), value)?;395 let value = lazy.unwrap_if_lazy()?;396 Ok(match value {397 Val::Func(f) => {398 let body = || f.evaluate(context, loc, args, tailstrict);399 if tailstrict {400 body()?401 } else {402 push(loc, || format!("function <{}> call", f.name()), body)?403 }404 }405 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),406 })407}408409pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {410 use Expr::*;411 let LocExpr(expr, _loc) = lexpr;412 Ok(match &**expr {413 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),414 _ => evaluate(context, lexpr)?,415 })416}417418pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {419 use Expr::*;420 let LocExpr(expr, loc) = expr;421 Ok(match &**expr {422 Literal(LiteralType::This) => Val::Obj(423 context424 .this()425 .clone()426 .ok_or_else(|| CantUseSelfOutsideOfObject)?,427 ),428 Literal(LiteralType::Dollar) => Val::Obj(429 context430 .dollar()431 .clone()432 .ok_or_else(|| 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(context, 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(context, &v1, *o, &v2)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,442 Var(name) => push(443 loc,444 || format!("variable <{}>", name),445 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),446 )?,447 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {448 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;449 context450 .super_obj()451 .clone()452 .expect("no super found")453 .get_raw(name, &context.this().clone().expect("no this found"))?454 .expect("value not found")455 }456 Index(value, index) => {457 match (458 evaluate(context.clone(), value)?.unwrap_if_lazy()?,459 evaluate(context, index)?,460 ) {461 (Val::Obj(v), Val::Str(s)) => {462 let sn = s.clone();463 push(464 &loc,465 || format!("field <{}> access", sn),466 || {467 if let Some(v) = v.get(s.clone())? {468 Ok(v.unwrap_if_lazy()?)469 } else if let Some(Val::Str(n)) =470 v.get("__intristic_namespace__".into())?471 {472 Ok(Val::Func(Rc::new(FuncVal::Intristic(n, s))))473 } else {474 throw!(NoSuchField(s))475 }476 },477 )?478 }479 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(480 ValType::Obj,481 ValType::Str,482 n.value_type()?,483 )),484485 (Val::Arr(v), Val::Num(n)) => {486 if n.fract() > f64::EPSILON {487 throw!(FractionalIndex)488 }489 v.get(n as usize)490 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?491 .clone()492 .unwrap_if_lazy()?493 }494 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),495 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(496 ValType::Arr,497 ValType::Num,498 n.value_type()?,499 )),500501 (Val::Str(s), Val::Num(n)) => Val::Str(502 s.chars()503 .skip(n as usize)504 .take(1)505 .collect::<String>()506 .into(),507 ),508 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(509 ValType::Str,510 ValType::Num,511 n.value_type()?,512 )),513514 (v, _) => throw!(CantIndexInto(v.value_type()?)),515 }516 }517 LocalExpr(bindings, returned) => {518 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();519 let future_context = Context::new_future();520521 let context_creator = context_creator!(522 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))523 );524525 for (k, v) in bindings526 .iter()527 .map(|b| evaluate_binding(b, context_creator.clone()))528 {529 new_bindings.insert(k, v);530 }531532 let context = context533 .extend_unbound(new_bindings, None, None, None)?534 .into_future(future_context);535 evaluate(context, &returned.clone())?536 }537 Arr(items) => {538 let mut out = Vec::with_capacity(items.len());539 for item in items {540 out.push(Val::Lazy(lazy_val!(541 closure!(clone context, clone item, || {542 evaluate(context.clone(), &item)543 })544 )));545 }546 Val::Arr(Rc::new(out))547 }548 ArrComp(expr, compspecs) => Val::Arr(549 // First compspec should be forspec, so no "None" possible here550 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),551 ),552 Obj(body) => Val::Obj(evaluate_object(context, body)?),553 ObjExtend(s, t) => evaluate_add_op(554 &evaluate(context.clone(), s)?,555 &Val::Obj(evaluate_object(context, t)?),556 )?,557 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,558 Function(params, body) => {559 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())560 }561 AssertExpr(AssertStmt(value, msg), returned) => {562 let assertion_result = push(563 &value.1,564 || "assertion condition".to_owned(),565 || {566 evaluate(context.clone(), &value)?567 .try_cast_bool("assertion condition should be boolean")568 },569 )?;570 if assertion_result {571 evaluate(context, returned)?572 } else if let Some(msg) = msg {573 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));574 } else {575 throw!(AssertionFailed(Val::Null.to_string()?));576 }577 }578 ErrorStmt(e) => push(579 &loc,580 || "error statement".to_owned(),581 || {582 throw!(RuntimeError(583 evaluate(context, e)?.try_cast_str("error text should be string")?,584 ))585 },586 )?,587 IfElse {588 cond,589 cond_then,590 cond_else,591 } => {592 if evaluate(context.clone(), &cond.0)?593 .try_cast_bool("if condition should be boolean")?594 {595 evaluate(context, cond_then)?596 } else {597 match cond_else {598 Some(v) => evaluate(context, v)?,599 None => Val::Null,600 }601 }602 }603 Import(path) => {604 let mut tmp = loc605 .clone()606 .expect("imports can't be used without loc_data")607 .0;608 let import_location = Rc::make_mut(&mut tmp);609 import_location.pop();610 push(611 loc,612 || format!("import {:?}", path),613 || with_state(|s| s.import_file(&import_location, path)),614 )?615 }616 ImportStr(path) => {617 let mut tmp = loc618 .clone()619 .expect("imports can't be used without loc_data")620 .0;621 let import_location = Rc::make_mut(&mut tmp);622 import_location.pop();623 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)624 }625 Literal(LiteralType::Super) => throw!(StandaloneSuper),626 })627}1use crate::{2 context_creator, error::Error::*, future_wrapper, lazy_val, push, throw, with_state, Context,3 ContextCreator, FuncDesc, FuncVal, LazyBinding, LazyVal, ObjMember, ObjValue, Result, Val,4 ValType,5};6use closure::closure;7use jrsonnet_parser::{8 ArgsDesc, AssertStmt, BinaryOpType, BindSpec, CompSpec, Expr, ExprLocation, FieldMember,9 ForSpecData, IfSpecData, LiteralType, LocExpr, Member, ObjBody, ParamsDesc, UnaryOpType,10 Visibility,11};12use rustc_hash::FxHashMap;13use std::{collections::HashMap, rc::Rc};1415pub fn evaluate_binding(b: &BindSpec, context_creator: ContextCreator) -> (Rc<str>, LazyBinding) {16 let b = b.clone();17 if let Some(params) = &b.params {18 let params = params.clone();19 (20 b.name.clone(),21 LazyBinding::Bindable(Rc::new(move |this, super_obj| {22 Ok(lazy_val!(23 closure!(clone b, clone params, clone context_creator, || Ok(evaluate_method(24 context_creator.0(this.clone(), super_obj.clone())?,25 b.name.clone(),26 params.clone(),27 b.value.clone(),28 )))29 ))30 })),31 )32 } else {33 (34 b.name.clone(),35 LazyBinding::Bindable(Rc::new(move |this, super_obj| {36 Ok(lazy_val!(closure!(clone context_creator, clone b, ||37 evaluate_named(38 context_creator.0(this.clone(), super_obj.clone())?,39 &b.value,40 b.name.clone()41 )42 )))43 })),44 )45 }46}4748pub fn evaluate_method(ctx: Context, name: Rc<str>, params: ParamsDesc, body: LocExpr) -> Val {49 Val::Func(Rc::new(FuncVal::Normal(FuncDesc {50 name,51 ctx,52 params,53 body,54 })))55}5657pub fn evaluate_field_name(58 context: Context,59 field_name: &jrsonnet_parser::FieldName,60) -> Result<Option<Rc<str>>> {61 Ok(match field_name {62 jrsonnet_parser::FieldName::Fixed(n) => Some(n.clone()),63 jrsonnet_parser::FieldName::Dyn(expr) => {64 let lazy = evaluate(context, expr)?;65 let value = lazy.unwrap_if_lazy()?;66 if matches!(value, Val::Null) {67 None68 } else {69 Some(value.try_cast_str("dynamic field name")?)70 }71 }72 })73}7475pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {76 Ok(match (op, b) {77 (o, Val::Lazy(l)) => evaluate_unary_op(o, &l.evaluate()?)?,78 (UnaryOpType::Not, Val::Bool(v)) => Val::Bool(!v),79 (UnaryOpType::Minus, Val::Num(n)) => Val::Num(-*n),80 (UnaryOpType::BitNot, Val::Num(n)) => Val::Num(!(*n as i32) as f64),81 (op, o) => throw!(UnaryOperatorDoesNotOperateOnType(op, o.value_type()?)),82 })83}8485pub(crate) fn evaluate_add_op(a: &Val, b: &Val) -> Result<Val> {86 Ok(match (a, b) {87 (Val::Str(v1), Val::Str(v2)) => Val::Str(((**v1).to_owned() + &v2).into()),8889 // Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)90 (Val::Num(n), Val::Str(o)) => Val::Str(format!("{}{}", n, o).into()),91 (Val::Str(o), Val::Num(n)) => Val::Str(format!("{}{}", o, n).into()),9293 (Val::Str(s), o) => Val::Str(format!("{}{}", s, o.clone().to_string()?).into()),94 (o, Val::Str(s)) => Val::Str(format!("{}{}", o.clone().to_string()?, s).into()),9596 (Val::Obj(v1), Val::Obj(v2)) => Val::Obj(v2.with_super(v1.clone())),97 (Val::Arr(a), Val::Arr(b)) => Val::Arr(Rc::new([&a[..], &b[..]].concat())),98 (Val::Num(v1), Val::Num(v2)) => Val::new_checked_num(v1 + v2)?,99 _ => throw!(BinaryOperatorDoesNotOperateOnValues(100 BinaryOpType::Add,101 a.value_type()?,102 b.value_type()?,103 )),104 })105}106107pub fn evaluate_binary_op_special(108 context: Context,109 a: &LocExpr,110 op: BinaryOpType,111 b: &LocExpr,112) -> Result<Val> {113 Ok(114 match (evaluate(context.clone(), &a)?.unwrap_if_lazy()?, op, b) {115 (Val::Bool(true), BinaryOpType::Or, _o) => Val::Bool(true),116 (Val::Bool(false), BinaryOpType::And, _o) => Val::Bool(false),117 (a, op, eb) => {118 evaluate_binary_op_normal(&a, op, &evaluate(context, eb)?.unwrap_if_lazy()?)?119 }120 },121 )122}123124pub fn evaluate_binary_op_normal(a: &Val, op: BinaryOpType, b: &Val) -> Result<Val> {125 Ok(match (a, op, b) {126 (a, BinaryOpType::Add, b) => evaluate_add_op(a, b)?,127128 (Val::Str(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::Str(v1.repeat(*v2 as usize).into()),129130 // Bool X Bool131 (Val::Bool(a), BinaryOpType::And, Val::Bool(b)) => Val::Bool(*a && *b),132 (Val::Bool(a), BinaryOpType::Or, Val::Bool(b)) => Val::Bool(*a || *b),133134 // Str X Str135 (Val::Str(v1), BinaryOpType::Lt, Val::Str(v2)) => Val::Bool(v1 < v2),136 (Val::Str(v1), BinaryOpType::Gt, Val::Str(v2)) => Val::Bool(v1 > v2),137 (Val::Str(v1), BinaryOpType::Lte, Val::Str(v2)) => Val::Bool(v1 <= v2),138 (Val::Str(v1), BinaryOpType::Gte, Val::Str(v2)) => Val::Bool(v1 >= v2),139140 // Num X Num141 (Val::Num(v1), BinaryOpType::Mul, Val::Num(v2)) => Val::new_checked_num(v1 * v2)?,142 (Val::Num(v1), BinaryOpType::Div, Val::Num(v2)) => {143 if *v2 <= f64::EPSILON {144 throw!(DivisionByZero)145 }146 Val::new_checked_num(v1 / v2)?147 }148149 (Val::Num(v1), BinaryOpType::Sub, Val::Num(v2)) => Val::new_checked_num(v1 - v2)?,150151 (Val::Num(v1), BinaryOpType::Lt, Val::Num(v2)) => Val::Bool(v1 < v2),152 (Val::Num(v1), BinaryOpType::Gt, Val::Num(v2)) => Val::Bool(v1 > v2),153 (Val::Num(v1), BinaryOpType::Lte, Val::Num(v2)) => Val::Bool(v1 <= v2),154 (Val::Num(v1), BinaryOpType::Gte, Val::Num(v2)) => Val::Bool(v1 >= v2),155156 (Val::Num(v1), BinaryOpType::BitAnd, Val::Num(v2)) => {157 Val::Num(((*v1 as i32) & (*v2 as i32)) as f64)158 }159 (Val::Num(v1), BinaryOpType::BitOr, Val::Num(v2)) => {160 Val::Num(((*v1 as i32) | (*v2 as i32)) as f64)161 }162 (Val::Num(v1), BinaryOpType::BitXor, Val::Num(v2)) => {163 Val::Num(((*v1 as i32) ^ (*v2 as i32)) as f64)164 }165 (Val::Num(v1), BinaryOpType::Lhs, Val::Num(v2)) => {166 if *v2 < 0.0 {167 throw!(RuntimeError("shift by negative exponent".into()))168 }169 Val::Num(((*v1 as i32) << (*v2 as i32)) as f64)170 }171 (Val::Num(v1), BinaryOpType::Rhs, Val::Num(v2)) => {172 if *v2 < 0.0 {173 throw!(RuntimeError("shift by negative exponent".into()))174 }175 Val::Num(((*v1 as i32) >> (*v2 as i32)) as f64)176 }177178 _ => throw!(BinaryOperatorDoesNotOperateOnValues(179 op,180 a.value_type()?,181 b.value_type()?,182 )),183 })184}185186future_wrapper!(HashMap<Rc<str>, LazyBinding>, FutureNewBindings);187future_wrapper!(ObjValue, FutureObjValue);188189pub fn evaluate_comp<T>(190 context: Context,191 value: &impl Fn(Context) -> Result<T>,192 specs: &[CompSpec],193) -> Result<Option<Vec<T>>> {194 Ok(match specs.get(0) {195 None => Some(vec![value(context)?]),196 Some(CompSpec::IfSpec(IfSpecData(cond))) => {197 if evaluate(context.clone(), &cond)?.try_cast_bool("if spec")? {198 evaluate_comp(context, value, &specs[1..])?199 } else {200 None201 }202 }203 Some(CompSpec::ForSpec(ForSpecData(var, expr))) => {204 match evaluate(context.clone(), &expr)?.unwrap_if_lazy()? {205 Val::Arr(list) => {206 let mut out = Vec::new();207 for item in list.iter() {208 let item = item.unwrap_if_lazy()?;209 out.push(evaluate_comp(210 context.clone().with_var(var.clone(), item.clone()),211 value,212 &specs[1..],213 )?);214 }215 Some(out.into_iter().flatten().flatten().collect())216 }217 _ => throw!(InComprehensionCanOnlyIterateOverArray),218 }219 }220 })221}222223pub fn evaluate_member_list_object(context: Context, members: &[Member]) -> Result<ObjValue> {224 let new_bindings = FutureNewBindings::new();225 let future_this = FutureObjValue::new();226 let context_creator = context_creator!(227 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {228 Ok(context.clone().extend_unbound(229 new_bindings.clone().unwrap(),230 context.dollar().clone().or_else(||this.clone()),231 Some(this.unwrap()),232 super_obj233 )?)234 })235 );236 {237 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();238 for (n, b) in members239 .iter()240 .filter_map(|m| match m {241 Member::BindStmt(b) => Some(b.clone()),242 _ => None,243 })244 .map(|b| evaluate_binding(&b, context_creator.clone()))245 {246 bindings.insert(n, b);247 }248 new_bindings.fill(bindings);249 }250251 let mut new_members = HashMap::new();252 for member in members.iter() {253 match member {254 Member::Field(FieldMember {255 name,256 plus,257 params: None,258 visibility,259 value,260 }) => {261 let name = evaluate_field_name(context.clone(), &name)?;262 if name.is_none() {263 continue;264 }265 let name = name.unwrap();266 new_members.insert(267 name.clone(),268 ObjMember {269 add: *plus,270 visibility: *visibility,271 invoke: LazyBinding::Bindable(Rc::new(272 closure!(clone name, clone value, clone context_creator, |this, super_obj| {273 Ok(LazyVal::new_resolved(evaluate(274 context_creator.0(this, super_obj)?,275 &value,276 )?))277 }),278 )),279 location: value.1.clone(),280 },281 );282 }283 Member::Field(FieldMember {284 name,285 params: Some(params),286 value,287 ..288 }) => {289 let name = evaluate_field_name(context.clone(), &name)?;290 if name.is_none() {291 continue;292 }293 let name = name.unwrap();294 new_members.insert(295 name.clone(),296 ObjMember {297 add: false,298 visibility: Visibility::Hidden,299 invoke: LazyBinding::Bindable(Rc::new(300 closure!(clone value, clone context_creator, clone params, clone name, |this, super_obj| {301 // TODO: Assert302 Ok(LazyVal::new_resolved(evaluate_method(303 context_creator.0(this, super_obj)?,304 name.clone(),305 params.clone(),306 value.clone(),307 )))308 }),309 )),310 location: value.1.clone(),311 },312 );313 }314 Member::BindStmt(_) => {}315 Member::AssertStmt(_) => {}316 }317 }318 Ok(future_this.fill(ObjValue::new(None, Rc::new(new_members))))319}320321pub fn evaluate_object(context: Context, object: &ObjBody) -> Result<ObjValue> {322 Ok(match object {323 ObjBody::MemberList(members) => evaluate_member_list_object(context, &members)?,324 ObjBody::ObjComp(obj) => {325 let future_this = FutureObjValue::new();326 let mut new_members = HashMap::new();327 for (k, v) in evaluate_comp(328 context.clone(),329 &|ctx| {330 let new_bindings = FutureNewBindings::new();331 let context_creator = context_creator!(332 closure!(clone context, clone new_bindings, |this: Option<ObjValue>, super_obj: Option<ObjValue>| {333 Ok(context.clone().extend_unbound(334 new_bindings.clone().unwrap(),335 context.dollar().clone().or_else(||this.clone()),336 None,337 super_obj338 )?)339 })340 );341 let mut bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();342 for (n, b) in obj343 .pre_locals344 .iter()345 .chain(obj.post_locals.iter())346 .map(|b| evaluate_binding(b, context_creator.clone()))347 {348 bindings.insert(n, b);349 }350 let bindings = new_bindings.fill(bindings);351 let ctx = ctx.extend_unbound(bindings, None, None, None)?;352 let key = evaluate(ctx.clone(), &obj.key)?;353 let value = LazyBinding::Bindable(Rc::new(354 closure!(clone ctx, clone obj.value, |this, _super_obj| {355 Ok(LazyVal::new_resolved(evaluate(ctx.clone().extend(FxHashMap::default(), None, this, None), &value)?))356 }),357 ));358359 Ok((key, value))360 },361 &obj.compspecs,362 )?363 .unwrap()364 {365 match k {366 Val::Null => {}367 Val::Str(n) => {368 new_members.insert(369 n,370 ObjMember {371 add: false,372 visibility: Visibility::Normal,373 invoke: v,374 location: obj.value.1.clone(),375 },376 );377 }378 v => throw!(FieldMustBeStringGot(v.value_type()?)),379 }380 }381382 future_this.fill(ObjValue::new(None, Rc::new(new_members)))383 }384 })385}386387pub fn evaluate_apply(388 context: Context,389 value: &LocExpr,390 args: &ArgsDesc,391 loc: &Option<ExprLocation>,392 tailstrict: bool,393) -> Result<Val> {394 let lazy = evaluate(context.clone(), value)?;395 let value = lazy.unwrap_if_lazy()?;396 Ok(match value {397 Val::Func(f) => {398 let body = || f.evaluate(context, loc, args, tailstrict);399 if tailstrict {400 body()?401 } else {402 push(loc, || format!("function <{}> call", f.name()), body)?403 }404 }405 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type()?)),406 })407}408409pub fn evaluate_named(context: Context, lexpr: &LocExpr, name: Rc<str>) -> Result<Val> {410 use Expr::*;411 let LocExpr(expr, _loc) = lexpr;412 Ok(match &**expr {413 Function(params, body) => evaluate_method(context, name, params.clone(), body.clone()),414 _ => evaluate(context, lexpr)?,415 })416}417418pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {419 use Expr::*;420 let LocExpr(expr, loc) = expr;421 Ok(match &**expr {422 Literal(LiteralType::This) => Val::Obj(423 context424 .this()425 .clone()426 .ok_or_else(|| CantUseSelfOutsideOfObject)?,427 ),428 Literal(LiteralType::Dollar) => Val::Obj(429 context430 .dollar()431 .clone()432 .ok_or_else(|| 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(context, 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(context, &v1, *o, &v2)?,441 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,442 Var(name) => push(443 loc,444 || format!("variable <{}>", name),445 || Ok(Val::Lazy(context.binding(name.clone())?).unwrap_if_lazy()?),446 )?,447 Index(LocExpr(v, _), index) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {448 let name = evaluate(context.clone(), index)?.try_cast_str("object index")?;449 context450 .super_obj()451 .clone()452 .expect("no super found")453 .get_raw(name, &context.this().clone().expect("no this found"))?454 .expect("value not found")455 }456 Index(value, index) => {457 match (458 evaluate(context.clone(), value)?.unwrap_if_lazy()?,459 evaluate(context, index)?,460 ) {461 (Val::Obj(v), Val::Str(s)) => {462 let sn = s.clone();463 push(464 &loc,465 || format!("field <{}> access", sn),466 || {467 if let Some(v) = v.get(s.clone())? {468 Ok(v.unwrap_if_lazy()?)469 } else if let Some(Val::Str(n)) =470 v.get("__intristic_namespace__".into())?471 {472 Ok(Val::Func(Rc::new(FuncVal::Intristic(n, s))))473 } else {474 throw!(NoSuchField(s))475 }476 },477 )?478 }479 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(480 ValType::Obj,481 ValType::Str,482 n.value_type()?,483 )),484485 (Val::Arr(v), Val::Num(n)) => {486 if n.fract() > f64::EPSILON {487 throw!(FractionalIndex)488 }489 v.get(n as usize)490 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?491 .clone()492 .unwrap_if_lazy()?493 }494 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),495 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(496 ValType::Arr,497 ValType::Num,498 n.value_type()?,499 )),500501 (Val::Str(s), Val::Num(n)) => Val::Str(502 s.chars()503 .skip(n as usize)504 .take(1)505 .collect::<String>()506 .into(),507 ),508 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(509 ValType::Str,510 ValType::Num,511 n.value_type()?,512 )),513514 (v, _) => throw!(CantIndexInto(v.value_type()?)),515 }516 }517 LocalExpr(bindings, returned) => {518 let mut new_bindings: HashMap<Rc<str>, LazyBinding> = HashMap::new();519 let future_context = Context::new_future();520521 let context_creator = context_creator!(522 closure!(clone future_context, |_, _| Ok(future_context.clone().unwrap()))523 );524525 for (k, v) in bindings526 .iter()527 .map(|b| evaluate_binding(b, context_creator.clone()))528 {529 new_bindings.insert(k, v);530 }531532 let context = context533 .extend_unbound(new_bindings, None, None, None)?534 .into_future(future_context);535 evaluate(context, &returned.clone())?536 }537 Arr(items) => {538 let mut out = Vec::with_capacity(items.len());539 for item in items {540 out.push(Val::Lazy(lazy_val!(541 closure!(clone context, clone item, || {542 evaluate(context.clone(), &item)543 })544 )));545 }546 Val::Arr(Rc::new(out))547 }548 ArrComp(expr, comp_specs) => Val::Arr(549 // First comp_spec should be for_spec, so no "None" possible here550 Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.unwrap()),551 ),552 Obj(body) => Val::Obj(evaluate_object(context, body)?),553 ObjExtend(s, t) => evaluate_add_op(554 &evaluate(context.clone(), s)?,555 &Val::Obj(evaluate_object(context, t)?),556 )?,557 Apply(value, args, tailstrict) => evaluate_apply(context, value, args, loc, *tailstrict)?,558 Function(params, body) => {559 evaluate_method(context, "anonymous".into(), params.clone(), body.clone())560 }561 AssertExpr(AssertStmt(value, msg), returned) => {562 let assertion_result = push(563 &value.1,564 || "assertion condition".to_owned(),565 || {566 evaluate(context.clone(), &value)?567 .try_cast_bool("assertion condition should be of type `boolean`")568 },569 )?;570 if assertion_result {571 evaluate(context, returned)?572 } else if let Some(msg) = msg {573 throw!(AssertionFailed(evaluate(context, msg)?.to_string()?));574 } else {575 throw!(AssertionFailed(Val::Null.to_string()?));576 }577 }578 ErrorStmt(e) => push(579 &loc,580 || "error statement".to_owned(),581 || {582 throw!(RuntimeError(583 evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,584 ))585 },586 )?,587 IfElse {588 cond,589 cond_then,590 cond_else,591 } => {592 if evaluate(context.clone(), &cond.0)?593 .try_cast_bool("if condition should be of type `boolean`")?594 {595 evaluate(context, cond_then)?596 } else {597 match cond_else {598 Some(v) => evaluate(context, v)?,599 None => Val::Null,600 }601 }602 }603 Import(path) => {604 let mut tmp = loc605 .clone()606 .expect("imports cannot be used without loc_data")607 .0;608 let import_location = Rc::make_mut(&mut tmp);609 import_location.pop();610 push(611 loc,612 || format!("import {:?}", path),613 || with_state(|s| s.import_file(&import_location, path)),614 )?615 }616 ImportStr(path) => {617 let mut tmp = loc618 .clone()619 .expect("imports cannot be used without loc_data")620 .0;621 let import_location = Rc::make_mut(&mut tmp);622 import_location.pop();623 Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)624 }625 Literal(LiteralType::Super) => throw!(StandaloneSuper),626 })627}crates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -7,13 +7,14 @@
const NO_DEFAULT_CONTEXT: &str =
"no default context set for call with defined default parameter value";
-/// Creates correct [context](Context) for function body evaluation, returning error on invalid call
+/// Creates correct [context](Context) for function body evaluation returning error on invalid call.
///
-/// * `ctx` used for passed argument expressions execution, and for body execution (if `body_ctx` is not set)
-/// * `body_ctx` used for default parameter values execution, and for body execution (if set)
-/// * `params` function parameters definition
-/// * `args` passed function arguments
-/// * `tailstruct` if true - function arguments is eager executed, otherwise - lazy
+/// ## Parameters
+/// * `ctx`: used for passed argument expressions' execution and for body execution (if `body_ctx` is not set)
+/// * `body_ctx`: used for default parameter values' execution and for body execution (if set)
+/// * `params`: function parameters' definition
+/// * `args`: passed function arguments
+/// * `tailstrict`: if set to `true` function arguments are eagerly executed, otherwise - lazily
pub fn parse_function_call(
ctx: Context,
body_ctx: Option<Context>,
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -9,17 +9,19 @@
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver {
- /// Resolve real file path, i.e
- /// `(/home/user/manifests, b.libsonnet)` can resolve to both `/home/user/manifests/b.libsonnet` and to `/home/user/vendor/b.libsonnet`
- /// (Where vendor is a library path)
+ /// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
+ /// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`
+ /// where `${vendor}` is a library path.
fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;
+
/// Reads file from filesystem, should be used only with path received from `resolve_file`
fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>>;
+
/// # Safety
///
- /// For use in bindings, do not try to use it elsewhere
- /// Implementations, which are not intended to be
- /// used in bindings, should panic in this method
+ /// For use only in bindings, should not be used elsewhere.
+ /// Implementations which are not intended to be used in bindings
+ /// should panic on call to this method.
unsafe fn as_any(&self) -> &dyn Any;
}
@@ -29,12 +31,14 @@
fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
throw!(ImportNotSupported(from.clone(), path.clone()))
}
+
fn load_file_contents(&self, _resolved: &PathBuf) -> Result<Rc<str>> {
// Can be only caused by library direct consumer, not by supplied jsonnet
panic!("dummy resolver can't load any file")
}
+
unsafe fn as_any(&self) -> &dyn Any {
- panic!("this resolver can't be used as any")
+ panic!("`as_any($self)` is not supported by dummy resolver")
}
}
impl Default for Box<dyn ImportResolver> {
@@ -46,8 +50,8 @@
/// File resolver, can load file from both FS and library paths
#[derive(Default)]
pub struct FileImportResolver {
- /// Library directories to search for file
- /// In original jsonnet referred as jpath
+ /// Library directories to search for file.
+ /// Referred to as `jpath` in original jsonnet implementation.
pub library_paths: Vec<PathBuf>,
}
impl ImportResolver for FileImportResolver {
@@ -81,7 +85,7 @@
type ResolutionData = (PathBuf, PathBuf);
-/// Caches results of underlying resolver implementation
+/// Caches results of the underlying resolver
pub struct CachingImportResolver {
resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,
loading_cache: RefCell<HashMap<PathBuf, Result<Rc<str>>>>,
@@ -95,6 +99,7 @@
.or_insert_with(|| self.inner.resolve_file(from, path))
.clone()
}
+
fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>> {
self.loading_cache
.borrow_mut()
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -56,11 +56,11 @@
}
pub struct EvaluationSettings {
- /// Limits recursion by limiting stack frames
+ /// Limits recursion by limiting the number of stack frames
pub max_stack: usize,
- /// Limit amount of stack trace items preserved
+ /// Limits amount of stack trace items preserved
pub max_trace: usize,
- /// Used for std.extVar
+ /// Used for s`td.extVar`
pub ext_vars: HashMap<Rc<str>, Val>,
/// Used for ext.native
pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,
@@ -96,10 +96,9 @@
#[derive(Default)]
struct EvaluationData {
- /// Used for stack overflow detection, stacktrace is now populated on unwind
+ /// Used for stack overflow detection, stacktrace is populated on unwind
stack_depth: usize,
- /// Contains file source codes and evaluated results for imports and pretty
- /// printing stacktraces
+ /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
files: HashMap<Rc<PathBuf>, FileData>,
str_files: HashMap<Rc<PathBuf>, Rc<str>>,
}
@@ -118,8 +117,8 @@
}
thread_local! {
- /// Contains state for currently executing file
- /// Global state is fine there
+ /// Contains the state for a currently executed file.
+ /// Global state is fine here.
pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)
}
pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
@@ -142,7 +141,7 @@
pub struct EvaluationState(Rc<EvaluationStateInternals>);
impl EvaluationState {
- /// Parses and adds file to loaded
+ /// Parses and adds files as loaded
pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {
self.add_parsed_file(
path.clone(),
@@ -264,7 +263,7 @@
Context::new().extend_unbound(new_bindings, None, None, None)
}
- /// Executes code, creating new stack frame
+ /// Executes code creating a new stack frame
pub fn push<T>(
&self,
e: &ExprLocation,
@@ -294,7 +293,7 @@
result
}
- /// Runs passed function in state (required, if function needs to modify stack trace)
+ /// Runs passed function in state (required if function needs to modify stack trace)
pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {
EVAL_STATE.with(|v| {
let has_state = v.borrow().is_some();
@@ -328,7 +327,7 @@
self.run_in_state(|| val.manifest_stream(&self.manifest_format()))
}
- /// If passed value is function - call with set TLA
+ /// If passed value is function then call with set TLA
pub fn with_tla(&self, val: Val) -> Result<Val> {
Ok(match val {
Val::Func(func) => func.evaluate_map(
@@ -357,7 +356,7 @@
}
}
-/// Raw methods evaluates passed values, but not performs TLA execution
+/// Raw methods evaluate passed values but don't perform TLA execution
impl EvaluationState {
pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))
@@ -365,7 +364,7 @@
pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))
}
- /// Parses and evaluates snippet
+ /// Parses and evaluates the given snippet
pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {
let parsed = parse(
&code,
@@ -378,7 +377,7 @@
self.add_parsed_file(source, code, parsed.clone())?;
self.evaluate_expr_raw(parsed)
}
- /// Evaluates parsed expression
+ /// Evaluates the parsed expression
pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {
self.run_in_state(|| evaluate(self.create_default_context()?, &code))
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -4,13 +4,13 @@
pub use location::*;
use std::path::PathBuf;
-/// How paths should be displayed
+/// The way paths should be displayed
pub enum PathResolver {
- /// Only filename will be shown
+ /// Only filename
FileName,
- /// Absolute path of file
+ /// Absolute path
Absolute,
- /// Relative path from base directory
+ /// Path relative to base directory
Relative(PathBuf),
}
@@ -32,7 +32,7 @@
}
}
-/// Implements trace to string pretty-printing
+/// Implements pretty-printing of traces
pub trait TraceFormat {
fn write_trace(
&self,
@@ -73,7 +73,7 @@
Ok(())
}
-/// vanilla jsonnet like formatting
+/// vanilla-like jsonnet formatting
pub struct CompactFormat {
pub resolver: PathResolver,
pub padding: usize,
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -225,7 +225,8 @@
};
}
impl Val {
- /// Creates Val::Num after checking for overflow. As numbers are f64, we can just check for finity
+ /// Creates `Val::Num` after checking for numeric overflow.
+ /// As numbers are `f64`, we can just check for their finity.
pub fn new_checked_num(num: f64) -> Result<Val> {
if num.is_finite() {
Ok(Val::Num(num))
@@ -379,7 +380,7 @@
.map(|s| s.into())
}
- /// Calls std.manifestJson
+ /// Calls `std.manifestJson`
#[cfg(feature = "faster")]
pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
manifest_json_ex(
@@ -392,7 +393,7 @@
.map(|s| s.into())
}
- /// Calls std.manifestJson
+ /// Calls `std.manifestJson`
#[cfg(not(feature = "faster"))]
pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {
with_state(|s| {
@@ -444,7 +445,7 @@
matches!(val, Val::Func(_))
}
-/// Implements std.primitiveEquals builtin
+/// Native implementation of `std.primitiveEquals`
pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {
Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {
(Val::Bool(a), Val::Bool(b)) => a == b,
@@ -464,7 +465,7 @@
})
}
-/// Native implementation of std.equals
+/// Native implementation of `std.equals`
pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {
let val_a = val_a.unwrap_if_lazy()?;
let val_b = val_b.unwrap_if_lazy()?;