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.rsdiffbeforeafterboth1mod location;23use crate::{EvaluationState, LocError};4pub use location::*;5use std::path::PathBuf;67/// How paths should be displayed8pub enum PathResolver {9 /// Only filename will be shown10 FileName,11 /// Absolute path of file12 Absolute,13 /// Relative path from base directory14 Relative(PathBuf),15}1617impl PathResolver {18 pub fn resolve(&self, from: &PathBuf) -> String {19 match self {20 PathResolver::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),21 PathResolver::Absolute => from.to_string_lossy().into_owned(),22 PathResolver::Relative(base) => {23 if from.is_relative() {24 return from.to_string_lossy().into_owned();25 }26 pathdiff::diff_paths(from, base)27 .unwrap()28 .to_string_lossy()29 .into_owned()30 }31 }32 }33}3435/// Implements trace to string pretty-printing36pub trait TraceFormat {37 fn write_trace(38 &self,39 out: &mut dyn std::fmt::Write,40 evaluation_state: &EvaluationState,41 error: &LocError,42 ) -> Result<(), std::fmt::Error>;43 // fn print_trace(44 // &self,45 // evaluation_state: &EvaluationState,46 // error: &LocError,47 // ) -> Result<(), std::fmt::Error> {48 // self.write_trace(&mut std::fmt::stdout(), evaluation_state, error)49 // }50}5152fn print_code_location(53 out: &mut impl std::fmt::Write,54 start: &CodeLocation,55 end: &CodeLocation,56) -> Result<(), std::fmt::Error> {57 if start.line == end.line {58 if start.column == end.column {59 write!(out, "{}:{}", start.line, end.column - 1)?;60 } else {61 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;62 }63 } else {64 write!(65 out,66 "{}:{}-{}:{}",67 start.line,68 end.column - 1,69 start.line,70 end.column71 )?;72 }73 Ok(())74}7576/// vanilla jsonnet like formatting77pub struct CompactFormat {78 pub resolver: PathResolver,79 pub padding: usize,80}8182impl TraceFormat for CompactFormat {83 fn write_trace(84 &self,85 out: &mut dyn std::fmt::Write,86 evaluation_state: &EvaluationState,87 error: &LocError,88 ) -> Result<(), std::fmt::Error> {89 writeln!(out, "{:?}", error.error())?;90 let file_names = error91 .trace()92 .093 .iter()94 .map(|el| {95 let resolved_path = self.resolver.resolve(&el.location.0);96 // TODO: Process all trace elements first97 let location = evaluation_state98 .map_source_locations(&el.location.0, &[el.location.1, el.location.2]);99 (resolved_path, location)100 })101 .map(|(mut n, location)| {102 use std::fmt::Write;103 write!(n, ":").unwrap();104 print_code_location(&mut n, &location[0], &location[1]).unwrap();105 n106 })107 .collect::<Vec<_>>();108 let align = file_names.iter().map(|e| e.len()).max().unwrap_or(0);109 for (i, (el, file)) in error.trace().0.iter().zip(file_names).enumerate() {110 if i != 0 {111 writeln!(out)?;112 }113 write!(114 out,115 "{:<p$}{:<w$}: {}",116 "",117 file,118 el.desc,119 p = self.padding,120 w = align121 )?;122 }123 Ok(())124 }125}126127pub struct JSFormat;128impl TraceFormat for JSFormat {129 fn write_trace(130 &self,131 out: &mut dyn std::fmt::Write,132 evaluation_state: &EvaluationState,133 error: &LocError,134 ) -> Result<(), std::fmt::Error> {135 writeln!(out, "{:?}", error.error())?;136 for (i, item) in error.trace().0.iter().enumerate() {137 if i != 0 {138 writeln!(out)?;139 }140 let desc = &item.desc;141 let source = item.location.clone();142 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);143144 write!(145 out,146 " at {} ({}:{}:{})",147 desc,148 source.0.to_str().unwrap(),149 start_end[0].line,150 start_end[0].column,151 )?;152 }153 Ok(())154 }155}156157/// rustc-like trace displaying158#[cfg(feature = "explaining-traces")]159pub struct ExplainingFormat {160 pub resolver: PathResolver,161}162#[cfg(feature = "explaining-traces")]163impl TraceFormat for ExplainingFormat {164 fn write_trace(165 &self,166 out: &mut dyn std::fmt::Write,167 evaluation_state: &EvaluationState,168 error: &LocError,169 ) -> Result<(), std::fmt::Error> {170 use annotate_snippets::{171 display_list::{DisplayList, FormatOptions},172 snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},173 };174 writeln!(out, "{:?}", error.error())?;175 let trace = &error.trace();176 for item in trace.0.iter() {177 let desc = &item.desc;178 let source = item.location.clone();179 let start_end = evaluation_state.map_source_locations(&source.0, &[source.1, source.2]);180181 let source_fragment: String = evaluation_state182 .get_source(&source.0)183 .unwrap()184 .chars()185 .skip(start_end[0].line_start_offset)186 .take(start_end[1].line_end_offset - start_end[0].line_start_offset)187 .collect();188189 let origin = self.resolver.resolve(&source.0);190 let snippet = Snippet {191 opt: FormatOptions {192 color: true,193 ..Default::default()194 },195 title: None,196 footer: vec![],197 slices: vec![Slice {198 source: &source_fragment,199 line_start: start_end[0].line,200 origin: Some(&origin),201 fold: false,202 annotations: vec![SourceAnnotation {203 label: desc,204 annotation_type: AnnotationType::Error,205 range: (206 source.1 - start_end[0].line_start_offset,207 source.2 - start_end[0].line_start_offset,208 ),209 }],210 }],211 };212213 let dl = DisplayList::from(snippet);214 writeln!(out, "{}", dl)?;215 }216 Ok(())217 }218}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()?;