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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -545,9 +545,9 @@
}
Val::Arr(Rc::new(out))
}
- ArrComp(expr, compspecs) => Val::Arr(
- // First compspec should be forspec, so no "None" possible here
- Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), compspecs)?.unwrap()),
+ ArrComp(expr, comp_specs) => Val::Arr(
+ // First comp_spec should be for_spec, so no "None" possible here
+ Rc::new(evaluate_comp(context, &|ctx| evaluate(ctx, expr), comp_specs)?.unwrap()),
),
Obj(body) => Val::Obj(evaluate_object(context, body)?),
ObjExtend(s, t) => evaluate_add_op(
@@ -564,7 +564,7 @@
|| "assertion condition".to_owned(),
|| {
evaluate(context.clone(), &value)?
- .try_cast_bool("assertion condition should be boolean")
+ .try_cast_bool("assertion condition should be of type `boolean`")
},
)?;
if assertion_result {
@@ -580,7 +580,7 @@
|| "error statement".to_owned(),
|| {
throw!(RuntimeError(
- evaluate(context, e)?.try_cast_str("error text should be string")?,
+ evaluate(context, e)?.try_cast_str("error text should be of type `string`")?,
))
},
)?,
@@ -590,7 +590,7 @@
cond_else,
} => {
if evaluate(context.clone(), &cond.0)?
- .try_cast_bool("if condition should be boolean")?
+ .try_cast_bool("if condition should be of type `boolean`")?
{
evaluate(context, cond_then)?
} else {
@@ -603,7 +603,7 @@
Import(path) => {
let mut tmp = loc
.clone()
- .expect("imports can't be used without loc_data")
+ .expect("imports cannot be used without loc_data")
.0;
let import_location = Rc::make_mut(&mut tmp);
import_location.pop();
@@ -616,7 +616,7 @@
ImportStr(path) => {
let mut tmp = loc
.clone()
- .expect("imports can't be used without loc_data")
+ .expect("imports cannot be used without loc_data")
.0;
let import_location = Rc::make_mut(&mut tmp);
import_location.pop();
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.rsdiffbeforeafterboth1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LocExpr, ParamsDesc};13use std::{14 cell::RefCell,15 collections::HashMap,16 fmt::{Debug, Display},17 rc::Rc,18};1920enum LazyValInternals {21 Computed(Val),22 Waiting(Box<dyn Fn() -> Result<Val>>),23}24#[derive(Clone)]25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {27 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28 LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29 }30 pub fn new_resolved(val: Val) -> Self {31 LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32 }33 pub fn evaluate(&self) -> Result<Val> {34 let new_value = match &*self.0.borrow() {35 LazyValInternals::Computed(v) => return Ok(v.clone()),36 LazyValInternals::Waiting(f) => f()?,37 };38 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());39 Ok(new_value)40 }41}4243#[macro_export]44macro_rules! lazy_val {45 ($f: expr) => {46 $crate::LazyVal::new(Box::new($f))47 };48}49#[macro_export]50macro_rules! resolved_lazy_val {51 ($f: expr) => {52 $crate::LazyVal::new_resolved($f)53 };54}55impl Debug for LazyVal {56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57 write!(f, "Lazy")58 }59}60impl PartialEq for LazyVal {61 fn eq(&self, other: &Self) -> bool {62 Rc::ptr_eq(&self.0, &other.0)63 }64}6566#[derive(Debug, PartialEq)]67pub struct FuncDesc {68 pub name: Rc<str>,69 pub ctx: Context,70 pub params: ParamsDesc,71 pub body: LocExpr,72}7374#[derive(Debug)]75pub enum FuncVal {76 /// Plain function implemented in jsonnet77 Normal(FuncDesc),78 /// Standard library function79 Intristic(Rc<str>, Rc<str>),80 /// Library functions implemented in native81 NativeExt(Rc<str>, Rc<NativeCallback>),82}8384impl PartialEq for FuncVal {85 fn eq(&self, other: &Self) -> bool {86 match (self, other) {87 (FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,88 (FuncVal::Intristic(ans, an), FuncVal::Intristic(bns, bn)) => ans == bns && an == bn,89 (FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,90 (..) => false,91 }92 }93}94impl FuncVal {95 pub fn is_ident(&self) -> bool {96 matches!(&self, FuncVal::Intristic(ns, n) if ns as &str == "std" && n as &str == "id")97 }98 pub fn name(&self) -> Rc<str> {99 match self {100 FuncVal::Normal(normal) => normal.name.clone(),101 FuncVal::Intristic(ns, name) => format!("intristic.{}.{}", ns, name).into(),102 FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),103 }104 }105 pub fn evaluate(106 &self,107 call_ctx: Context,108 loc: &Option<ExprLocation>,109 args: &ArgsDesc,110 tailstrict: bool,111 ) -> Result<Val> {112 match self {113 FuncVal::Normal(func) => {114 let ctx = parse_function_call(115 call_ctx,116 Some(func.ctx.clone()),117 &func.params,118 args,119 tailstrict,120 )?;121 evaluate(ctx, &func.body)122 }123 FuncVal::Intristic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),124 FuncVal::NativeExt(_name, handler) => {125 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126 let mut out_args = Vec::with_capacity(handler.params.len());127 for p in handler.params.0.iter() {128 out_args.push(args.binding(p.0.clone())?.evaluate()?);129 }130 Ok(handler.call(&out_args)?)131 }132 }133 }134135 pub fn evaluate_map(136 &self,137 call_ctx: Context,138 args: &HashMap<Rc<str>, Val>,139 tailstrict: bool,140 ) -> Result<Val> {141 match self {142 FuncVal::Normal(func) => {143 let ctx = parse_function_call_map(144 call_ctx,145 Some(func.ctx.clone()),146 &func.params,147 args,148 tailstrict,149 )?;150 evaluate(ctx, &func.body)151 }152 FuncVal::Intristic(_, _) => todo!(),153 FuncVal::NativeExt(_, _) => todo!(),154 }155 }156157 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158 match self {159 FuncVal::Normal(func) => {160 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161 evaluate(ctx, &func.body)162 }163 FuncVal::Intristic(_, _) => todo!(),164 FuncVal::NativeExt(_, _) => todo!(),165 }166 }167}168169#[derive(Debug, Clone, Copy, PartialEq)]170pub enum ValType {171 Bool,172 Null,173 Str,174 Num,175 Arr,176 Obj,177 Func,178}179impl ValType {180 pub fn name(&self) -> &'static str {181 use ValType::*;182 match self {183 Bool => "boolean",184 Null => "null",185 Str => "string",186 Num => "number",187 Arr => "array",188 Obj => "object",189 Func => "function",190 }191 }192}193impl Display for ValType {194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {195 write!(f, "{}", self.name())196 }197}198199#[derive(Clone)]200pub enum ManifestFormat {201 YamlStream(Box<ManifestFormat>),202 Yaml(usize),203 Json(usize),204 String,205}206207#[derive(Debug, Clone)]208pub enum Val {209 Bool(bool),210 Null,211 Str(Rc<str>),212 Num(f64),213 Lazy(LazyVal),214 Arr(Rc<Vec<Val>>),215 Obj(ObjValue),216 Func(Rc<FuncVal>),217}218219macro_rules! matches_unwrap {220 ($e: expr, $p: pat, $r: expr) => {221 match $e {222 $p => $r,223 _ => panic!("no match"),224 }225 };226}227impl Val {228 /// Creates Val::Num after checking for overflow. As numbers are f64, we can just check for finity229 pub fn new_checked_num(num: f64) -> Result<Val> {230 if num.is_finite() {231 Ok(Val::Num(num))232 } else {233 throw!(RuntimeError("overflow".into()))234 }235 }236237 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {238 let this_type = self.value_type()?;239 if this_type != val_type {240 throw!(TypeMismatch(context, vec![val_type], this_type))241 } else {242 Ok(())243 }244 }245 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {246 self.assert_type(context, ValType::Bool)?;247 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))248 }249 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {250 self.assert_type(context, ValType::Str)?;251 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))252 }253 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {254 self.assert_type(context, ValType::Num)?;255 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))256 }257 pub fn inplace_unwrap(&mut self) -> Result<()> {258 while let Val::Lazy(lazy) = self {259 *self = lazy.evaluate()?;260 }261 Ok(())262 }263 pub fn unwrap_if_lazy(&self) -> Result<Self> {264 Ok(if let Val::Lazy(v) = self {265 v.evaluate()?.unwrap_if_lazy()?266 } else {267 self.clone()268 })269 }270 pub fn value_type(&self) -> Result<ValType> {271 Ok(match self {272 Val::Str(..) => ValType::Str,273 Val::Num(..) => ValType::Num,274 Val::Arr(..) => ValType::Arr,275 Val::Obj(..) => ValType::Obj,276 Val::Bool(_) => ValType::Bool,277 Val::Null => ValType::Null,278 Val::Func(..) => ValType::Func,279 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,280 })281 }282283 pub fn to_string(&self) -> Result<Rc<str>> {284 Ok(match self.unwrap_if_lazy()? {285 Val::Bool(true) => "true".into(),286 Val::Bool(false) => "false".into(),287 Val::Null => "null".into(),288 Val::Str(s) => s,289 v => manifest_json_ex(290 &v,291 &ManifestJsonOptions {292 padding: &"",293 mtype: ManifestType::ToString,294 },295 )?296 .into(),297 })298 }299300 /// Expects value to be object, outputs (key, manifested value) pairs301 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {302 let obj = match self {303 Val::Obj(obj) => obj,304 _ => throw!(MultiManifestOutputIsNotAObject),305 };306 let keys = obj.visible_fields();307 let mut out = Vec::with_capacity(keys.len());308 for key in keys {309 let value = obj310 .get(key.clone())?311 .expect("item in object")312 .manifest(ty)?;313 out.push((key, value));314 }315 Ok(out)316 }317318 /// Expects value to be array, outputs manifested values319 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {320 let arr = match self {321 Val::Arr(a) => a,322 _ => throw!(StreamManifestOutputIsNotAArray),323 };324 let mut out = Vec::with_capacity(arr.len());325 for i in arr.iter() {326 out.push(i.manifest(ty)?);327 }328 Ok(out)329 }330331 pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {332 Ok(match ty {333 ManifestFormat::YamlStream(format) => {334 let arr = match self {335 Val::Arr(a) => a,336 _ => throw!(StreamManifestOutputIsNotAArray),337 };338 let mut out = String::new();339340 match format as &ManifestFormat {341 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),342 ManifestFormat::String => throw!(StreamManifestCannotNestString),343 _ => {}344 };345346 if !arr.is_empty() {347 for v in arr.iter() {348 out.push_str("---\n");349 out.push_str(&v.manifest(format)?);350 out.push_str("\n");351 }352 out.push_str("...");353 }354355 out.into()356 }357 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,358 ManifestFormat::Json(padding) => self.to_json(*padding)?,359 ManifestFormat::String => match self {360 Val::Str(s) => s.clone(),361 _ => throw!(StringManifestOutputIsNotAString),362 },363 })364 }365366 /// For manifestification367 pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {368 manifest_json_ex(369 self,370 &ManifestJsonOptions {371 padding: &" ".repeat(padding),372 mtype: if padding == 0 {373 ManifestType::Minify374 } else {375 ManifestType::Manifest376 },377 },378 )379 .map(|s| s.into())380 }381382 /// Calls std.manifestJson383 #[cfg(feature = "faster")]384 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {385 manifest_json_ex(386 &self,387 &ManifestJsonOptions {388 padding: &" ".repeat(padding),389 mtype: ManifestType::Std,390 },391 )392 .map(|s| s.into())393 }394395 /// Calls std.manifestJson396 #[cfg(not(feature = "faster"))]397 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {398 with_state(|s| {399 let ctx = s400 .create_default_context()?401 .with_var("__tmp__to_json__".into(), self.clone())?;402 Ok(evaluate(403 ctx,404 &el!(Expr::Apply(405 el!(Expr::Index(406 el!(Expr::Var("std".into())),407 el!(Expr::Str("manifestJsonEx".into()))408 )),409 ArgsDesc(vec![410 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),411 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))412 ]),413 false414 )),415 )?416 .try_cast_str("to json")?)417 })418 }419 pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {420 with_state(|s| {421 let ctx = s422 .create_default_context()?423 .with_var("__tmp__to_json__".into(), self.clone());424 Ok(evaluate(425 ctx,426 &el!(Expr::Apply(427 el!(Expr::Index(428 el!(Expr::Var("std".into())),429 el!(Expr::Str("manifestYamlDoc".into()))430 )),431 ArgsDesc(vec![432 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),433 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))434 ]),435 false436 )),437 )?438 .try_cast_str("to json")?)439 })440 }441}442443fn is_function_like(val: &Val) -> bool {444 matches!(val, Val::Func(_))445}446447/// Implements std.primitiveEquals builtin448pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {449 Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {450 (Val::Bool(a), Val::Bool(b)) => a == b,451 (Val::Null, Val::Null) => true,452 (Val::Str(a), Val::Str(b)) => a == b,453 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,454 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(455 "primitiveEquals operates on primitive types, got array".into(),456 )),457 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(458 "primitiveEquals operates on primitive types, got object".into(),459 )),460 (a, b) if is_function_like(&a) && is_function_like(&b) => {461 throw!(RuntimeError("cannot test equality of functions".into()))462 }463 (_, _) => false,464 })465}466467/// Native implementation of std.equals468pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {469 let val_a = val_a.unwrap_if_lazy()?;470 let val_b = val_b.unwrap_if_lazy()?;471472 if val_a.value_type()? != val_b.value_type()? {473 return Ok(false);474 }475 match (val_a, val_b) {476 // Cant test for ptr equality, because all fields needs to be evaluated477 (Val::Arr(a), Val::Arr(b)) => {478 if a.len() != b.len() {479 return Ok(false);480 }481 for (a, b) in a.iter().zip(b.iter()) {482 if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {483 return Ok(false);484 }485 }486 Ok(true)487 }488 (Val::Obj(a), Val::Obj(b)) => {489 let fields = a.visible_fields();490 if fields != b.visible_fields() {491 return Ok(false);492 }493 for field in fields {494 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {495 return Ok(false);496 }497 }498 Ok(true)499 }500 (a, b) => Ok(primitive_equals(&a, &b)?),501 }502}1use crate::{2 builtin::{3 call_builtin,4 manifest::{manifest_json_ex, ManifestJsonOptions, ManifestType},5 },6 error::Error::*,7 evaluate,8 function::{parse_function_call, parse_function_call_map, place_args},9 native::NativeCallback,10 throw, with_state, Context, ObjValue, Result,11};12use jrsonnet_parser::{el, Arg, ArgsDesc, Expr, ExprLocation, LocExpr, ParamsDesc};13use std::{14 cell::RefCell,15 collections::HashMap,16 fmt::{Debug, Display},17 rc::Rc,18};1920enum LazyValInternals {21 Computed(Val),22 Waiting(Box<dyn Fn() -> Result<Val>>),23}24#[derive(Clone)]25pub struct LazyVal(Rc<RefCell<LazyValInternals>>);26impl LazyVal {27 pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {28 LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))29 }30 pub fn new_resolved(val: Val) -> Self {31 LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))32 }33 pub fn evaluate(&self) -> Result<Val> {34 let new_value = match &*self.0.borrow() {35 LazyValInternals::Computed(v) => return Ok(v.clone()),36 LazyValInternals::Waiting(f) => f()?,37 };38 *self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());39 Ok(new_value)40 }41}4243#[macro_export]44macro_rules! lazy_val {45 ($f: expr) => {46 $crate::LazyVal::new(Box::new($f))47 };48}49#[macro_export]50macro_rules! resolved_lazy_val {51 ($f: expr) => {52 $crate::LazyVal::new_resolved($f)53 };54}55impl Debug for LazyVal {56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57 write!(f, "Lazy")58 }59}60impl PartialEq for LazyVal {61 fn eq(&self, other: &Self) -> bool {62 Rc::ptr_eq(&self.0, &other.0)63 }64}6566#[derive(Debug, PartialEq)]67pub struct FuncDesc {68 pub name: Rc<str>,69 pub ctx: Context,70 pub params: ParamsDesc,71 pub body: LocExpr,72}7374#[derive(Debug)]75pub enum FuncVal {76 /// Plain function implemented in jsonnet77 Normal(FuncDesc),78 /// Standard library function79 Intristic(Rc<str>, Rc<str>),80 /// Library functions implemented in native81 NativeExt(Rc<str>, Rc<NativeCallback>),82}8384impl PartialEq for FuncVal {85 fn eq(&self, other: &Self) -> bool {86 match (self, other) {87 (FuncVal::Normal(a), FuncVal::Normal(b)) => a == b,88 (FuncVal::Intristic(ans, an), FuncVal::Intristic(bns, bn)) => ans == bns && an == bn,89 (FuncVal::NativeExt(an, _), FuncVal::NativeExt(bn, _)) => an == bn,90 (..) => false,91 }92 }93}94impl FuncVal {95 pub fn is_ident(&self) -> bool {96 matches!(&self, FuncVal::Intristic(ns, n) if ns as &str == "std" && n as &str == "id")97 }98 pub fn name(&self) -> Rc<str> {99 match self {100 FuncVal::Normal(normal) => normal.name.clone(),101 FuncVal::Intristic(ns, name) => format!("intristic.{}.{}", ns, name).into(),102 FuncVal::NativeExt(n, _) => format!("native.{}", n).into(),103 }104 }105 pub fn evaluate(106 &self,107 call_ctx: Context,108 loc: &Option<ExprLocation>,109 args: &ArgsDesc,110 tailstrict: bool,111 ) -> Result<Val> {112 match self {113 FuncVal::Normal(func) => {114 let ctx = parse_function_call(115 call_ctx,116 Some(func.ctx.clone()),117 &func.params,118 args,119 tailstrict,120 )?;121 evaluate(ctx, &func.body)122 }123 FuncVal::Intristic(ns, name) => call_builtin(call_ctx, loc, &ns, &name, args),124 FuncVal::NativeExt(_name, handler) => {125 let args = parse_function_call(call_ctx, None, &handler.params, args, true)?;126 let mut out_args = Vec::with_capacity(handler.params.len());127 for p in handler.params.0.iter() {128 out_args.push(args.binding(p.0.clone())?.evaluate()?);129 }130 Ok(handler.call(&out_args)?)131 }132 }133 }134135 pub fn evaluate_map(136 &self,137 call_ctx: Context,138 args: &HashMap<Rc<str>, Val>,139 tailstrict: bool,140 ) -> Result<Val> {141 match self {142 FuncVal::Normal(func) => {143 let ctx = parse_function_call_map(144 call_ctx,145 Some(func.ctx.clone()),146 &func.params,147 args,148 tailstrict,149 )?;150 evaluate(ctx, &func.body)151 }152 FuncVal::Intristic(_, _) => todo!(),153 FuncVal::NativeExt(_, _) => todo!(),154 }155 }156157 pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {158 match self {159 FuncVal::Normal(func) => {160 let ctx = place_args(call_ctx, Some(func.ctx.clone()), &func.params, args)?;161 evaluate(ctx, &func.body)162 }163 FuncVal::Intristic(_, _) => todo!(),164 FuncVal::NativeExt(_, _) => todo!(),165 }166 }167}168169#[derive(Debug, Clone, Copy, PartialEq)]170pub enum ValType {171 Bool,172 Null,173 Str,174 Num,175 Arr,176 Obj,177 Func,178}179impl ValType {180 pub fn name(&self) -> &'static str {181 use ValType::*;182 match self {183 Bool => "boolean",184 Null => "null",185 Str => "string",186 Num => "number",187 Arr => "array",188 Obj => "object",189 Func => "function",190 }191 }192}193impl Display for ValType {194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {195 write!(f, "{}", self.name())196 }197}198199#[derive(Clone)]200pub enum ManifestFormat {201 YamlStream(Box<ManifestFormat>),202 Yaml(usize),203 Json(usize),204 String,205}206207#[derive(Debug, Clone)]208pub enum Val {209 Bool(bool),210 Null,211 Str(Rc<str>),212 Num(f64),213 Lazy(LazyVal),214 Arr(Rc<Vec<Val>>),215 Obj(ObjValue),216 Func(Rc<FuncVal>),217}218219macro_rules! matches_unwrap {220 ($e: expr, $p: pat, $r: expr) => {221 match $e {222 $p => $r,223 _ => panic!("no match"),224 }225 };226}227impl Val {228 /// Creates `Val::Num` after checking for numeric overflow.229 /// As numbers are `f64`, we can just check for their finity.230 pub fn new_checked_num(num: f64) -> Result<Val> {231 if num.is_finite() {232 Ok(Val::Num(num))233 } else {234 throw!(RuntimeError("overflow".into()))235 }236 }237238 pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {239 let this_type = self.value_type()?;240 if this_type != val_type {241 throw!(TypeMismatch(context, vec![val_type], this_type))242 } else {243 Ok(())244 }245 }246 pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {247 self.assert_type(context, ValType::Bool)?;248 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))249 }250 pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {251 self.assert_type(context, ValType::Str)?;252 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))253 }254 pub fn try_cast_num(self, context: &'static str) -> Result<f64> {255 self.assert_type(context, ValType::Num)?;256 Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))257 }258 pub fn inplace_unwrap(&mut self) -> Result<()> {259 while let Val::Lazy(lazy) = self {260 *self = lazy.evaluate()?;261 }262 Ok(())263 }264 pub fn unwrap_if_lazy(&self) -> Result<Self> {265 Ok(if let Val::Lazy(v) = self {266 v.evaluate()?.unwrap_if_lazy()?267 } else {268 self.clone()269 })270 }271 pub fn value_type(&self) -> Result<ValType> {272 Ok(match self {273 Val::Str(..) => ValType::Str,274 Val::Num(..) => ValType::Num,275 Val::Arr(..) => ValType::Arr,276 Val::Obj(..) => ValType::Obj,277 Val::Bool(_) => ValType::Bool,278 Val::Null => ValType::Null,279 Val::Func(..) => ValType::Func,280 Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,281 })282 }283284 pub fn to_string(&self) -> Result<Rc<str>> {285 Ok(match self.unwrap_if_lazy()? {286 Val::Bool(true) => "true".into(),287 Val::Bool(false) => "false".into(),288 Val::Null => "null".into(),289 Val::Str(s) => s,290 v => manifest_json_ex(291 &v,292 &ManifestJsonOptions {293 padding: &"",294 mtype: ManifestType::ToString,295 },296 )?297 .into(),298 })299 }300301 /// Expects value to be object, outputs (key, manifested value) pairs302 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(Rc<str>, Rc<str>)>> {303 let obj = match self {304 Val::Obj(obj) => obj,305 _ => throw!(MultiManifestOutputIsNotAObject),306 };307 let keys = obj.visible_fields();308 let mut out = Vec::with_capacity(keys.len());309 for key in keys {310 let value = obj311 .get(key.clone())?312 .expect("item in object")313 .manifest(ty)?;314 out.push((key, value));315 }316 Ok(out)317 }318319 /// Expects value to be array, outputs manifested values320 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<Rc<str>>> {321 let arr = match self {322 Val::Arr(a) => a,323 _ => throw!(StreamManifestOutputIsNotAArray),324 };325 let mut out = Vec::with_capacity(arr.len());326 for i in arr.iter() {327 out.push(i.manifest(ty)?);328 }329 Ok(out)330 }331332 pub fn manifest(&self, ty: &ManifestFormat) -> Result<Rc<str>> {333 Ok(match ty {334 ManifestFormat::YamlStream(format) => {335 let arr = match self {336 Val::Arr(a) => a,337 _ => throw!(StreamManifestOutputIsNotAArray),338 };339 let mut out = String::new();340341 match format as &ManifestFormat {342 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),343 ManifestFormat::String => throw!(StreamManifestCannotNestString),344 _ => {}345 };346347 if !arr.is_empty() {348 for v in arr.iter() {349 out.push_str("---\n");350 out.push_str(&v.manifest(format)?);351 out.push_str("\n");352 }353 out.push_str("...");354 }355356 out.into()357 }358 ManifestFormat::Yaml(padding) => self.to_yaml(*padding)?,359 ManifestFormat::Json(padding) => self.to_json(*padding)?,360 ManifestFormat::String => match self {361 Val::Str(s) => s.clone(),362 _ => throw!(StringManifestOutputIsNotAString),363 },364 })365 }366367 /// For manifestification368 pub fn to_json(&self, padding: usize) -> Result<Rc<str>> {369 manifest_json_ex(370 self,371 &ManifestJsonOptions {372 padding: &" ".repeat(padding),373 mtype: if padding == 0 {374 ManifestType::Minify375 } else {376 ManifestType::Manifest377 },378 },379 )380 .map(|s| s.into())381 }382383 /// Calls `std.manifestJson`384 #[cfg(feature = "faster")]385 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {386 manifest_json_ex(387 &self,388 &ManifestJsonOptions {389 padding: &" ".repeat(padding),390 mtype: ManifestType::Std,391 },392 )393 .map(|s| s.into())394 }395396 /// Calls `std.manifestJson`397 #[cfg(not(feature = "faster"))]398 pub fn to_std_json(&self, padding: usize) -> Result<Rc<str>> {399 with_state(|s| {400 let ctx = s401 .create_default_context()?402 .with_var("__tmp__to_json__".into(), self.clone())?;403 Ok(evaluate(404 ctx,405 &el!(Expr::Apply(406 el!(Expr::Index(407 el!(Expr::Var("std".into())),408 el!(Expr::Str("manifestJsonEx".into()))409 )),410 ArgsDesc(vec![411 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),412 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))413 ]),414 false415 )),416 )?417 .try_cast_str("to json")?)418 })419 }420 pub fn to_yaml(&self, padding: usize) -> Result<Rc<str>> {421 with_state(|s| {422 let ctx = s423 .create_default_context()?424 .with_var("__tmp__to_json__".into(), self.clone());425 Ok(evaluate(426 ctx,427 &el!(Expr::Apply(428 el!(Expr::Index(429 el!(Expr::Var("std".into())),430 el!(Expr::Str("manifestYamlDoc".into()))431 )),432 ArgsDesc(vec![433 Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),434 Arg(None, el!(Expr::Str(" ".repeat(padding).into())))435 ]),436 false437 )),438 )?439 .try_cast_str("to json")?)440 })441 }442}443444fn is_function_like(val: &Val) -> bool {445 matches!(val, Val::Func(_))446}447448/// Native implementation of `std.primitiveEquals`449pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {450 Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {451 (Val::Bool(a), Val::Bool(b)) => a == b,452 (Val::Null, Val::Null) => true,453 (Val::Str(a), Val::Str(b)) => a == b,454 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,455 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(456 "primitiveEquals operates on primitive types, got array".into(),457 )),458 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(459 "primitiveEquals operates on primitive types, got object".into(),460 )),461 (a, b) if is_function_like(&a) && is_function_like(&b) => {462 throw!(RuntimeError("cannot test equality of functions".into()))463 }464 (_, _) => false,465 })466}467468/// Native implementation of `std.equals`469pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {470 let val_a = val_a.unwrap_if_lazy()?;471 let val_b = val_b.unwrap_if_lazy()?;472473 if val_a.value_type()? != val_b.value_type()? {474 return Ok(false);475 }476 match (val_a, val_b) {477 // Cant test for ptr equality, because all fields needs to be evaluated478 (Val::Arr(a), Val::Arr(b)) => {479 if a.len() != b.len() {480 return Ok(false);481 }482 for (a, b) in a.iter().zip(b.iter()) {483 if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {484 return Ok(false);485 }486 }487 Ok(true)488 }489 (Val::Obj(a), Val::Obj(b)) => {490 let fields = a.visible_fields();491 if fields != b.visible_fields() {492 return Ok(false);493 }494 for field in fields {495 if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {496 return Ok(false);497 }498 }499 Ok(true)500 }501 (a, b) => Ok(primitive_equals(&a, &b)?),502 }503}