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.rsdiffbeforeafterboth56}56}575758pub struct EvaluationSettings {58pub struct EvaluationSettings {59 /// Limits recursion by limiting stack frames59 /// Limits recursion by limiting the number of stack frames60 pub max_stack: usize,60 pub max_stack: usize,61 /// Limit amount of stack trace items preserved61 /// Limits amount of stack trace items preserved62 pub max_trace: usize,62 pub max_trace: usize,63 /// Used for std.extVar63 /// Used for s`td.extVar`64 pub ext_vars: HashMap<Rc<str>, Val>,64 pub ext_vars: HashMap<Rc<str>, Val>,65 /// Used for ext.native65 /// Used for ext.native66 pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,66 pub ext_natives: HashMap<Rc<str>, Rc<NativeCallback>>,969697#[derive(Default)]97#[derive(Default)]98struct EvaluationData {98struct EvaluationData {99 /// Used for stack overflow detection, stacktrace is now populated on unwind99 /// Used for stack overflow detection, stacktrace is populated on unwind100 stack_depth: usize,100 stack_depth: usize,101 /// Contains file source codes and evaluated results for imports and pretty101 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces102 /// printing stacktraces103 files: HashMap<Rc<PathBuf>, FileData>,102 files: HashMap<Rc<PathBuf>, FileData>,104 str_files: HashMap<Rc<PathBuf>, Rc<str>>,103 str_files: HashMap<Rc<PathBuf>, Rc<str>>,105}104}118}117}119118120thread_local! {119thread_local! {121 /// Contains state for currently executing file120 /// Contains the state for a currently executed file.122 /// Global state is fine there121 /// Global state is fine here.123 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)122 pub(crate) static EVAL_STATE: RefCell<Option<EvaluationState>> = RefCell::new(None)124}123}125pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {124pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {142pub struct EvaluationState(Rc<EvaluationStateInternals>);141pub struct EvaluationState(Rc<EvaluationStateInternals>);143142144impl EvaluationState {143impl EvaluationState {145 /// Parses and adds file to loaded144 /// Parses and adds files as loaded146 pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {145 pub fn add_file(&self, path: Rc<PathBuf>, source_code: Rc<str>) -> Result<()> {147 self.add_parsed_file(146 self.add_parsed_file(148 path.clone(),147 path.clone(),264 Context::new().extend_unbound(new_bindings, None, None, None)263 Context::new().extend_unbound(new_bindings, None, None, None)265 }264 }266265267 /// Executes code, creating new stack frame266 /// Executes code creating a new stack frame268 pub fn push<T>(267 pub fn push<T>(269 &self,268 &self,270 e: &ExprLocation,269 e: &ExprLocation,294 result293 result295 }294 }296295297 /// Runs passed function in state (required, if function needs to modify stack trace)296 /// Runs passed function in state (required if function needs to modify stack trace)298 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {297 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {299 EVAL_STATE.with(|v| {298 EVAL_STATE.with(|v| {300 let has_state = v.borrow().is_some();299 let has_state = v.borrow().is_some();328 self.run_in_state(|| val.manifest_stream(&self.manifest_format()))327 self.run_in_state(|| val.manifest_stream(&self.manifest_format()))329 }328 }330329331 /// If passed value is function - call with set TLA330 /// If passed value is function then call with set TLA332 pub fn with_tla(&self, val: Val) -> Result<Val> {331 pub fn with_tla(&self, val: Val) -> Result<Val> {333 Ok(match val {332 Ok(match val {334 Val::Func(func) => func.evaluate_map(333 Val::Func(func) => func.evaluate_map(357 }356 }358}357}359358360/// Raw methods evaluates passed values, but not performs TLA execution359/// Raw methods evaluate passed values but don't perform TLA execution361impl EvaluationState {360impl EvaluationState {362 pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {361 pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {363 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))362 self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), &name))364 }363 }365 pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {364 pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {366 self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))365 self.run_in_state(|| self.import_file(&PathBuf::from("."), &name))367 }366 }368 /// Parses and evaluates snippet367 /// Parses and evaluates the given snippet369 pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {368 pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: Rc<str>) -> Result<Val> {370 let parsed = parse(369 let parsed = parse(371 &code,370 &code,378 self.add_parsed_file(source, code, parsed.clone())?;377 self.add_parsed_file(source, code, parsed.clone())?;379 self.evaluate_expr_raw(parsed)378 self.evaluate_expr_raw(parsed)380 }379 }381 /// Evaluates parsed expression380 /// Evaluates the parsed expression382 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {381 pub fn evaluate_expr_raw(&self, code: LocExpr) -> Result<Val> {383 self.run_in_state(|| evaluate(self.create_default_context()?, &code))382 self.run_in_state(|| evaluate(self.create_default_context()?, &code))384 }383 }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()?;