git.delta.rocks / jrsonnet / refs/commits / 09a4bd7b68d6

difftreelog

feat breakpoints

Yaroslav Bolyukin2021-11-23parent: #8e60cf1.patch.diff
in: master

9 files changed

modifiedcrates/jrsonnet-evaluator/src/builtin/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/manifest.rs
@@ -1,5 +1,6 @@
 use crate::error::Error::*;
 use crate::error::Result;
+use crate::push_frame;
 use crate::{throw, Val};
 
 #[derive(PartialEq, Clone, Copy)]
@@ -102,12 +103,13 @@
 					buf.push_str(cur_padding);
 					escape_string_json_buf(&field, buf);
 					buf.push_str(": ");
-					crate::push(
+					push_frame(
 						None,
 						|| format!("field <{}> manifestification", field.clone()),
 						|| {
 							let value = obj.get(field.clone())?.unwrap();
-							manifest_json_ex_buf(&value, buf, cur_padding, options)
+							manifest_json_ex_buf(&value, buf, cur_padding, options)?;
+							Ok(Val::Null)
 						},
 					)?;
 				}
modifiedcrates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -3,8 +3,8 @@
 	equals,
 	error::{Error::*, Result},
 	operator::evaluate_mod_op,
-	parse_args, primitive_equals, push, throw, with_state, ArrValue, Context, EvaluationState,
-	FuncVal, IndexableVal, LazyVal, Val,
+	parse_args, primitive_equals, push_frame, throw, with_state, ArrValue, Context,
+	EvaluationState, FuncVal, IndexableVal, LazyVal, Val,
 };
 use format::{format_arr, format_obj};
 use jrsonnet_gc::Gc;
