git.delta.rocks / jrsonnet / refs/commits / f44bc09e725c

difftreelog

docs cleanup evaluator's docs

progrm_jarvis2020-08-07parent: #e9a9036.patch.diff
in: master

7 files changed

modifiedcrates/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")]
modifiedcrates/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();
modifiedcrates/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>,
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/import.rs
1use crate::{2	error::{Error::*, Result},3	throw,4};5use fs::File;6use std::fs;7use std::io::Read;8use std::{any::Any, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};910/// Implements file resolution logic for `import` and `importStr`11pub trait ImportResolver {12	/// Resolve real file path, i.e13	/// `(/home/user/manifests, b.libsonnet)` can resolve to both `/home/user/manifests/b.libsonnet` and to `/home/user/vendor/b.libsonnet`14	/// (Where vendor is a library path)15	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;16	/// Reads file from filesystem, should be used only with path received from `resolve_file`17	fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>>;18	/// # Safety19	///20	/// For use in bindings, do not try to use it elsewhere21	/// Implementations, which are not intended to be22	/// used in bindings, should panic in this method23	unsafe fn as_any(&self) -> &dyn Any;24}2526/// Dummy resolver, can't resolve/load any file27pub struct DummyImportResolver;28impl ImportResolver for DummyImportResolver {29	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {30		throw!(ImportNotSupported(from.clone(), path.clone()))31	}32	fn load_file_contents(&self, _resolved: &PathBuf) -> Result<Rc<str>> {33		// Can be only caused by library direct consumer, not by supplied jsonnet34		panic!("dummy resolver can't load any file")35	}36	unsafe fn as_any(&self) -> &dyn Any {37		panic!("this resolver can't be used as any")38	}39}40impl Default for Box<dyn ImportResolver> {41	fn default() -> Self {42		Box::new(DummyImportResolver)43	}44}4546/// File resolver, can load file from both FS and library paths47#[derive(Default)]48pub struct FileImportResolver {49	/// Library directories to search for file50	/// In original jsonnet referred as jpath51	pub library_paths: Vec<PathBuf>,52}53impl ImportResolver for FileImportResolver {54	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {55		let mut new_path = from.clone();56		new_path.push(path);57		if new_path.exists() {58			Ok(Rc::new(new_path))59		} else {60			for library_path in self.library_paths.iter() {61				let mut cloned = library_path.clone();62				cloned.push(path);63				if cloned.exists() {64					return Ok(Rc::new(cloned));65				}66			}67			throw!(ImportFileNotFound(from.clone(), path.clone()))68		}69	}70	fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {71		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;72		let mut out = String::new();73		file.read_to_string(&mut out)74			.map_err(|_e| ImportBadFileUtf8(id.clone()))?;75		Ok(out.into())76	}77	unsafe fn as_any(&self) -> &dyn Any {78		panic!("this resolver can't be used as any")79	}80}8182type ResolutionData = (PathBuf, PathBuf);8384/// Caches results of underlying resolver implementation85pub struct CachingImportResolver {86	resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,87	loading_cache: RefCell<HashMap<PathBuf, Result<Rc<str>>>>,88	inner: Box<dyn ImportResolver>,89}90impl ImportResolver for CachingImportResolver {91	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {92		self.resolution_cache93			.borrow_mut()94			.entry((from.clone(), path.clone()))95			.or_insert_with(|| self.inner.resolve_file(from, path))96			.clone()97	}98	fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>> {99		self.loading_cache100			.borrow_mut()101			.entry(resolved.clone())102			.or_insert_with(|| self.inner.load_file_contents(resolved))103			.clone()104	}105	unsafe fn as_any(&self) -> &dyn Any {106		panic!("this resolver can't be used as any")107	}108}
after · crates/jrsonnet-evaluator/src/import.rs
1use crate::{2	error::{Error::*, Result},3	throw,4};5use fs::File;6use std::fs;7use std::io::Read;8use std::{any::Any, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};910/// Implements file resolution logic for `import` and `importStr`11pub trait ImportResolver {12	/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond13	/// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`14	/// where `${vendor}` is a library path.15	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;1617	/// Reads file from filesystem, should be used only with path received from `resolve_file`18	fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>>;1920	/// # Safety21	///22	/// For use only in bindings, should not be used elsewhere.23	/// Implementations which are not intended to be used in bindings24	/// should panic on call to this method.25	unsafe fn as_any(&self) -> &dyn Any;26}2728/// Dummy resolver, can't resolve/load any file29pub struct DummyImportResolver;30impl ImportResolver for DummyImportResolver {31	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {32		throw!(ImportNotSupported(from.clone(), path.clone()))33	}3435	fn load_file_contents(&self, _resolved: &PathBuf) -> Result<Rc<str>> {36		// Can be only caused by library direct consumer, not by supplied jsonnet37		panic!("dummy resolver can't load any file")38	}3940	unsafe fn as_any(&self) -> &dyn Any {41		panic!("`as_any($self)` is not supported by dummy resolver")42	}43}44impl Default for Box<dyn ImportResolver> {45	fn default() -> Self {46		Box::new(DummyImportResolver)47	}48}4950/// File resolver, can load file from both FS and library paths51#[derive(Default)]52pub struct FileImportResolver {53	/// Library directories to search for file.54	/// Referred to as `jpath` in original jsonnet implementation.55	pub library_paths: Vec<PathBuf>,56}57impl ImportResolver for FileImportResolver {58	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {59		let mut new_path = from.clone();60		new_path.push(path);61		if new_path.exists() {62			Ok(Rc::new(new_path))63		} else {64			for library_path in self.library_paths.iter() {65				let mut cloned = library_path.clone();66				cloned.push(path);67				if cloned.exists() {68					return Ok(Rc::new(cloned));69				}70			}71			throw!(ImportFileNotFound(from.clone(), path.clone()))72		}73	}74	fn load_file_contents(&self, id: &PathBuf) -> Result<Rc<str>> {75		let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;76		let mut out = String::new();77		file.read_to_string(&mut out)78			.map_err(|_e| ImportBadFileUtf8(id.clone()))?;79		Ok(out.into())80	}81	unsafe fn as_any(&self) -> &dyn Any {82		panic!("this resolver can't be used as any")83	}84}8586type ResolutionData = (PathBuf, PathBuf);8788/// Caches results of the underlying resolver89pub struct CachingImportResolver {90	resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,91	loading_cache: RefCell<HashMap<PathBuf, Result<Rc<str>>>>,92	inner: Box<dyn ImportResolver>,93}94impl ImportResolver for CachingImportResolver {95	fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {96		self.resolution_cache97			.borrow_mut()98			.entry((from.clone(), path.clone()))99			.or_insert_with(|| self.inner.resolve_file(from, path))100			.clone()101	}102103	fn load_file_contents(&self, resolved: &PathBuf) -> Result<Rc<str>> {104		self.loading_cache105			.borrow_mut()106			.entry(resolved.clone())107			.or_insert_with(|| self.inner.load_file_contents(resolved))108			.clone()109	}110	unsafe fn as_any(&self) -> &dyn Any {111		panic!("this resolver can't be used as any")112	}113}
modifiedcrates/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))
 	}
modifiedcrates/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,
modifiedcrates/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()?;