difftreelog
feat breakpoints
in: master
9 files changed
crates/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)
},
)?;
}
crates/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),
|| {
crates/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};
crates/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)),
crates/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)
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -40,7 +40,7 @@
path::{Path, PathBuf},
rc::Rc,
};
-use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
+use trace::{location_to_offset, offset_to_location, CodeLocation, CompactFormat, TraceFormat};
pub use val::*;
pub trait Bindable: Trace {
@@ -109,6 +109,10 @@
struct EvaluationData {
/// Used for stack overflow detection, stacktrace is populated on unwind
stack_depth: usize,
+ /// Updated every time stack entry is popt
+ stack_generation: usize,
+
+ breakpoints: Breakpoints,
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
files: HashMap<Rc<Path>, FileData>,
str_files: HashMap<Rc<Path>, IStr>,
@@ -119,6 +123,38 @@
parsed: LocExpr,
evaluated: Option<Val>,
}
+
+pub struct Breakpoint {
+ loc: ExprLocation,
+ collected: RefCell<HashMap<usize, (usize, Vec<Result<Val>>)>>,
+}
+#[derive(Default)]
+struct Breakpoints(Vec<Rc<Breakpoint>>);
+impl Breakpoints {
+ fn insert(
+ &self,
+ stack_depth: usize,
+ stack_generation: usize,
+ loc: &ExprLocation,
+ result: Result<Val>,
+ ) -> Result<Val> {
+ if self.0.is_empty() {
+ return result;
+ }
+ for item in self.0.iter() {
+ if item.loc.belongs_to(loc) {
+ let mut collected = item.collected.borrow_mut();
+ let (depth, vals) = collected.entry(stack_generation).or_default();
+ if stack_depth > *depth {
+ vals.clear();
+ }
+ vals.push(result.clone());
+ }
+ }
+ result
+ }
+}
+
#[derive(Default)]
pub struct EvaluationStateInternals {
/// Internal state
@@ -135,7 +171,7 @@
pub(crate) fn with_state<T>(f: impl FnOnce(&EvaluationState) -> T) -> T {
EVAL_STATE.with(|s| f(s.borrow().as_ref().unwrap()))
}
-pub(crate) fn push<T>(
+pub(crate) fn push_frame<T>(
e: Option<&ExprLocation>,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<T>,
@@ -143,12 +179,12 @@
with_state(|s| s.push(e, frame_desc, f))
}
-pub fn push_stack_frame<T>(
+pub(crate) fn push_val_frame(
e: Option<&ExprLocation>,
frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
-) -> Result<T> {
- push(e, frame_desc, f)
+ f: impl FnOnce() -> Result<Val>,
+) -> Result<Val> {
+ with_state(|s| s.push(e, frame_desc, f))
}
/// Maintains stack trace and import resolution
@@ -178,6 +214,15 @@
Ok(())
}
+ pub fn reset_evaluation_state(&self, name: &Path) {
+ self.data_mut()
+ .files
+ .get_mut(name)
+ .unwrap()
+ .evaluated
+ .take();
+ }
+
/// Adds file by source code and parsed expr
pub fn add_parsed_file(
&self,
@@ -203,8 +248,15 @@
pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {
offset_to_location(&self.get_source(file).unwrap(), locs)
}
-
- pub(crate) fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
+ pub fn map_from_source_location(
+ &self,
+ file: &Path,
+ line: usize,
+ column: usize,
+ ) -> Option<usize> {
+ location_to_offset(&self.get_source(file).unwrap(), line, column)
+ }
+ pub fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
let file_path = self.resolve_file(from, path)?;
{
let data = self.data();
@@ -297,7 +349,54 @@
}
}
let result = f();
- self.data_mut().stack_depth -= 1;
+ {
+ let mut data = self.data_mut();
+ data.stack_depth -= 1;
+ data.stack_generation += 1;
+ // if let Some(e) = e {
+ // result =
+ // data.breakpoints
+ // .insert(data.stack_depth, data.stack_generation, &e, result)
+ // }
+ }
+ if let Err(mut err) = result {
+ err.trace_mut().0.push(StackTraceElement {
+ location: e.cloned(),
+ desc: frame_desc(),
+ });
+ return Err(err);
+ }
+ result
+ }
+ /// Executes code creating a new stack frame
+ pub fn push_val(
+ &self,
+ e: Option<&ExprLocation>,
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<Val>,
+ ) -> Result<Val> {
+ {
+ let mut data = self.data_mut();
+ let stack_depth = &mut data.stack_depth;
+ if *stack_depth > self.max_stack() {
+ // Error creation uses data, so i drop guard here
+ drop(data);
+ throw!(StackOverflow);
+ } else {
+ *stack_depth += 1;
+ }
+ }
+ let mut result = f();
+ {
+ let mut data = self.data_mut();
+ data.stack_depth -= 1;
+ data.stack_generation += 1;
+ if let Some(e) = e {
+ result =
+ data.breakpoints
+ .insert(data.stack_depth, data.stack_generation, &e, result)
+ }
+ }
if let Err(mut err) = result {
err.trace_mut().0.push(StackTraceElement {
location: e.cloned(),
@@ -322,7 +421,26 @@
result
})
}
+ pub fn run_in_state_with_breakpoint(
+ &self,
+ bp: Rc<Breakpoint>,
+ f: impl FnOnce() -> Result<()>,
+ ) -> Result<()> {
+ {
+ let mut data = self.data_mut();
+ data.breakpoints.0.push(bp);
+ }
+
+ let result = self.run_in_state(f);
+ {
+ let mut data = self.data_mut();
+ data.breakpoints.0.pop();
+ }
+
+ result
+ }
+
pub fn stringify_err(&self, e: &LocError) -> String {
let mut out = String::new();
self.settings()
@@ -346,7 +464,7 @@
pub fn with_tla(&self, val: Val) -> Result<Val> {
self.run_in_state(|| {
Ok(match val {
- Val::Func(func) => push(
+ Val::Func(func) => push_frame(
None,
|| "during TLA call".to_owned(),
|| {
@@ -514,7 +632,7 @@
|| "inner".to_owned(),
|| Err(RuntimeError("".into()).into()),
)?;
- Ok(())
+ Ok(Val::Null)
},
)
.unwrap();
crates/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![];
crates/jrsonnet-evaluator/src/typed.rsdiffbeforeafterboth1use std::{fmt::Display, rc::Rc};23use crate::{4 error::{Error, LocError, Result},5 push, Val,6};7use jrsonnet_gc::Trace;8use jrsonnet_parser::ExprLocation;9use jrsonnet_types::{ComplexValType, ValType};10use thiserror::Error;1112#[macro_export]13macro_rules! unwrap_type {14 ($desc: expr, $value: expr, $typ: expr => $match: path) => {{15 use $crate::{push_stack_frame, typed::CheckType};16 push_stack_frame(None, $desc, || Ok($typ.check(&$value)?))?;17 match $value {18 $match(v) => v,19 _ => unreachable!(),20 }21 }};22}2324#[derive(Debug, Error, Clone, Trace)]25#[trivially_drop]26pub enum TypeError {27 #[error("expected {0}, got {1}")]28 ExpectedGot(ComplexValType, ValType),29 #[error("missing property {0} from {1:?}")]30 MissingProperty(Rc<str>, ComplexValType),31 #[error("every failed from {0}:\n{1}")]32 UnionFailed(ComplexValType, TypeLocErrorList),33 #[error(34 "number out of bounds: {0} not in {}..{}",35 .1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),36 .2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),37 )]38 BoundsFailed(f64, Option<f64>, Option<f64>),39}40impl From<TypeError> for LocError {41 fn from(e: TypeError) -> Self {42 Error::TypeError(e.into()).into()43 }44}4546#[derive(Debug, Clone, Trace)]47#[trivially_drop]48pub struct TypeLocError(Box<TypeError>, ValuePathStack);49impl From<TypeError> for TypeLocError {50 fn from(e: TypeError) -> Self {51 Self(Box::new(e), ValuePathStack(Vec::new()))52 }53}54impl From<TypeLocError> for LocError {55 fn from(e: TypeLocError) -> Self {56 Error::TypeError(e).into()57 }58}59impl Display for TypeLocError {60 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {61 write!(f, "{}", self.0)?;62 if !(self.1).0.is_empty() {63 write!(f, " at {}", self.1)?;64 }65 Ok(())66 }67}6869#[derive(Debug, Clone, Trace)]70#[trivially_drop]71pub struct TypeLocErrorList(Vec<TypeLocError>);72impl Display for TypeLocErrorList {73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {74 use std::fmt::Write;75 let mut out = String::new();76 for (i, err) in self.0.iter().enumerate() {77 if i != 0 {78 writeln!(f)?;79 }80 out.clear();81 write!(out, "{}", err)?;8283 for (i, line) in out.lines().enumerate() {84 if line.trim().is_empty() {85 continue;86 }87 if i != 0 {88 writeln!(f)?;89 write!(f, " ")?;90 } else {91 write!(f, " - ")?;92 }93 write!(f, "{}", line)?;94 }95 }96 Ok(())97 }98}99100fn push_type(101 location: Option<&ExprLocation>,102 error_reason: impl Fn() -> String,103 path: impl Fn() -> ValuePathItem,104 item: impl Fn() -> Result<()>,105) -> Result<()> {106 push(location, error_reason, || match item() {107 Ok(_) => Ok(()),108 Err(mut e) => {109 if let Error::TypeError(e) = &mut e.error_mut() {110 (e.1).0.push(path())111 }112 Err(e)113 }114 })115}116117// TODO: check_fast for fast path of union type checking118pub trait CheckType {119 fn check(&self, value: &Val) -> Result<()>;120}121122impl CheckType for ValType {123 fn check(&self, value: &Val) -> Result<()> {124 let got = value.value_type();125 if got != *self {126 let loc_error: TypeLocError = TypeError::ExpectedGot((*self).into(), got).into();127 return Err(loc_error.into());128 }129 Ok(())130 }131}132133#[derive(Clone, Debug, Trace)]134#[trivially_drop]135enum ValuePathItem {136 Field(Rc<str>),137 Index(u64),138}139impl Display for ValuePathItem {140 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {141 match self {142 Self::Field(name) => write!(f, ".{}", name)?,143 Self::Index(idx) => write!(f, "[{}]", idx)?,144 }145 Ok(())146 }147}148149#[derive(Clone, Debug, Trace)]150#[trivially_drop]151struct ValuePathStack(Vec<ValuePathItem>);152impl Display for ValuePathStack {153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {154 write!(f, "self")?;155 for elem in self.0.iter().rev() {156 write!(f, "{}", elem)?;157 }158 Ok(())159 }160}161162impl CheckType for ComplexValType {163 fn check(&self, value: &Val) -> Result<()> {164 match self {165 Self::Any => Ok(()),166 Self::Simple(s) => s.check(value),167 Self::Char => match value {168 Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),169 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),170 },171 Self::BoundedNumber(from, to) => {172 if let Val::Num(n) = value {173 if from.map(|from| from > *n).unwrap_or(false)174 || to.map(|to| to <= *n).unwrap_or(false)175 {176 return Err(TypeError::BoundsFailed(*n, *from, *to).into());177 }178 Ok(())179 } else {180 Err(TypeError::ExpectedGot(self.clone(), value.value_type()).into())181 }182 }183 Self::Array(elem_type) => match value {184 Val::Arr(a) => {185 for (i, item) in a.iter().enumerate() {186 push_type(187 None,188 || format!("array index {}", i),189 || ValuePathItem::Index(i as u64),190 || elem_type.check(&item.clone()?),191 )?;192 }193 Ok(())194 }195 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),196 },197 Self::ArrayRef(elem_type) => match value {198 Val::Arr(a) => {199 for (i, item) in a.iter().enumerate() {200 push_type(201 None,202 || format!("array index {}", i),203 || ValuePathItem::Index(i as u64),204 || elem_type.check(&item.clone()?),205 )?;206 }207 Ok(())208 }209 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),210 },211 Self::ObjectRef(elems) => match value {212 Val::Obj(obj) => {213 for (k, v) in elems.iter() {214 if let Some(got_v) = obj.get((*k).into())? {215 push_type(216 None,217 || format!("property {}", k),218 || ValuePathItem::Field((*k).into()),219 || v.check(&got_v),220 )?221 } else {222 return Err(223 TypeError::MissingProperty((*k).into(), self.clone()).into()224 );225 }226 }227 Ok(())228 }229 v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),230 },231 Self::Union(types) => {232 let mut errors = Vec::new();233 for ty in types.iter() {234 match ty.check(value) {235 Ok(()) => {236 return Ok(());237 }238 Err(e) => match e.error() {239 Error::TypeError(e) => errors.push(e.clone()),240 _ => return Err(e),241 },242 }243 }244 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())245 }246 Self::UnionRef(types) => {247 let mut errors = Vec::new();248 for ty in types.iter() {249 match ty.check(value) {250 Ok(()) => {251 return Ok(());252 }253 Err(e) => match e.error() {254 Error::TypeError(e) => errors.push(e.clone()),255 _ => return Err(e),256 },257 }258 }259 Err(TypeError::UnionFailed(self.clone(), TypeLocErrorList(errors)).into())260 }261 Self::Sum(types) => {262 for ty in types.iter() {263 ty.check(value)?264 }265 Ok(())266 }267 Self::SumRef(types) => {268 for ty in types.iter() {269 ty.check(value)?270 }271 Ok(())272 }273 }274 }275}crates/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 {