@@ -23,7 +23,7 @@
 pub mod sort;
 
 pub fn std_format(str: IStr, vals: Val) -> Result<Val> {
-	push(
+	push_frame(
 		Some(&ExprLocation(Rc::from(PathBuf::from("std.jsonnet")), 0, 0)),
 		|| format!("std.format of {}", str),
 		|| {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -1,7 +1,4 @@
-use crate::{
-	builtin::{format::FormatError, sort::SortError},
-	typed::TypeLocError,
-};
+use crate::{Val, builtin::{format::FormatError, sort::SortError}, typed::TypeLocError};
 use jrsonnet_gc::Trace;
 use jrsonnet_interner::IStr;
 use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -2,7 +2,7 @@
 	builtin::std_slice,
 	error::Error::*,
 	evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
-	push, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
+	push_frame, throw, with_state, ArrValue, Bindable, Context, ContextCreator, FuncDesc, FuncVal,
 	FutureWrapper, LazyBinding, LazyVal, LazyValValue, ObjValue, ObjValueBuilder, ObjectAssertion,
 	Result, Val,
 };
@@ -464,7 +464,7 @@
 			if tailstrict {
 				body()?
 			} else {
-				push(loc, || format!("function <{}> call", f.name()), body)?
+				push_frame(loc, || format!("function <{}> call", f.name()), body)?
 			}
 		}
 		v => throw!(OnlyFunctionsCanBeCalledGot(v.value_type())),
@@ -474,7 +474,7 @@
 pub fn evaluate_assert(context: Context, assertion: &AssertStmt) -> Result<()> {
 	let value = &assertion.0;
 	let msg = &assertion.1;
-	let assertion_result = push(
+	let assertion_result = push_frame(
 		value.1.as_ref(),
 		|| "assertion condition".to_owned(),
 		|| {
@@ -483,7 +483,7 @@
 		},
 	)?;
 	if !assertion_result {
-		push(
+		push_frame(
 			value.1.as_ref(),
 			|| "assertion failure".to_owned(),
 			|| {
@@ -510,6 +510,7 @@
 pub fn evaluate(context: Context, expr: &LocExpr) -> Result<Val> {
 	use Expr::*;
 	let LocExpr(expr, loc) = expr;
+	// let bp = with_state(|s| s.0.stop_at.borrow().clone());
 	Ok(match &**expr {
 		Literal(LiteralType::This) => {
 			Val::Obj(context.this().clone().ok_or(CantUseSelfOutsideOfObject)?)
@@ -532,7 +533,7 @@
 		Num(v) => Val::new_checked_num(*v)?,
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(context, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(context, v)?)?,
-		Var(name) => push(
+		Var(name) => push_frame(
 			loc.as_ref(),
 			|| format!("variable <{}>", name),
 			|| context.binding(name.clone())?.evaluate(),
@@ -541,7 +542,7 @@
 			match (evaluate(context.clone(), value)?, evaluate(context, index)?) {
 				(Val::Obj(v), Val::Str(s)) => {
 					let sn = s.clone();
-					push(
+					push_frame(
 						loc.as_ref(),
 						|| format!("field <{}> access", sn),
 						|| {
@@ -652,7 +653,7 @@
 			evaluate_assert(context.clone(), assert)?;
 			evaluate(context, returned)?
 		}
-		ErrorStmt(e) => push(
+		ErrorStmt(e) => push_frame(
 			loc.as_ref(),
 			|| "error statement".to_owned(),
 			|| {
@@ -666,7 +667,7 @@
 			cond_then,
 			cond_else,
 		} => {
-			if push(
+			if push_frame(
 				loc.as_ref(),
 				|| "if condition".to_owned(),
 				|| evaluate(context.clone(), &cond.0)?.try_cast_bool("in if condition"),
@@ -708,7 +709,7 @@
 				.0;
 			let mut import_location = tmp.to_path_buf();
 			import_location.pop();
-			push(
+			push_frame(
 				loc.as_ref(),
 				|| format!("import {:?}", path),
 				|| with_state(|s| s.import_file(&import_location, path)),
modifiedcrates/jrsonnet-evaluator/src/function.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function.rs
+++ b/crates/jrsonnet-evaluator/src/function.rs
@@ -243,7 +243,7 @@
 	($ctx: expr, $fn_name: expr, $args: expr, $total_args: expr, [
 		$($id: expr, $name: ident: $ty: expr $(=>$match: path)?);+ $(;)?
 	], $handler:block) => {{
-		use $crate::{error::Error::*, throw, evaluate, push_stack_frame, typed::CheckType};
+		use $crate::{error::Error::*, throw, evaluate, push_frame, typed::CheckType};
 
 		let args = $args;
 		if args.unnamed.len() + args.named.len() > $total_args {
@@ -263,7 +263,7 @@
 			} else {
 				&$args.unnamed[$id]
 			};
-			let $name = push_stack_frame(None, || format!("evaluating argument"), || {
+			let $name = push_frame(None, || format!("evaluating argument"), || {
 				let value = evaluate($ctx.clone(), &$name)?;
 				$ty.check(&value)?;
 				Ok(value)
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
40 path::{Path, PathBuf},40 path::{Path, PathBuf},
41 rc::Rc,41 rc::Rc,
42};42};
43use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};43use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
44pub use val::*;44pub use val::*;
4545
46pub trait Bindable: Trace {46pub trait Bindable: Trace {
109struct EvaluationData {109struct EvaluationData {
110 /// Used for stack overflow detection, stacktrace is populated on unwind110 /// Used for stack overflow detection, stacktrace is populated on unwind
111 stack_depth: usize,111 stack_depth: usize,
112 /// Updated every time stack entry is popt
113 stack_generation: usize,
114
115 breakpoints: Breakpoints,
112 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces116 /// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
113 files: HashMap<Rc<Path>, FileData>,117 files: HashMap<Rc<Path>, FileData>,
114 str_files: HashMap<Rc<Path>, IStr>,118 str_files: HashMap<Rc<Path>, IStr>,
120 evaluated: Option<Val>,124 evaluated: Option<Val>,
121}125}
126
127pub struct Breakpoint {
128 loc: ExprLocation,
129 collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,
130}
131#[derive(Default)]
132struct Breakpoints(Vec<Rc<Breakpoint>>);
133impl Breakpoints {
134 fn insert(
135 &self,
136 stack_depth: usize,
137 stack_generation: usize,
138 loc: &ExprLocation,
139 result: Result<Val>,
140 ) -> Result<Val> {
141 if self.0.is_empty() {
142 return result;
143 }
144 for item in self.0.iter() {
145 if item.loc.belongs_to(loc) {
146 let mut collected = item.collected.borrow_mut();
147 let (depth, vals) = collected.entry(stack_generation).or_default();
148 if stack_depth > *depth {
149 vals.clear();
150 }
151 vals.push(result.clone());
152 }
153 }
154 result
155 }
156}
157
122#[derive(Default)]158#[derive(Default)]
123pub struct EvaluationStateInternals {159pub struct EvaluationStateInternals {
135pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {171pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
136 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))172 EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
137}173}
138pub(crate) fn push<T>(174pub(crate) fn push_frame<T>(
139 e: Option<&ExprLocation>,175 e: Option<&ExprLocation>,
140 frame_desc: impl FnOnce() -> String,176 frame_desc: impl FnOnce() -> String,
141 f: impl FnOnce() -> Result<T>,177 f: impl FnOnce() -> Result<T>,
142) -> Result<T> {178) -> Result<T> {
143 with_state(|s| s.push(e, frame_desc, f))179 with_state(|s| s.push(e, frame_desc, f))
144}180}
145181
146pub fn push_stack_frame<T>(182pub(crate) fn push_val_frame(
147 e: Option<&ExprLocation>,183 e: Option<&ExprLocation>,
148 frame_desc: impl FnOnce() -> String,184 frame_desc: impl FnOnce() -> String,
149 f: impl FnOnce() -> Result<T>,185 f: impl FnOnce() -> Result<Val>,
150) -> Result<T> {186) -> Result<Val> {
151 push(e, frame_desc, f)187 with_state(|s| s.push(e, frame_desc, f))
152}188}
153189
154/// Maintains stack trace and import resolution190/// Maintains stack trace and import resolution
178 Ok(())214 Ok(())
179 }215 }
216
217 pub fn reset_evaluation_state(&self, name: &Path) {
218 self.data_mut()
219 .files
220 .get_mut(name)
221 .unwrap()
222 .evaluated
223 .take();
224 }
180225
181 /// Adds file by source code and parsed expr226 /// Adds file by source code and parsed expr
182 pub fn add_parsed_file(227 pub fn add_parsed_file(
204 offset_to_location(&self.get_source(file).unwrap(), locs)249 offset_to_location(&self.get_source(file).unwrap(), locs)
205 }250 }
206
207 pub(crate) fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {251 pub fn map_from_source_location(
252 &self,
253 file: &Path,
254 line: usize,
255 column: usize,
256 ) -> Option<usize> {
257 location_to_offset(&self.get_source(file).unwrap(), line, column)
258 }
259 pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
208 let file_path = self.resolve_file(from, path)?;260 let file_path = self.resolve_file(from, path)?;
209 {261 {
210 let data = self.data();262 let data = self.data();
297 }349 }
298 }350 }
299 let result = f();351 let result = f();
352 {
300 self.data_mut().stack_depth -= 1;353 let mut data = self.data_mut();
354 data.stack_depth -= 1;
355 data.stack_generation += 1;
356 // if let Some(e) = e {
357 // result =
358 // data.breakpoints
359 // .insert(data.stack_depth, data.stack_generation, &e, result)
360 // }
361 }
301 if let Err(mut err) = result {362 if let Err(mut err) = result {
302 err.trace_mut().0.push(StackTraceElement {363 err.trace_mut().0.push(StackTraceElement {
303 location: e.cloned(),364 location: e.cloned(),
307 }368 }
308 result369 result
309 }370 }
371 /// Executes code creating a new stack frame
372 pub fn push_val(
373 &self,
374 e: Option<&ExprLocation>,
375 frame_desc: impl FnOnce() -> String,
376 f: impl FnOnce() -> Result<Val>,
377 ) -> Result<Val> {
378 {
379 let mut data = self.data_mut();
380 let stack_depth = &mut data.stack_depth;
381 if *stack_depth > self.max_stack() {
382 // Error creation uses data, so i drop guard here
383 drop(data);
384 throw!(StackOverflow);
385 } else {
386 *stack_depth += 1;
387 }
388 }
389 let mut result = f();
390 {
391 let mut data = self.data_mut();
392 data.stack_depth -= 1;
393 data.stack_generation += 1;
394 if let Some(e) = e {
395 result =
396 data.breakpoints
397 .insert(data.stack_depth, data.stack_generation, &e, result)
398 }
399 }
400 if let Err(mut err) = result {
401 err.trace_mut().0.push(StackTraceElement {
402 location: e.cloned(),
403 desc: frame_desc(),
404 });
405 return Err(err);
406 }
407 result
408 }
310409
311 /// Runs passed function in state (required if function needs to modify stack trace)410 /// Runs passed function in state (required if function needs to modify stack trace)
312 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {411 pub fn run_in_state<T>(&self, f: impl FnOnce() -> T) -> T {
322 result421 result
323 })422 })
324 }423 }
424 pub fn run_in_state_with_breakpoint(
425 &self,
426 bp: Rc<Breakpoint>,
427 f: impl FnOnce() -> Result<()>,
428 ) -> Result<()> {
429 {
430 let mut data = self.data_mut();
431 data.breakpoints.0.push(bp);
432 }
433
434 let result = self.run_in_state(f);
435
436 {
437 let mut data = self.data_mut();
438 data.breakpoints.0.pop();
439 }
440
441 result
442 }
325443
326 pub fn stringify_err(&self, e: &LocError) -> String {444 pub fn stringify_err(&self, e: &LocError) -> String {
327 let mut out = String::new();445 let mut out = String::new();
346 pub fn with_tla(&self, val: Val) -> Result<Val> {464 pub fn with_tla(&self, val: Val) -> Result<Val> {
347 self.run_in_state(|| {465 self.run_in_state(|| {
348 Ok(match val {466 Ok(match val {
349 Val::Func(func) => push(467 Val::Func(func) => push_frame(
350 None,468 None,
351 || "during TLA call".to_owned(),469 || "during TLA call".to_owned(),
352 || {470 || {
514 || "inner".to_owned(),632 || "inner".to_owned(),
515 || Err(RuntimeError("".into()).into()),633 || Err(RuntimeError("".into()).into()),
516 )?;634 )?;
517 Ok(())635 Ok(Val::Null)
518 },636 },
519 )637 )
520 .unwrap();638 .unwrap();
modifiedcrates/jrsonnet-evaluator/src/trace/location.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/location.rs
+++ b/crates/jrsonnet-evaluator/src/trace/location.rs
@@ -9,6 +9,18 @@
 	pub line_end_offset: usize,
 }
 
+pub fn location_to_offset(mut file: &str, mut line: usize, column: usize) -> Option<usize> {
+	let mut offset = 0;
+	while line > 1 {
+		let pos = file.find('\n')?;
+		offset += pos + 1;
+		file = &file[pos + 1..];
+		line -= 1;
+	}
+	offset += column - 1;
+	Some(offset)
+}
+
 pub fn offset_to_location(file: &str, offsets: &[usize]) -> Vec<CodeLocation> {
 	if offsets.is_empty() {
 		return vec![];
modifiedcrates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed.rs
+++ b/crates/jrsonnet-evaluator/src/typed.rs
@@ -2,7 +2,7 @@
 
 use crate::{
 	error::{Error, LocError, Result},
-	push, Val,
+	push_frame, Val,
 };
 use jrsonnet_gc::Trace;
 use jrsonnet_parser::ExprLocation;
@@ -103,7 +103,7 @@
 	path: impl Fn() -> ValuePathItem,
 	item: impl Fn() -> Result<()>,
 ) -> Result<()> {
-	push(location, error_reason, || match item() {
+	push_frame(location, error_reason, || match item() {
 		Ok(_) => Ok(()),
 		Err(mut e) => {
 			if let Error::TypeError(e) = &mut e.error_mut() {
modifiedcrates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -356,6 +356,11 @@
 #[derive(Clone, PartialEq, Trace)]
 #[trivially_drop]
 pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
+impl ExprLocation {
+	pub fn belongs_to(&self, other: &ExprLocation) -> bool {
+		other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2
+	}
+}
 
 impl Debug for ExprLocation {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {