difftreelog
doc: review issues
in: master
19 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -93,7 +93,7 @@
/// # Safety
///
-/// Caller should pass correct callback function
+/// It should be safe to call `cb` using valid values with passed `ctx`
#[no_mangle]
pub unsafe extern "C" fn jsonnet_import_callback(
vm: &State,
@@ -109,10 +109,10 @@
/// # Safety
///
-/// Caller should pass correct path: it should contain correct utf-8, and be \0-terminated
+/// `path` should be a NUL-terminated string
#[no_mangle]
-pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, v: *const c_char) {
- let cstr = CStr::from_ptr(v);
+pub unsafe extern "C" fn jsonnet_jpath_add(vm: &State, path: *const c_char) {
+ let cstr = CStr::from_ptr(path);
let path = PathBuf::from(cstr.to_str().unwrap());
let any_resolver = vm.import_resolver();
let resolver = any_resolver
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -41,17 +41,10 @@
let str = OsStr::from_bytes(input.to_bytes());
Cow::Borrowed(Path::new(str))
}
- #[cfg(target_family = "windows")]
+ #[cfg(not(target_family = "unix"))]
{
- use std::os::windows::ffi::OsStringExt;
- let str = input.to_str().expect("input is not utf8");
- let wide = str.encode_utf16().collect::<Vec<_>>();
- let wide = OsString::from_wide(&wide);
- Cow::Owned(PathBuf::new(wide))
- }
- #[cfg(not(any(target_family = "unix", target_family = "windows")))]
- {
- compile_error!("unsupported os")
+ let string = input.to_str().expect("bad utf-8");
+ Cow::Borrowed(string.as_ref())
}
}
@@ -62,9 +55,11 @@
let str = CString::new(input.as_os_str().as_bytes()).expect("input has zero byte in it");
Cow::Owned(str)
}
- #[cfg(not(any(target_family = "unix", target_family = "windows")))]
+ #[cfg(not(target_family = "unix"))]
{
- compile_error!("unsupported os")
+ let str = input.as_os_str().to_str().expect("bad utf-8");
+ let cstr = CString::new(str).expect("input has NUL inside");
+ Cow::Owned(cstr)
}
}
@@ -169,7 +164,7 @@
///
/// # Safety
///
-/// `filename` should be a \0-terminated string
+/// `filename` should be a NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_evaluate_file(
vm: &State,
@@ -200,7 +195,7 @@
///
/// # Safety
///
-/// `filename`, `snippet` should be a \0-terminated strings
+/// `filename`, `snippet` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_evaluate_snippet(
vm: &State,
bindings/jsonnet/src/native.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/native.rs
+++ b/bindings/jsonnet/src/native.rs
@@ -65,9 +65,9 @@
/// # Safety
///
/// `vm` should be a vm allocated by `jsonnet_make`
-/// `cb` should be a correct function pointer
-/// `raw_params` should point to a NULL-terminated string array
-/// `name`, `raw_params` elements should be a \0-terminated strings
+/// `name` should be a NUL-terminated string
+/// `cb` should be a function pointer
+/// `raw_params` should point to a NULL-terminated array of NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_native_callback(
vm: &State,
bindings/jsonnet/src/val_make.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_make.rs
+++ b/bindings/jsonnet/src/val_make.rs
@@ -12,7 +12,7 @@
///
/// # Safety
///
-/// `v` should be a \0-terminated string
+/// `v` should be a NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_make_string(_vm: &State, val: *const c_char) -> *mut Val {
let val = CStr::from_ptr(val);
bindings/jsonnet/src/val_modify.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/val_modify.rs
+++ b/bindings/jsonnet/src/val_modify.rs
@@ -11,8 +11,8 @@
///
/// # Safety
///
-/// `arr` should be correct pointer to array value allocated by make_array, or returned by other library call
-/// `val` should be correct pointer to value allocated using this library
+/// `arr` should be a pointer to array value allocated by make_array, or returned by other library call
+/// `val` should be a pointer to value allocated using this library
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_array_append(_vm: &State, arr: &mut Val, val: &Val) {
match arr {
@@ -35,8 +35,8 @@
///
/// # Safety
///
-/// `obj` should be a valid pointer to object value allocated by `make_object`, or returned by other library call
-/// `name` should be \0-terminated string
+/// `obj` should be a pointer to object value allocated by `make_object`, or returned by other library call
+/// `name` should be NUL-terminated string
#[no_mangle]
pub unsafe extern "C" fn jsonnet_json_object_append(
_vm: &State,
bindings/jsonnet/src/vars_tlas.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/vars_tlas.rs
+++ b/bindings/jsonnet/src/vars_tlas.rs
@@ -4,13 +4,13 @@
use jrsonnet_evaluator::State;
-/// Bind a Jsonnet external var to the given string.
+/// Binds a Jsonnet external variable to the given string.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_var(vm: &State, name: *const c_char, value: *const c_char) {
let name = CStr::from_ptr(name);
@@ -27,13 +27,13 @@
)
}
-/// Bind a Jsonnet external var to the given code.
+/// Binds a Jsonnet external variable to the given code.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_ext_code(vm: &State, name: *const c_char, code: *const c_char) {
let name = CStr::from_ptr(name);
@@ -51,13 +51,13 @@
.expect("can't parse ext code")
}
-/// Bind a string top-level argument for a top-level parameter.
+/// Binds a top-level string argument for a top-level parameter.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `value`, they need to be \0-terminated strings
+/// `name`, `value` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_tla_var(vm: &State, name: *const c_char, value: *const c_char) {
let name = CStr::from_ptr(name);
@@ -68,13 +68,13 @@
)
}
-/// Bind a code top-level argument for a top-level parameter.
+/// Binds a top-level code argument for a top-level parameter.
///
-/// Argument values are copied so memory should be managed by caller.
+/// Argument values are copied so memory should be managed by the caller.
///
/// # Safety
///
-/// Caller should pass correct pointers as `name` and `code`, they need to be \0-terminated strings
+/// `name`, `code` should be a NUL-terminated strings
#[no_mangle]
pub unsafe extern "C" fn jsonnet_tla_code(vm: &State, name: *const c_char, code: *const c_char) {
let name = CStr::from_ptr(name);
crates/jrsonnet-evaluator/src/ctx.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/ctx.rs
+++ b/crates/jrsonnet-evaluator/src/ctx.rs
@@ -20,6 +20,9 @@
}
}
+/// Context keeps information about current lexical code location
+///
+/// This information includes local variables, top-level object (`$`), current object (`this`), and super object (`super`)
#[derive(Debug, Clone, Trace)]
pub struct Context(Cc<ContextInternals>);
impl Context {
@@ -160,8 +163,11 @@
extend: Some(parent),
}
}
+ /// # Panics
+ /// If `name` is already bound
pub fn bind(&mut self, name: IStr, value: Thunk<Val>) -> &mut Self {
- self.bindings.insert(name, value);
+ let old = self.bindings.insert(name, value);
+ assert!(old.is_none(), "variable bound twice in single context call");
self
}
pub fn build(self) -> Context {
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -67,7 +67,10 @@
type FunctionSignature = Vec<(Option<IStr>, bool)>;
+/// Possible errors
+#[allow(missing_docs)]
#[derive(Error, Debug, Clone, Trace)]
+#[non_exhaustive]
pub enum Error {
#[error("intrinsic not found: {0}")]
IntrinsicNotFound(IStr),
@@ -217,9 +220,13 @@
}
}
+/// Single stack trace frame
#[derive(Clone, Debug, Trace)]
pub struct StackTraceElement {
+ /// Source of this frame
+ /// Some frames only act as description, without attached source
pub location: Option<ExprLocation>,
+ /// Frame description
pub desc: String,
}
#[derive(Debug, Clone, Trace)]
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth1use 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) => s.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 // We have single context for all fields, so we can cache binds141 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(188 s.clone(),189 tb!(UnboundValue {190 uctx: uctx.clone(),191 value: value.clone(),192 name: name.clone()193 }),194 )?;195 }196 Member::Field(FieldMember {197 name,198 params: Some(params),199 value,200 ..201 }) => {202 #[derive(Trace)]203 struct UnboundMethod<B: Trace> {204 uctx: B,205 value: LocExpr,206 params: ParamsDesc,207 name: IStr,208 }209 impl<B: Unbound<Bound = Context>> Unbound for UnboundMethod<B> {210 type Bound = Thunk<Val>;211 fn bind(212 &self,213 s: State,214 sup: Option<ObjValue>,215 this: Option<ObjValue>,216 ) -> Result<Thunk<Val>> {217 Ok(Thunk::evaluated(evaluate_method(218 self.uctx.bind(s, sup, this)?,219 self.name.clone(),220 self.params.clone(),221 self.value.clone(),222 )))223 }224 }225226 let name = if let Some(name) = evaluate_field_name(s.clone(), ctx.clone(), name)? {227 name228 } else {229 continue;230 };231232 builder233 .member(name.clone())234 .hide()235 .with_location(value.1.clone())236 .bindable(237 s.clone(),238 tb!(UnboundMethod {239 uctx: uctx.clone(),240 value: value.clone(),241 params: params.clone(),242 name: name.clone()243 }),244 )?;245 }246 Member::BindStmt(_) => {}247 Member::AssertStmt(stmt) => {248 #[derive(Trace)]249 struct ObjectAssert<B: Trace> {250 uctx: B,251 assert: AssertStmt,252 }253 impl<B: Unbound<Bound = Context>> ObjectAssertion for ObjectAssert<B> {254 fn run(255 &self,256 s: State,257 sup: Option<ObjValue>,258 this: Option<ObjValue>,259 ) -> Result<()> {260 let ctx = self.uctx.bind(s.clone(), sup, this)?;261 evaluate_assert(s, ctx, &self.assert)262 }263 }264 builder.assert(tb!(ObjectAssert {265 uctx: uctx.clone(),266 assert: stmt.clone(),267 }));268 }269 }270 }271 let this = builder.build();272 let _ctx = ctx273 .extend(GcHashMap::new(), None, None, Some(this.clone()))274 .into_future(fctx);275 Ok(this)276}277278pub fn evaluate_object(s: State, ctx: Context, object: &ObjBody) -> Result<ObjValue> {279 Ok(match object {280 ObjBody::MemberList(members) => evaluate_member_list_object(s, ctx, members)?,281 ObjBody::ObjComp(obj) => {282 let mut builder = ObjValueBuilder::new();283 let locals = Rc::new(284 obj.pre_locals285 .iter()286 .chain(obj.post_locals.iter())287 .cloned()288 .collect::<Vec<_>>(),289 );290 let mut ctxs = vec![];291 evaluate_comp(s.clone(), ctx, &obj.compspecs, &mut |ctx| {292 let key = evaluate(s.clone(), ctx.clone(), &obj.key)?;293 let fctx = Context::new_future();294 ctxs.push((ctx, fctx.clone()));295 let uctx = evaluate_object_locals(fctx, locals.clone());296297 match key {298 Val::Null => {}299 Val::Str(n) => {300 #[derive(Trace)]301 struct UnboundValue<B: Trace> {302 uctx: B,303 value: LocExpr,304 }305 impl<B: Unbound<Bound = Context>> Unbound for UnboundValue<B> {306 type Bound = Thunk<Val>;307 fn bind(308 &self,309 s: State,310 sup: Option<ObjValue>,311 this: Option<ObjValue>,312 ) -> Result<Thunk<Val>> {313 Ok(Thunk::evaluated(evaluate(314 s.clone(),315 self.uctx.bind(s, sup, this.clone())?.extend(316 GcHashMap::new(),317 None,318 None,319 this,320 ),321 &self.value,322 )?))323 }324 }325 builder326 .member(n)327 .with_location(obj.value.1.clone())328 .with_add(obj.plus)329 .bindable(330 s.clone(),331 tb!(UnboundValue {332 uctx,333 value: obj.value.clone(),334 }),335 )?;336 }337 v => throw!(FieldMustBeStringGot(v.value_type())),338 }339340 Ok(())341 })?;342343 let this = builder.build();344 for (ctx, fctx) in ctxs {345 let _ctx = ctx346 .extend(GcHashMap::new(), None, None, Some(this.clone()))347 .into_future(fctx);348 }349 this350 }351 })352}353354pub fn evaluate_apply(355 s: State,356 ctx: Context,357 value: &LocExpr,358 args: &ArgsDesc,359 loc: CallLocation,360 tailstrict: bool,361) -> Result<Val> {362 let value = evaluate(s.clone(), ctx.clone(), value)?;363 Ok(match value {364 Val::Func(f) => {365 let body = || f.evaluate(s.clone(), ctx, loc, args, tailstrict);366 if tailstrict {367 body()?368 } else {369 s.push(loc, || format!("function <{}> call", f.name()), body)?370 }371 }372 v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),373 })374}375376pub fn evaluate_assert(s: State, ctx: Context, assertion: &AssertStmt) -> Result<()> {377 let value = &assertion.0;378 let msg = &assertion.1;379 let assertion_result = s.push(380 CallLocation::new(&value.1),381 || "assertion condition".to_owned(),382 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),383 )?;384 if !assertion_result {385 s.push(386 CallLocation::new(&value.1),387 || "assertion failure".to_owned(),388 || {389 if let Some(msg) = msg {390 throw!(AssertionFailed(391 evaluate(s.clone(), ctx, msg)?.to_string(s.clone())?392 ));393 }394 throw!(AssertionFailed(Val::Null.to_string(s.clone())?));395 },396 )?;397 }398 Ok(())399}400401pub fn evaluate_named(s: State, ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {402 use Expr::*;403 let LocExpr(raw_expr, _loc) = expr;404 Ok(match &**raw_expr {405 Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),406 _ => evaluate(s, ctx, expr)?,407 })408}409410#[allow(clippy::too_many_lines)]411pub fn evaluate(s: State, ctx: Context, expr: &LocExpr) -> Result<Val> {412 use Expr::*;413 let LocExpr(expr, loc) = expr;414 // let bp = with_state(|s| s.0.stop_at.borrow().clone());415 Ok(match &**expr {416 Literal(LiteralType::This) => {417 Val::Obj(ctx.this().clone().ok_or(CantUseSelfOutsideOfObject)?)418 }419 Literal(LiteralType::Super) => Val::Obj(420 ctx.super_obj().clone().ok_or(NoSuperFound)?.with_this(421 ctx.this()422 .clone()423 .expect("if super exists - then this should to"),424 ),425 ),426 Literal(LiteralType::Dollar) => {427 Val::Obj(ctx.dollar().clone().ok_or(NoTopLevelObjectFound)?)428 }429 Literal(LiteralType::True) => Val::Bool(true),430 Literal(LiteralType::False) => Val::Bool(false),431 Literal(LiteralType::Null) => Val::Null,432 Parened(e) => evaluate(s, ctx, e)?,433 Str(v) => Val::Str(v.clone()),434 Num(v) => Val::new_checked_num(*v)?,435 BinaryOp(v1, o, v2) => evaluate_binary_op_special(s, ctx, v1, *o, v2)?,436 UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,437 Var(name) => s.push(438 CallLocation::new(loc),439 || format!("variable <{name}> access"),440 || ctx.binding(name.clone())?.evaluate(s.clone()),441 )?,442 Index(value, index) => {443 match (444 evaluate(s.clone(), ctx.clone(), value)?,445 evaluate(s.clone(), ctx, index)?,446 ) {447 (Val::Obj(v), Val::Str(key)) => s.push(448 CallLocation::new(loc),449 || format!("field <{key}> access"),450 || match v.get(s.clone(), key.clone()) {451 Ok(Some(v)) => Ok(v),452 #[cfg(not(feature = "friendly-errors"))]453 Ok(None) => throw!(NoSuchField(key.clone(), vec![])),454 #[cfg(feature = "friendly-errors")]455 Ok(None) => {456 let mut heap = Vec::new();457 for field in v.fields_ex(458 true,459 #[cfg(feature = "exp-preserve-order")]460 false,461 ) {462 let conf = strsim::jaro_winkler(&field as &str, &key as &str);463 if conf < 0.8 {464 continue;465 }466 heap.push((conf, field));467 }468 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));469470 throw!(NoSuchField(471 key.clone(),472 heap.into_iter().map(|(_, v)| v).collect()473 ))474 }475 Err(e) => Err(e),476 },477 )?,478 (Val::Obj(_), n) => throw!(ValueIndexMustBeTypeGot(479 ValType::Obj,480 ValType::Str,481 n.value_type(),482 )),483484 (Val::Arr(v), Val::Num(n)) => {485 if n.fract() > f64::EPSILON {486 throw!(FractionalIndex)487 }488 v.get(s, n as usize)?489 .ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?490 }491 (Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),492 (Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(493 ValType::Arr,494 ValType::Num,495 n.value_type(),496 )),497498 (Val::Str(s), Val::Num(n)) => Val::Str({499 let v: IStr = s500 .chars()501 .skip(n as usize)502 .take(1)503 .collect::<String>()504 .into();505 if v.is_empty() {506 let size = s.chars().count();507 throw!(StringBoundsError(n as usize, size))508 }509 v510 }),511 (Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(512 ValType::Str,513 ValType::Num,514 n.value_type(),515 )),516517 (v, _) => throw!(CantIndexInto(v.value_type())),518 }519 }520 LocalExpr(bindings, returned) => {521 let mut new_bindings: GcHashMap<IStr, Thunk<Val>> =522 GcHashMap::with_capacity(bindings.len());523 let fctx = Context::new_future();524 for b in bindings {525 evaluate_dest(b, fctx.clone(), &mut new_bindings)?;526 }527 let ctx = ctx.extend(new_bindings, None, None, None).into_future(fctx);528 evaluate(s, ctx, &returned.clone())?529 }530 Arr(items) => {531 let mut out = Vec::with_capacity(items.len());532 for item in items {533 // TODO: Implement ArrValue::Lazy with same context for every element?534 #[derive(Trace)]535 struct ArrayElement {536 ctx: Context,537 item: LocExpr,538 }539 impl ThunkValue for ArrayElement {540 type Output = Val;541 fn get(self: Box<Self>, s: State) -> Result<Val> {542 evaluate(s, self.ctx, &self.item)543 }544 }545 out.push(Thunk::new(tb!(ArrayElement {546 ctx: ctx.clone(),547 item: item.clone(),548 })));549 }550 Val::Arr(out.into())551 }552 ArrComp(expr, comp_specs) => {553 let mut out = Vec::new();554 evaluate_comp(s.clone(), ctx, comp_specs, &mut |ctx| {555 out.push(evaluate(s.clone(), ctx, expr)?);556 Ok(())557 })?;558 Val::Arr(ArrValue::Eager(Cc::new(out)))559 }560 Obj(body) => Val::Obj(evaluate_object(s, ctx, body)?),561 ObjExtend(a, b) => evaluate_add_op(562 s.clone(),563 &evaluate(s.clone(), ctx.clone(), a)?,564 &Val::Obj(evaluate_object(s, ctx, b)?),565 )?,566 Apply(value, args, tailstrict) => {567 evaluate_apply(s, ctx, value, args, CallLocation::new(loc), *tailstrict)?568 }569 Function(params, body) => {570 evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())571 }572 AssertExpr(assert, returned) => {573 evaluate_assert(s.clone(), ctx.clone(), assert)?;574 evaluate(s, ctx, returned)?575 }576 ErrorStmt(e) => s.push(577 CallLocation::new(loc),578 || "error statement".to_owned(),579 || {580 throw!(RuntimeError(581 evaluate(s.clone(), ctx, e)?.to_string(s.clone())?,582 ))583 },584 )?,585 IfElse {586 cond,587 cond_then,588 cond_else,589 } => {590 if s.push(591 CallLocation::new(loc),592 || "if condition".to_owned(),593 || bool::from_untyped(evaluate(s.clone(), ctx.clone(), &cond.0)?, s.clone()),594 )? {595 evaluate(s, ctx, cond_then)?596 } else {597 match cond_else {598 Some(v) => evaluate(s, ctx, v)?,599 None => Val::Null,600 }601 }602 }603 Slice(value, desc) => {604 fn parse_idx<T: Typed>(605 loc: CallLocation,606 s: State,607 ctx: &Context,608 expr: &Option<LocExpr>,609 desc: &'static str,610 ) -> Result<Option<T>> {611 if let Some(value) = expr {612 Ok(Some(s.push(613 loc,614 || format!("slice {desc}"),615 || T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),616 )?))617 } else {618 Ok(None)619 }620 }621622 let indexable = evaluate(s.clone(), ctx.clone(), value)?;623 let loc = CallLocation::new(loc);624625 let start = parse_idx(loc, s.clone(), &ctx, &desc.start, "start")?;626 let end = parse_idx(loc, s.clone(), &ctx, &desc.end, "end")?;627 let step = parse_idx(loc, s.clone(), &ctx, &desc.step, "step")?;628629 IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?, s)?630 }631 i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {632 let tmp = loc.clone().0;633 let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;634 match i {635 Import(_) => s.push(636 CallLocation::new(loc),637 || format!("import {:?}", path.clone()),638 || s.import_resolved(resolved_path),639 )?,640 ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),641 ImportBin(_) => Val::Arr(ArrValue::Bytes(s.import_resolved_bin(resolved_path)?)),642 _ => unreachable!(),643 }644 }645 })646}crates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -24,7 +24,13 @@
/// Parameter names for named calls
fn params(&self) -> &[BuiltinParam];
/// Call the builtin
- fn call(&self, s: State, ctx: Context, loc: CallLocation, args: &dyn ArgsLike) -> Result<Val>;
+ fn call(
+ &self,
+ s: State,
+ ctx: Context,
+ loc: CallLocation<'_>,
+ args: &dyn ArgsLike,
+ ) -> Result<Val>;
}
pub trait StaticBuiltin: Builtin + Send + Sync
@@ -70,7 +76,13 @@
&self.params
}
- fn call(&self, s: State, ctx: Context, _loc: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
+ fn call(
+ &self,
+ s: State,
+ ctx: Context,
+ _loc: CallLocation<'_>,
+ args: &dyn ArgsLike,
+ ) -> Result<Val> {
let args = parse_builtin_call(s.clone(), ctx, &self.params, args, true)?;
let args = args
.into_iter()
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -18,43 +18,50 @@
pub mod native;
pub mod parse;
+/// Function callsite location.
+/// Either from other jsonnet code, specified by expression location, or from native (without location).
#[derive(Clone, Copy)]
pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
impl<'l> CallLocation<'l> {
+ /// Construct new location for calls coming from specified jsonnet expression location.
pub const fn new(loc: &'l ExprLocation) -> Self {
Self(Some(loc))
}
}
impl CallLocation<'static> {
+ /// Construct new location for calls coming from native code.
pub const fn native() -> Self {
Self(None)
}
}
-/// Function implemented in jsonnet
+/// Represents Jsonnet function defined in code.
#[derive(Debug, PartialEq, Trace)]
pub struct FuncDesc {
- /// In expressions like
+ /// # Example
+ ///
+ /// In expressions like this, deducted to `a`, unspecified otherwise.
/// ```jsonnet
/// local a = function() ...
/// local a() ...
/// { a: function() ... }
/// { a() = ... }
/// ```
- ///
- /// Deducted to `a`, unspecified otherwise
pub name: IStr,
- /// Context, in which this function was evaluated
+ /// Context, in which this function was evaluated.
///
- /// I.e in
+ /// # Example
+ /// In
/// ```jsonnet
/// local a = 2;
/// function() ...
/// ```
- /// context will contain `a`
+ /// context will contain `a`.
pub ctx: Context,
+ /// Function parameter definition
pub params: ParamsDesc,
+ /// Function body
pub body: LocExpr,
}
impl FuncDesc {
@@ -82,17 +89,17 @@
}
}
-/// Any possible function value, including plain functions and user-provided builtins
+/// Represents a Jsonnet function value, including plain functions and user-provided builtins.
#[allow(clippy::module_name_repetitions)]
#[derive(Trace, Clone)]
pub enum FuncVal {
- /// std.id
+ /// Identity function, kept this way for comparsions.
Id,
- /// Plain function implemented in jsonnet
+ /// Plain function implemented in jsonnet.
Normal(Cc<FuncDesc>),
- /// Standard library function
+ /// Standard library function.
StaticBuiltin(#[trace(skip)] &'static dyn StaticBuiltin),
- /// User-provided function
+ /// User-provided function.
Builtin(Cc<TraceBox<dyn Builtin>>),
}
@@ -110,9 +117,7 @@
}
impl FuncVal {
- pub fn into_native<D: NativeDesc>(self) -> D::Value {
- D::into_native(self)
- }
+ /// Amount of non-default required arguments
pub fn params_len(&self) -> usize {
match self {
Self::Id => 1,
@@ -121,6 +126,7 @@
Self::Builtin(i) => i.params().iter().filter(|p| !p.has_default).count(),
}
}
+ /// Function name, as defined in code.
pub fn name(&self) -> IStr {
match self {
Self::Id => "id".into(),
@@ -129,11 +135,14 @@
Self::Builtin(builtin) => builtin.name().into(),
}
}
+ /// Call function using arguments evaluated in specified `call_ctx` [`Context`].
+ ///
+ /// If `tailstrict` is specified - then arguments will be evaluated before being passed to function body.
pub fn evaluate(
&self,
s: State,
call_ctx: Context,
- loc: CallLocation,
+ loc: CallLocation<'_>,
args: &dyn ArgsLike,
tailstrict: bool,
) -> Result<Val> {
@@ -156,13 +165,22 @@
Self::Builtin(b) => b.call(s, call_ctx, loc, args),
}
}
+ /// Helper method, which calls [`Self::evaluate`] with sensible defaults for native code.
pub fn evaluate_simple(&self, s: State, args: &dyn ArgsLike) -> Result<Val> {
self.evaluate(s, Context::default(), CallLocation::native(), args, true)
}
+ /// Convert jsonnet function to plain `Fn` value.
+ pub fn into_native<D: NativeDesc>(self) -> D::Value {
+ D::into_native(self)
+ }
+ /// Is this function an indentity function.
+ ///
+ /// Currently only works for builtin `std.id`, aka `Self::Id` value, `function(x) x` defined by jsonnet will not count as identity.
pub const fn is_identity(&self) -> bool {
matches!(self, Self::Id)
}
+ /// Identity function value.
pub const fn identity() -> Self {
Self::Id
}
crates/jrsonnet-evaluator/src/gc.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/gc.rs
+++ b/crates/jrsonnet-evaluator/src/gc.rs
@@ -22,7 +22,7 @@
}
impl<T: ?Sized + Trace> Trace for TraceBox<T> {
- fn trace(&self, tracer: &mut Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
self.0.trace(tracer);
}
@@ -92,7 +92,7 @@
where
V: Trace,
{
- fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
for v in &self.0 {
v.trace(tracer);
}
@@ -133,7 +133,7 @@
K: Trace,
V: Trace,
{
- fn trace(&self, tracer: &mut jrsonnet_gcmodule::Tracer) {
+ fn trace(&self, tracer: &mut Tracer<'_>) {
for (k, v) in &self.0 {
k.trace(tracer);
v.trace(tracer);
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -1,4 +1,18 @@
-#![warn(clippy::all, clippy::nursery, clippy::pedantic)]
+//! jsonnet interpreter implementation
+
+#![deny(unsafe_op_in_unsafe_fn)]
+#![warn(
+ clippy::all,
+ clippy::nursery,
+ clippy::pedantic,
+ // missing_docs,
+ elided_lifetimes_in_paths,
+ explicit_outlives_requirements,
+ noop_method_call,
+ single_use_lifetimes,
+ variant_size_differences,
+ rustdoc::all
+)]
#![allow(
macro_expanded_macro_exports_accessed_by_absolute_paths,
clippy::ptr_arg,
@@ -67,23 +81,32 @@
use trace::{CompactFormat, TraceFormat};
pub use val::{ManifestFormat, Thunk, Val};
+/// Thunk without bound `super`/`this`
+/// object inheritance may be overriden multiple times, and will be fixed only on field read
pub trait Unbound: Trace {
+ /// Type of value after object context is bound
type Bound;
+ /// Create value bound to specified object context
fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<Self::Bound>;
}
+/// Object fields may, or may not depend on `this`/`super`, this enum allows cheaper reuse of object-independent fields for native code
+/// Standard jsonnet fields are always unbound
#[derive(Clone, Trace)]
-pub enum LazyBinding {
- Bindable(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+pub enum MaybeUnbound {
+ /// Value needs to be bound to `this`/`super`
+ Unbound(Cc<TraceBox<dyn Unbound<Bound = Thunk<Val>>>>),
+ /// Value is object-independent
Bound(Thunk<Val>),
}
-impl Debug for LazyBinding {
+impl Debug for MaybeUnbound {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "LazyBinding")
+ write!(f, "MaybeUnbound")
}
}
-impl LazyBinding {
+impl MaybeUnbound {
+ /// Attach object context to value, if required
pub fn evaluate(
&self,
s: State,
@@ -91,17 +114,19 @@
this: Option<ObjValue>,
) -> Result<Thunk<Val>> {
match self {
- Self::Bindable(v) => v.bind(s, sup, this),
+ Self::Unbound(v) => v.bind(s, sup, this),
Self::Bound(v) => Ok(v.clone()),
}
}
}
-/// During import, this trait will be called to create initial context for file
-/// It may initialize global variables, stdlib for example
+/// During import, this trait will be called to create initial context for file.
+/// It may initialize global variables, stdlib for example.
pub trait ContextInitializer {
+ /// Initialize default file context.
fn initialize(&self, state: State, for_file: Source) -> Context;
-
+ /// Allows upcasting from abstract to concrete context initializer.
+ /// jrsonnet by itself doesn't use this method, it is allowed for it to panic.
fn as_any(&self) -> &dyn Any;
}
@@ -116,6 +141,7 @@
}
}
+/// Dynamically reconfigurable evaluation settings
pub struct EvaluationSettings {
/// Limits recursion by limiting the number of stack frames
pub max_stack: usize,
@@ -401,7 +427,7 @@
/// Executes code creating a new stack frame
pub fn push<T>(
&self,
- e: CallLocation,
+ e: CallLocation<'_>,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
) -> Result<T> {
@@ -547,16 +573,13 @@
/// Internals
impl State {
- // fn data(&self) -> Ref<EvaluationData> {
- // self.0.data.borrow()
- // }
- fn data_mut(&self) -> RefMut<EvaluationData> {
+ fn data_mut(&self) -> RefMut<'_, EvaluationData> {
self.0.data.borrow_mut()
}
- pub fn settings(&self) -> Ref<EvaluationSettings> {
+ pub fn settings(&self) -> Ref<'_, EvaluationSettings> {
self.0.settings.borrow()
}
- pub fn settings_mut(&self) -> RefMut<EvaluationSettings> {
+ pub fn settings_mut(&self) -> RefMut<'_, EvaluationSettings> {
self.0.settings.borrow_mut()
}
}
@@ -623,13 +646,13 @@
pub fn resolve(&self, path: impl AsRef<Path>) -> Result<SourcePath> {
self.import_resolver().resolve(path.as_ref())
}
- pub fn import_resolver(&self) -> Ref<dyn ImportResolver> {
+ pub fn import_resolver(&self) -> Ref<'_, dyn ImportResolver> {
Ref::map(self.settings(), |s| &*s.import_resolver)
}
pub fn set_import_resolver(&self, resolver: Box<dyn ImportResolver>) {
self.settings_mut().import_resolver = resolver;
}
- pub fn context_initializer(&self) -> Ref<dyn ContextInitializer> {
+ pub fn context_initializer(&self) -> Ref<'_, dyn ContextInitializer> {
Ref::map(self.settings(), |s| &*s.context_initializer)
}
@@ -640,7 +663,7 @@
self.settings_mut().manifest_format = format;
}
- pub fn trace_format(&self) -> Ref<dyn TraceFormat> {
+ pub fn trace_format(&self) -> Ref<'_, dyn TraceFormat> {
Ref::map(self.settings(), |s| &*s.trace_format)
}
pub fn set_trace_format(&self, format: Box<dyn TraceFormat>) {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -15,7 +15,7 @@
function::CallLocation,
gc::{GcHashMap, GcHashSet, TraceBox},
operator::evaluate_add_op,
- throw, LazyBinding, Result, State, Thunk, Unbound, Val,
+ throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -100,7 +100,7 @@
pub add: bool,
pub visibility: Visibility,
original_index: FieldIndex,
- pub invoke: LazyBinding,
+ pub invoke: MaybeUnbound,
pub location: Option<ExprLocation>,
}
@@ -208,7 +208,7 @@
new.insert(key, value);
Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))
}
- pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder> {
+ pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {
ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())
}
@@ -239,6 +239,8 @@
}
/// Run callback for every field found in object
+ ///
+ /// Returns true if ended prematurely
pub(crate) fn enum_fields(
&self,
depth: SuperDepth,
@@ -500,7 +502,7 @@
self.assertions.push(assertion);
self
}
- pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {
+ pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {
let field_index = self.next_field_index;
self.next_field_index = self.next_field_index.next();
ObjMemberBuilder::new(ValueBuilder(self), name, field_index)
@@ -558,7 +560,7 @@
self.location = Some(location);
self
}
- fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {
+ fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {
(
self.kind,
self.name,
@@ -574,18 +576,18 @@
}
pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);
-impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {
+impl ObjMemberBuilder<ValueBuilder<'_>> {
pub fn value(self, s: State, value: Val) -> Result<()> {
- self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))
+ self.binding(s, MaybeUnbound::Bound(Thunk::evaluated(value)))
}
pub fn bindable(
self,
s: State,
bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,
) -> Result<()> {
- self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))
+ self.binding(s, MaybeUnbound::Unbound(Cc::new(bindable)))
}
- pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {
+ pub fn binding(self, s: State, binding: MaybeUnbound) -> Result<()> {
let (receiver, name, member) = self.build_member(binding);
let location = member.location.clone();
let old = receiver.0.map.insert(name.clone(), member);
@@ -601,14 +603,14 @@
}
pub struct ExtendBuilder<'v>(&'v mut ObjValue);
-impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {
+impl ObjMemberBuilder<ExtendBuilder<'_>> {
pub fn value(self, value: Val) {
- self.binding(LazyBinding::Bound(Thunk::evaluated(value)));
+ self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));
}
pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {
- self.binding(LazyBinding::Bindable(Cc::new(bindable)));
+ self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));
}
- pub fn binding(self, binding: LazyBinding) {
+ pub fn binding(self, binding: MaybeUnbound) {
let (receiver, name, member) = self.build_member(binding);
let new = receiver.0.clone();
*receiver.0 = new.extend_with_raw_member(name, member);
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -36,7 +36,7 @@
type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;
-pub fn try_parse_mapping_key(str: &str) -> ParseResult<&str> {
+pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -96,7 +96,7 @@
pub sign: bool,
}
-pub fn try_parse_cflags(str: &str) -> ParseResult<CFlags> {
+pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -125,7 +125,7 @@
Star,
Fixed(usize),
}
-pub fn try_parse_field_width(str: &str) -> ParseResult<Width> {
+pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -146,7 +146,7 @@
Ok((Width::Fixed(out), &str[digits..]))
}
-pub fn try_parse_precision(str: &str) -> ParseResult<Option<Width>> {
+pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -159,7 +159,7 @@
}
// Only skips
-pub fn try_parse_length_modifier(str: &str) -> ParseResult<()> {
+pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -191,7 +191,7 @@
caps: bool,
}
-pub fn parse_conversion_type(str: &str) -> ParseResult<ConvType> {
+pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -226,7 +226,7 @@
convtype: ConvTypeV,
caps: bool,
}
-pub fn parse_code(str: &str) -> ParseResult<Code> {
+pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {
if str.is_empty() {
return Err(TruncatedFormatCode);
}
@@ -255,7 +255,7 @@
String(&'s str),
Code(Code<'s>),
}
-pub fn parse_codes(mut str: &str) -> Result<Vec<Element>> {
+pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {
let mut bytes = str.as_bytes();
let mut out = vec![];
let mut offset = 0;
@@ -475,7 +475,7 @@
s: State,
out: &mut String,
value: &Val,
- code: &Code,
+ code: &Code<'_>,
width: usize,
precision: Option<usize>,
) -> Result<()> {
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -116,7 +116,7 @@
|| {
let value = obj.get(s.clone(), field.clone())?.unwrap();
manifest_json_ex_buf(s.clone(), &value, buf, cur_padding, options)?;
- Ok(Val::Null)
+ Ok(())
},
)?;
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -186,16 +186,26 @@
}
}
+/// Represents a Jsonnet array value.
#[derive(Debug, Clone, Trace)]
// may contrain other ArrValue
#[trace(tracking(force))]
pub enum ArrValue {
+ /// Layout optimized byte array.
Bytes(#[trace(skip)] IBytes),
+ /// Every element is lazy evaluated.
Lazy(Cc<Vec<Thunk<Val>>>),
+ /// Every field is already evaluated.
Eager(Cc<Vec<Val>>),
+ /// Concatenation of two arrays of any kind.
Extended(Box<(Self, Self)>),
+ /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.
+ /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.
Range(i32, i32),
+ /// Sliced array view.
Slice(Box<Slice>),
+ /// Reversed array view.
+ /// Returned by `std.reverse(other)` call
Reversed(Box<Self>),
}
@@ -237,6 +247,7 @@
}))
}
+ /// Array length.
pub fn len(&self) -> usize {
match self {
Self::Bytes(i) => i.len(),
@@ -249,10 +260,14 @@
}
}
+ /// Is array contains no elements?
pub fn is_empty(&self) -> bool {
self.len() == 0
}
+ /// Get array element by index, evaluating it, if it is lazy.
+ ///
+ /// Returns `None` on out-of-bounds condition.
pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {
match self {
Self::Bytes(i) => i
@@ -297,6 +312,9 @@
}
}
+ /// Get array element by index, without evaluation.
+ ///
+ /// Returns `None` on out-of-bounds condition.
pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
match self {
Self::Bytes(i) => i
@@ -337,6 +355,7 @@
}
}
+ /// Evaluate all array elements, returning new array.
pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {
Ok(match self {
Self::Bytes(i) => {
@@ -389,6 +408,7 @@
})
}
+ /// Iterate over elements, evaluating them.
pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),
@@ -400,6 +420,7 @@
})
}
+ /// Iterate over elements, returning lazy values.
pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {
(0..self.len()).map(move |idx| match self {
Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),
@@ -411,11 +432,13 @@
})
}
+ /// Return a reversed view on current array.
#[must_use]
pub fn reversed(self) -> Self {
Self::Reversed(Box::new(self))
}
+ /// Return a new array, produced by passing every element of current array to specified callback function.
pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {
let mut out = Vec::with_capacity(self.len());
@@ -426,6 +449,7 @@
Ok(Self::Eager(Cc::new(out)))
}
+ /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.
pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {
let mut out = Vec::with_capacity(self.len());
@@ -460,12 +484,22 @@
}
}
+/// Represents a Jsonnet value, which can be spliced or indexed (string or array).
#[allow(clippy::module_name_repetitions)]
pub enum IndexableVal {
+ /// String.
Str(IStr),
+ /// Array.
Arr(ArrValue),
}
impl IndexableVal {
+ /// Slice the value.
+ ///
+ /// # Implementation
+ ///
+ /// For strings, will create a copy of specified interval.
+ ///
+ /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.
pub fn slice(
self,
index: Option<BoundedUsize<0, { i32::MAX as usize }>>,
@@ -511,14 +545,24 @@
}
}
+/// Represents any valid Jsonnet value.
#[derive(Debug, Clone, Trace)]
pub enum Val {
+ /// Represents a Jsonnet boolean.
Bool(bool),
+ /// Represents a Jsonnet null value.
Null,
+ /// Represents a Jsonnet string.
Str(IStr),
+ /// Represents a Jsonnet number.
+ /// Should be finite, and not NaN
+ /// This restriction isn't enforced by enum, as enum field can't be marked as private
Num(f64),
+ /// Represents a Jsonnet array.
Arr(ArrValue),
+ /// Represents a Jsonnet object.
Obj(ObjValue),
+ /// Represents a Jsonnet function.
Func(FuncVal),
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -52,91 +52,88 @@
builder.with_super(eval);
for (name, builtin) in [
- ("length".into(), builtin_length::INST),
+ ("length", builtin_length::INST),
// Types
- ("type".into(), builtin_type::INST),
- ("isString".into(), builtin_is_string::INST),
- ("isNumber".into(), builtin_is_number::INST),
- ("isBoolean".into(), builtin_is_boolean::INST),
- ("isObject".into(), builtin_is_object::INST),
- ("isArray".into(), builtin_is_array::INST),
- ("isFunction".into(), builtin_is_function::INST),
+ ("type", builtin_type::INST),
+ ("isString", builtin_is_string::INST),
+ ("isNumber", builtin_is_number::INST),
+ ("isBoolean", builtin_is_boolean::INST),
+ ("isObject", builtin_is_object::INST),
+ ("isArray", builtin_is_array::INST),
+ ("isFunction", builtin_is_function::INST),
// Arrays
- ("makeArray".into(), builtin_make_array::INST),
- ("slice".into(), builtin_slice::INST),
- ("map".into(), builtin_map::INST),
- ("flatMap".into(), builtin_flatmap::INST),
- ("filter".into(), builtin_filter::INST),
- ("foldl".into(), builtin_foldl::INST),
- ("foldr".into(), builtin_foldr::INST),
- ("range".into(), builtin_range::INST),
- ("join".into(), builtin_join::INST),
- ("reverse".into(), builtin_reverse::INST),
- ("any".into(), builtin_any::INST),
- ("all".into(), builtin_all::INST),
- ("member".into(), builtin_member::INST),
- ("count".into(), builtin_count::INST),
+ ("makeArray", builtin_make_array::INST),
+ ("slice", builtin_slice::INST),
+ ("map", builtin_map::INST),
+ ("flatMap", builtin_flatmap::INST),
+ ("filter", builtin_filter::INST),
+ ("foldl", builtin_foldl::INST),
+ ("foldr", builtin_foldr::INST),
+ ("range", builtin_range::INST),
+ ("join", builtin_join::INST),
+ ("reverse", builtin_reverse::INST),
+ ("any", builtin_any::INST),
+ ("all", builtin_all::INST),
+ ("member", builtin_member::INST),
+ ("count", builtin_count::INST),
// Math
- ("modulo".into(), builtin_modulo::INST),
- ("floor".into(), builtin_floor::INST),
- ("ceil".into(), builtin_ceil::INST),
- ("log".into(), builtin_log::INST),
- ("pow".into(), builtin_pow::INST),
- ("sqrt".into(), builtin_sqrt::INST),
- ("sin".into(), builtin_sin::INST),
- ("cos".into(), builtin_cos::INST),
- ("tan".into(), builtin_tan::INST),
- ("asin".into(), builtin_asin::INST),
- ("acos".into(), builtin_acos::INST),
- ("atan".into(), builtin_atan::INST),
- ("exp".into(), builtin_exp::INST),
- ("mantissa".into(), builtin_mantissa::INST),
- ("exponent".into(), builtin_exponent::INST),
+ ("modulo", builtin_modulo::INST),
+ ("floor", builtin_floor::INST),
+ ("ceil", builtin_ceil::INST),
+ ("log", builtin_log::INST),
+ ("pow", builtin_pow::INST),
+ ("sqrt", builtin_sqrt::INST),
+ ("sin", builtin_sin::INST),
+ ("cos", builtin_cos::INST),
+ ("tan", builtin_tan::INST),
+ ("asin", builtin_asin::INST),
+ ("acos", builtin_acos::INST),
+ ("atan", builtin_atan::INST),
+ ("exp", builtin_exp::INST),
+ ("mantissa", builtin_mantissa::INST),
+ ("exponent", builtin_exponent::INST),
// Operator
- ("mod".into(), builtin_mod::INST),
- ("primitiveEquals".into(), builtin_primitive_equals::INST),
- ("equals".into(), builtin_equals::INST),
- ("format".into(), builtin_format::INST),
+ ("mod", builtin_mod::INST),
+ ("primitiveEquals", builtin_primitive_equals::INST),
+ ("equals", builtin_equals::INST),
+ ("format", builtin_format::INST),
// Sort
- ("sort".into(), builtin_sort::INST),
+ ("sort", builtin_sort::INST),
// Hash
- ("md5".into(), builtin_md5::INST),
+ ("md5", builtin_md5::INST),
// Encoding
- ("encodeUTF8".into(), builtin_encode_utf8::INST),
- ("decodeUTF8".into(), builtin_decode_utf8::INST),
- ("base64".into(), builtin_base64::INST),
- ("base64Decode".into(), builtin_base64_decode::INST),
- (
- "base64DecodeBytes".into(),
- builtin_base64_decode_bytes::INST,
- ),
+ ("encodeUTF8", builtin_encode_utf8::INST),
+ ("decodeUTF8", builtin_decode_utf8::INST),
+ ("base64", builtin_base64::INST),
+ ("base64Decode", builtin_base64_decode::INST),
+ ("base64DecodeBytes", builtin_base64_decode_bytes::INST),
// Objects
- ("objectFieldsEx".into(), builtin_object_fields_ex::INST),
- ("objectHasEx".into(), builtin_object_has_ex::INST),
+ ("objectFieldsEx", builtin_object_fields_ex::INST),
+ ("objectHasEx", builtin_object_has_ex::INST),
// Manifest
- ("escapeStringJson".into(), builtin_escape_string_json::INST),
- ("manifestJsonEx".into(), builtin_manifest_json_ex::INST),
- ("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),
+ ("escapeStringJson", builtin_escape_string_json::INST),
+ ("manifestJsonEx", builtin_manifest_json_ex::INST),
+ ("manifestYamlDoc", builtin_manifest_yaml_doc::INST),
// Parsing
- ("parseJson".into(), builtin_parse_json::INST),
- ("parseYaml".into(), builtin_parse_yaml::INST),
+ ("parseJson", builtin_parse_json::INST),
+ ("parseYaml", builtin_parse_yaml::INST),
// Misc
- ("codepoint".into(), builtin_codepoint::INST),
- ("substr".into(), builtin_substr::INST),
- ("char".into(), builtin_char::INST),
- ("strReplace".into(), builtin_str_replace::INST),
- ("splitLimit".into(), builtin_splitlimit::INST),
- ("asciiUpper".into(), builtin_ascii_upper::INST),
- ("asciiLower".into(), builtin_ascii_lower::INST),
- ("findSubstr".into(), builtin_find_substr::INST),
- ("startsWith".into(), builtin_starts_with::INST),
- ("endsWith".into(), builtin_ends_with::INST),
+ ("codepoint", builtin_codepoint::INST),
+ ("substr", builtin_substr::INST),
+ ("char", builtin_char::INST),
+ ("strReplace", builtin_str_replace::INST),
+ ("splitLimit", builtin_splitlimit::INST),
+ ("asciiUpper", builtin_ascii_upper::INST),
+ ("asciiLower", builtin_ascii_lower::INST),
+ ("findSubstr", builtin_find_substr::INST),
+ ("startsWith", builtin_starts_with::INST),
+ ("endsWith", builtin_ends_with::INST),
]
.iter()
.cloned()
{
builder
- .member(name)
+ .member(name.into())
.hide()
.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))
.expect("no conflict");
tests/src/lib.rsdiffbeforeafterboth--- a/tests/src/lib.rs
+++ b/tests/src/lib.rs
@@ -1 +1 @@
-
+//! See tests/, suite/ and golden/ directories for tests