difftreelog
refactor add proper getters for LocExpr
in: master
10 files changed
crates/jrsonnet-evaluator/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-evaluator/Cargo.toml
+++ b/crates/jrsonnet-evaluator/Cargo.toml
@@ -53,8 +53,6 @@
serde.workspace = true
anyhow = { workspace = true, optional = true }
-# Serialized stdlib
-bincode = { workspace = true, optional = true }
# Explaining traces
annotate-snippets = { workspace = true, optional = true }
# Better explaining traces
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -7,7 +7,7 @@
use jrsonnet_gcmodule::Trace;
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};
+use jrsonnet_parser::{BinaryOpType, LocExpr, Source, SourcePath, Span, UnaryOpType};
use jrsonnet_types::ValType;
use thiserror::Error;
@@ -275,7 +275,7 @@
pub struct StackTraceElement {
/// Source of this frame
/// Some frames only act as description, without attached source
- pub location: Option<ExprLocation>,
+ pub location: Option<Span>,
/// Frame description
pub desc: String,
}
@@ -324,20 +324,20 @@
impl std::error::Error for Error {}
pub trait ErrorSource {
- fn to_location(self) -> Option<ExprLocation>;
+ fn to_location(self) -> Option<Span>;
}
impl ErrorSource for &LocExpr {
- fn to_location(self) -> Option<ExprLocation> {
- Some(self.1.clone())
+ fn to_location(self) -> Option<Span> {
+ Some(self.span())
}
}
-impl ErrorSource for &ExprLocation {
- fn to_location(self) -> Option<ExprLocation> {
+impl ErrorSource for &Span {
+ fn to_location(self) -> Option<Span> {
Some(self.clone())
}
}
impl ErrorSource for CallLocation<'_> {
- fn to_location(self) -> Option<ExprLocation> {
+ fn to_location(self) -> Option<Span> {
self.0.cloned()
}
}
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -26,7 +26,7 @@
pub fn evaluate_trivial(expr: &LocExpr) -> Option<Val> {
fn is_trivial(expr: &LocExpr) -> bool {
- match &*expr.0 {
+ match expr.expr() {
Expr::Str(_)
| Expr::Num(_)
| Expr::Literal(LiteralType::False | LiteralType::True | LiteralType::Null) => true,
@@ -35,7 +35,7 @@
_ => false,
}
}
- Some(match &*expr.0 {
+ Some(match expr.expr() {
Expr::Str(s) => Val::string(s.clone()),
Expr::Num(n) => {
Val::Num(NumValue::new(*n).expect("parser will not allow non-finite values"))
@@ -72,7 +72,7 @@
Ok(match field_name {
FieldName::Fixed(n) => Some(n.clone()),
FieldName::Dyn(expr) => State::push(
- CallLocation::new(&expr.1),
+ CallLocation::new(&expr.span()),
|| "evaluating field name".to_string(),
|| {
let value = evaluate(ctx, expr)?;
@@ -231,7 +231,7 @@
.field(name.clone())
.with_add(*plus)
.with_visibility(*visibility)
- .with_location(value.1.clone())
+ .with_location(value.span())
.bindable(UnboundValue {
uctx,
value: value.clone(),
@@ -266,7 +266,7 @@
builder
.field(name.clone())
.with_visibility(*visibility)
- .with_location(value.1.clone())
+ .with_location(value.span())
.bindable(UnboundMethod {
uctx,
value: value.clone(),
@@ -385,13 +385,13 @@
let value = &assertion.0;
let msg = &assertion.1;
let assertion_result = State::push(
- CallLocation::new(&value.1),
+ CallLocation::new(&value.span()),
|| "assertion condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), value)?),
)?;
if !assertion_result {
State::push(
- CallLocation::new(&value.1),
+ CallLocation::new(&value.span()),
|| "assertion failure".to_owned(),
|| {
if let Some(msg) = msg {
@@ -406,8 +406,7 @@
pub fn evaluate_named(ctx: Context, expr: &LocExpr, name: IStr) -> Result<Val> {
use Expr::*;
- let LocExpr(raw_expr, _loc) = expr;
- Ok(match &**raw_expr {
+ Ok(match expr.expr() {
Function(params, body) => evaluate_method(ctx, name, params.clone(), body.clone()),
_ => evaluate(ctx, expr)?,
})
@@ -420,8 +419,8 @@
if let Some(trivial) = evaluate_trivial(expr) {
return Ok(trivial);
}
- let LocExpr(expr, loc) = expr;
- Ok(match &**expr {
+ let loc = expr.span();
+ Ok(match expr.expr() {
Literal(LiteralType::This) => {
Val::Obj(ctx.this().ok_or(CantUseSelfOutsideOfObject)?.clone())
}
@@ -448,7 +447,7 @@
// because the standalone super literal is not supported, that is because in other
// implementations `in super` treated differently from in `smth_else`.
BinaryOp(field, BinaryOpType::In, e)
- if matches!(&*e.0, Expr::Literal(LiteralType::Super)) =>
+ if matches!(e.expr(), Expr::Literal(LiteralType::Super)) =>
{
let Some(super_obj) = ctx.super_obj() else {
return Ok(Val::Bool(false));
@@ -459,52 +458,50 @@
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
Var(name) => State::push(
- CallLocation::new(loc),
+ CallLocation::new(&loc),
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(),
)?,
Index { indexable, parts } => {
let mut parts = parts.iter();
- let mut indexable = match &indexable {
- // Cheaper to execute than creating object with overriden `this`
- LocExpr(v, _) if matches!(&**v, Expr::Literal(LiteralType::Super)) => {
- let part = parts.next().expect("at least part should exist");
- let Some(super_obj) = ctx.super_obj() else {
- #[cfg(feature = "exp-null-coaelse")]
- if part.null_coaelse {
- return Ok(Val::Null);
- }
- bail!(NoSuperFound)
- };
- let name = evaluate(ctx.clone(), &part.value)?;
+ let mut indexable = if matches!(indexable.expr(), Expr::Literal(LiteralType::Super)) {
+ let part = parts.next().expect("at least part should exist");
+ let Some(super_obj) = ctx.super_obj() else {
+ #[cfg(feature = "exp-null-coaelse")]
+ if part.null_coaelse {
+ return Ok(Val::Null);
+ }
+ bail!(NoSuperFound)
+ };
+ let name = evaluate(ctx.clone(), &part.value)?;
- let Val::Str(name) = name else {
- bail!(ValueIndexMustBeTypeGot(
- ValType::Obj,
- ValType::Str,
- name.value_type(),
- ))
- };
+ let Val::Str(name) = name else {
+ bail!(ValueIndexMustBeTypeGot(
+ ValType::Obj,
+ ValType::Str,
+ name.value_type(),
+ ))
+ };
- let this = ctx
- .this()
- .expect("no this found, while super present, should not happen");
- let name = name.into_flat();
- match super_obj
- .get_for(name.clone(), this.clone())
- .with_description_src(&part.value, || format!("field <{name}> access"))?
- {
- Some(v) => v,
- #[cfg(feature = "exp-null-coaelse")]
- None if part.null_coaelse => return Ok(Val::Null),
- None => {
- let suggestions = suggest_object_fields(super_obj, name.clone());
+ let this = ctx
+ .this()
+ .expect("no this found, while super present, should not happen");
+ let name = name.into_flat();
+ match super_obj
+ .get_for(name.clone(), this.clone())
+ .with_description_src(&part.value, || format!("field <{name}> access"))?
+ {
+ Some(v) => v,
+ #[cfg(feature = "exp-null-coaelse")]
+ None if part.null_coaelse => return Ok(Val::Null),
+ None => {
+ let suggestions = suggest_object_fields(super_obj, name.clone());
- bail!(NoSuchField(name, suggestions))
- }
+ bail!(NoSuchField(name, suggestions))
}
}
- e => evaluate(ctx.clone(), e)?,
+ } else {
+ evaluate(ctx.clone(), indexable)?
};
for part in parts {
@@ -639,7 +636,7 @@
&Val::Obj(evaluate_object(ctx, b)?),
)?,
Apply(value, args, tailstrict) => {
- evaluate_apply(ctx, value, args, CallLocation::new(loc), *tailstrict)?
+ evaluate_apply(ctx, value, args, CallLocation::new(&loc), *tailstrict)?
}
Function(params, body) => {
evaluate_method(ctx, "anonymous".into(), params.clone(), body.clone())
@@ -649,7 +646,7 @@
evaluate(ctx, returned)?
}
ErrorStmt(e) => State::push(
- CallLocation::new(loc),
+ CallLocation::new(&loc),
|| "error statement".to_owned(),
|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
)?,
@@ -659,7 +656,7 @@
cond_else,
} => {
if State::push(
- CallLocation::new(loc),
+ CallLocation::new(&loc),
|| "if condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
)? {
@@ -690,7 +687,7 @@
}
let indexable = evaluate(ctx.clone(), value)?;
- let loc = CallLocation::new(loc);
+ let loc = CallLocation::new(&loc);
let start = parse_idx(loc, &ctx, desc.start.as_ref(), "start")?;
let end = parse_idx(loc, &ctx, desc.end.as_ref(), "end")?;
@@ -699,7 +696,7 @@
IndexableVal::into_untyped(indexable.into_indexable()?.slice(start, end, step)?)?
}
i @ (Import(path) | ImportStr(path) | ImportBin(path)) => {
- let Expr::Str(path) = &*path.0 else {
+ let Expr::Str(path) = &path.expr() else {
bail!("computed imports are not supported")
};
let tmp = loc.clone().0;
@@ -707,7 +704,7 @@
let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
match i {
Import(_) => State::push(
- CallLocation::new(loc),
+ CallLocation::new(&loc),
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
)?,
crates/jrsonnet-evaluator/src/function/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/function/mod.rs
+++ b/crates/jrsonnet-evaluator/src/function/mod.rs
@@ -4,7 +4,7 @@
use jrsonnet_gcmodule::{Cc, Trace};
use jrsonnet_interner::IStr;
pub use jrsonnet_macros::builtin;
-use jrsonnet_parser::{Destruct, Expr, ExprLocation, LocExpr, ParamsDesc};
+use jrsonnet_parser::{Destruct, Expr, LocExpr, ParamsDesc, Span};
use self::{
arglike::OptionalContext,
@@ -22,10 +22,10 @@
/// Function callsite location.
/// Either from other jsonnet code, specified by expression location, or from native (without location).
#[derive(Clone, Copy)]
-pub struct CallLocation<'l>(pub Option<&'l ExprLocation>);
+pub struct CallLocation<'l>(pub Option<&'l Span>);
impl<'l> CallLocation<'l> {
/// Construct new location for calls coming from specified jsonnet expression location.
- pub const fn new(loc: &'l ExprLocation) -> Self {
+ pub const fn new(loc: &'l Span) -> Self {
Self(Some(loc))
}
}
@@ -225,7 +225,7 @@
#[cfg(feature = "exp-destruct")]
_ => return false,
};
- &desc.body.0 as &Expr == &Expr::Var(id.clone())
+ desc.body.expr() == &Expr::Var(id.clone())
}
_ => false,
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{ExprLocation, LocExpr, ParserSettings, Source, SourcePath};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
@@ -369,7 +369,7 @@
/// Executes code creating a new stack frame
pub fn push_val(
&self,
- e: &ExprLocation,
+ e: &Span,
frame_desc: impl FnOnce() -> String,
f: impl FnOnce() -> Result<Val>,
) -> Result<Val> {
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -8,7 +8,7 @@
use jrsonnet_gcmodule::{Cc, Trace, Weak};
use jrsonnet_interner::IStr;
-use jrsonnet_parser::{ExprLocation, Visibility};
+use jrsonnet_parser::{Span, Visibility};
use rustc_hash::FxHashMap;
use crate::{
@@ -135,7 +135,7 @@
flags: ObjFieldFlags,
original_index: FieldIndex,
pub invoke: MaybeUnbound,
- pub location: Option<ExprLocation>,
+ pub location: Option<Span>,
}
pub trait ObjectAssertion: Trace {
@@ -896,7 +896,7 @@
add: bool,
visibility: Visibility,
original_index: FieldIndex,
- location: Option<ExprLocation>,
+ location: Option<Span>,
}
#[allow(clippy::missing_const_for_fn)]
@@ -926,7 +926,7 @@
pub fn hide(self) -> Self {
self.with_visibility(Visibility::Hidden)
}
- pub fn with_location(mut self, location: ExprLocation) -> Self {
+ pub fn with_location(mut self, location: Span) -> Self {
self.location = Some(location);
self
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth1use std::{2 any::Any,3 cell::RefCell,4 path::{Path, PathBuf},5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_parser::{CodeLocation, ExprLocation, Source};910use crate::{error::ErrorKind, Error};1112/// The way paths should be displayed13#[derive(Clone, Trace)]14pub enum PathResolver {15 /// Only filename16 FileName,17 /// Absolute path18 Absolute,19 /// Path relative to base directory20 Relative(PathBuf),21}2223impl PathResolver {24 /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure25 pub fn new_cwd_fallback() -> Self {26 std::env::current_dir().map_or(Self::Absolute, Self::Relative)27 }28 pub fn resolve(&self, from: &Path) -> String {29 match self {30 Self::FileName => from31 .file_name()32 .expect("file name exists")33 .to_string_lossy()34 .into_owned(),35 Self::Absolute => from.to_string_lossy().into_owned(),36 Self::Relative(base) => {37 if from.is_relative() {38 return from.to_string_lossy().into_owned();39 }40 pathdiff::diff_paths(from, base)41 .expect("base is absolute")42 .to_string_lossy()43 .into_owned()44 }45 }46 }47}4849/// Implements pretty-printing of traces50#[allow(clippy::module_name_repetitions)]51pub trait TraceFormat: Trace {52 fn write_trace(53 &self,54 out: &mut dyn std::fmt::Write,55 error: &Error,56 ) -> Result<(), std::fmt::Error>;57 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {58 let mut out = String::new();59 self.write_trace(&mut out, error)?;60 Ok(out)61 }62 fn as_any(&self) -> &dyn Any;63 fn as_any_mut(&mut self) -> &mut dyn Any;64}6566fn print_code_location(67 out: &mut impl std::fmt::Write,68 start: &CodeLocation,69 end: &CodeLocation,70) -> Result<(), std::fmt::Error> {71 if start.line == end.line {72 if start.column == end.column {73 write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;74 } else {75 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;76 }77 } else {78 write!(79 out,80 "{}:{}-{}:{}",81 start.line,82 end.column.saturating_sub(1),83 start.line,84 end.column85 )?;86 }87 Ok(())88}8990/// vanilla-like jsonnet formatting91#[derive(Trace)]92pub struct CompactFormat {93 pub resolver: PathResolver,94 pub max_trace: usize,95 pub padding: usize,96}97impl Default for CompactFormat {98 fn default() -> Self {99 Self {100 resolver: PathResolver::Absolute,101 max_trace: 20,102 padding: 4,103 }104 }105}106107impl TraceFormat for CompactFormat {108 fn write_trace(109 &self,110 out: &mut dyn std::fmt::Write,111 error: &Error,112 ) -> Result<(), std::fmt::Error> {113 write!(out, "{}", error.error())?;114 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {115 use std::fmt::Write;116117 writeln!(out)?;118 let mut n = path.source_path().path().map_or_else(119 || path.source_path().to_string(),120 |r| self.resolver.resolve(r),121 );122 let mut offset = error.location.offset;123 let is_eof = if offset >= path.code().len() {124 offset = path.code().len().saturating_sub(1);125 true126 } else {127 false128 };129 let mut location = path130 .map_source_locations(&[offset as u32])131 .into_iter()132 .next()133 .unwrap();134 if is_eof {135 location.column += 1;136 }137138 write!(n, ":").unwrap();139 print_code_location(&mut n, &location, &location).unwrap();140 write!(out, "{:<p$}{n}", "", p = self.padding)?;141 }142 let file_names = error143 .trace()144 .0145 .iter()146 .map(|el| &el.location)147 .map(|location| {148 use std::fmt::Write;149 #[allow(clippy::option_if_let_else)]150 if let Some(location) = location {151 let mut resolved_path = match location.0.source_path().path() {152 Some(r) => self.resolver.resolve(r),153 None => location.0.source_path().to_string(),154 };155 // TODO: Process all trace elements first156 let location = location.0.map_source_locations(&[location.1, location.2]);157 write!(resolved_path, ":").unwrap();158 print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();159 write!(resolved_path, ":").unwrap();160 Some(resolved_path)161 } else {162 None163 }164 })165 .collect::<Vec<_>>();166 let align = file_names167 .iter()168 .flatten()169 .map(String::len)170 .max()171 .unwrap_or(0);172 for (el, file) in error.trace().0.iter().zip(file_names) {173 writeln!(out)?;174 if let Some(file) = file {175 write!(176 out,177 "{:<p$}{:<w$} {}",178 "",179 file,180 el.desc,181 p = self.padding,182 w = align183 )?;184 } else {185 write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;186 }187 }188 Ok(())189 }190191 fn as_any(&self) -> &dyn Any {192 self193 }194195 fn as_any_mut(&mut self) -> &mut dyn Any {196 self197 }198}199200#[derive(Trace)]201pub struct JsFormat {202 pub max_trace: usize,203}204impl TraceFormat for JsFormat {205 fn write_trace(206 &self,207 out: &mut dyn std::fmt::Write,208 error: &Error,209 ) -> Result<(), std::fmt::Error> {210 write!(out, "{}", error.error())?;211 for item in &error.trace().0 {212 writeln!(out)?;213 let desc = &item.desc;214 if let Some(source) = &item.location {215 let start_end = source.0.map_source_locations(&[source.1, source.2]);216 let resolved_path = source.0.source_path().path().map_or_else(217 || source.0.source_path().to_string(),218 |r| r.display().to_string(),219 );220221 write!(222 out,223 " at {} ({}:{}:{})",224 desc, resolved_path, start_end[0].line, start_end[0].column,225 )?;226 } else {227 write!(out, " during {desc}")?;228 }229 }230 Ok(())231 }232233 fn as_any(&self) -> &dyn Any {234 self235 }236237 fn as_any_mut(&mut self) -> &mut dyn Any {238 self239 }240}241242/// rustc-like trace displaying243#[cfg(feature = "explaining-traces")]244#[derive(Trace)]245pub struct ExplainingFormat {246 pub resolver: PathResolver,247 pub max_trace: usize,248}249#[cfg(feature = "explaining-traces")]250impl TraceFormat for ExplainingFormat {251 fn write_trace(252 &self,253 out: &mut dyn std::fmt::Write,254 error: &Error,255 ) -> Result<(), std::fmt::Error> {256 write!(out, "{}", error.error())?;257 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {258 writeln!(out)?;259 let offset = error.location.offset;260 let location = path261 .map_source_locations(&[offset as u32])262 .into_iter()263 .next()264 .unwrap();265 let mut end_location = location;266 end_location.offset += 1;267268 self.print_snippet(269 out,270 path.code(),271 path,272 &location,273 &end_location,274 "syntax error",275 )?;276 }277 let trace = &error.trace();278 for item in &trace.0 {279 writeln!(out)?;280 let desc = &item.desc;281 if let Some(source) = &item.location {282 let start_end = source.0.map_source_locations(&[source.1, source.2]);283 self.print_snippet(284 out,285 source.0.code(),286 &source.0,287 &start_end[0],288 &start_end[1],289 desc,290 )?;291 } else {292 write!(out, "{desc}")?;293 }294 }295 Ok(())296 }297298 fn as_any(&self) -> &dyn Any {299 self300 }301302 fn as_any_mut(&mut self) -> &mut dyn Any {303 self304 }305}306307#[cfg(feature = "explaining-traces")]308impl ExplainingFormat {309 fn print_snippet(310 &self,311 out: &mut dyn std::fmt::Write,312 source: &str,313 origin: &Source,314 start: &CodeLocation,315 end: &CodeLocation,316 desc: &str,317 ) -> Result<(), std::fmt::Error> {318 use annotate_snippets::{319 // DisplayList, FormatOptions,320 AnnotationType,321 Renderer,322 Slice,323 Snippet,324 SourceAnnotation,325 };326327 let source_fragment: String = source328 .chars()329 .skip(start.line_start_offset)330 .take(end.line_end_offset - end.line_start_offset)331 .collect();332333 let origin = origin.source_path().path().map_or_else(334 || origin.source_path().to_string(),335 |r| self.resolver.resolve(r),336 );337 let snippet = Snippet {338 // opt: FormatOptions {339 // color: true,340 // ..FormatOptions::default()341 // },342 title: None,343 footer: vec![],344 slices: vec![Slice {345 source: &source_fragment,346 line_start: start.line,347 origin: Some(&origin),348 fold: false,349 annotations: vec![SourceAnnotation {350 label: desc,351 annotation_type: AnnotationType::Error,352 range: (353 start.offset - start.line_start_offset,354 (end.offset.saturating_sub(start.line_start_offset))355 .min(source_fragment.len()),356 ),357 }],358 }],359 };360361 let renderer = Renderer::styled();362 let dl = renderer.render(snippet);363 write!(out, "{dl}")?;364365 Ok(())366 }367}368369#[cfg(feature = "explaining-traces")]370#[derive(Trace)]371pub struct AssStrokeFormat {372 pub resolver: PathResolver,373 pub max_trace: usize,374}375#[cfg(feature = "explaining-traces")]376impl TraceFormat for AssStrokeFormat {377 fn write_trace(378 &self,379 out: &mut dyn std::fmt::Write,380 error: &Error,381 ) -> Result<(), std::fmt::Error> {382 struct ResetData {383 loc: ExprLocation,384 }385 use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};386387 write!(out, "{}", error.error())?;388 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {389 writeln!(out)?;390 let offset = error.location.offset;391 let mut builder = SnippetBuilder::new(path.code());392 builder393 .error(Text::single("syntax error".chars(), Formatting::default()))394 .range(offset..=offset)395 .build();396 let source = builder.build();397 let ansi = source_to_ansi(&source);398 write!(out, "{ansi}")?;399 }400 let trace = &error.trace();401 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);402 let mut last_location: Option<ExprLocation> = None;403 let mut flush_builder = |data: Option<ResetData>| {404 use std::fmt::Write;405 let mut out = String::new();406 let location_changed = if let Some(ResetData { loc }) = &data {407 if last_location.as_ref().map(|l| l.0.code()) != Some(loc.0.code()) {408 true409 } else if let (Some(last), new) = (&last_location, loc) {410 // Reverse condition if traceback411 last.1 > new.1 || last.2 > new.2412 } else {413 false414 }415 } else {416 true417 };418 if location_changed {419 if let Some(builder) = snippet_builder.borrow_mut().take() {420 let rendered = builder.build();421 let ansi = source_to_ansi(&rendered);422 if let Some(loc) = &last_location {423 let _ = writeln!(out, "...because of {}", loc.0.source_path());424 }425 let _ = write!(out, "{}", ansi.trim_end());426 }427 last_location = None;428429 if let Some(ResetData { loc }) = data {430 *snippet_builder.borrow_mut() = Some(SnippetBuilder::new(loc.0.code()));431 last_location = Some(loc);432 }433 }434 if out.is_empty() {435 return None;436 }437 Some(out)438 };439 for item in &trace.0 {440 let desc = &item.desc;441 if let Some(source) = &item.location {442 if let Some(flushed) = flush_builder(Some(ResetData {443 loc: source.clone(),444 })) {445 writeln!(out)?;446 write!(out, "{flushed}")?;447 }448 let mut builder = snippet_builder.borrow_mut();449 let builder = builder.as_mut().unwrap();450 builder451 .note(Text::single(desc.chars(), Formatting::default()))452 .range(source.1 as usize..=(source.2 as usize - 1).max(source.1 as usize))453 .build();454 } else {455 if let Some(flushed) = flush_builder(None) {456 writeln!(out)?;457 write!(out, "{flushed}")?;458 }459 write!(out, "{desc}")?;460 }461 }462463 if let Some(flushed) = flush_builder(None) {464 writeln!(out)?;465 write!(out, "{flushed}")?;466 }467 Ok(())468 }469470 fn as_any(&self) -> &dyn Any {471 self472 }473474 fn as_any_mut(&mut self) -> &mut dyn Any {475 self476 }477}1use std::{2 any::Any,3 cell::RefCell,4 path::{Path, PathBuf},5};67use jrsonnet_gcmodule::Trace;8use jrsonnet_parser::{CodeLocation, Source, Span};910use crate::{error::ErrorKind, Error};1112/// The way paths should be displayed13#[derive(Clone, Trace)]14pub enum PathResolver {15 /// Only filename16 FileName,17 /// Absolute path18 Absolute,19 /// Path relative to base directory20 Relative(PathBuf),21}2223impl PathResolver {24 /// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure25 pub fn new_cwd_fallback() -> Self {26 std::env::current_dir().map_or(Self::Absolute, Self::Relative)27 }28 pub fn resolve(&self, from: &Path) -> String {29 match self {30 Self::FileName => from31 .file_name()32 .expect("file name exists")33 .to_string_lossy()34 .into_owned(),35 Self::Absolute => from.to_string_lossy().into_owned(),36 Self::Relative(base) => {37 if from.is_relative() {38 return from.to_string_lossy().into_owned();39 }40 pathdiff::diff_paths(from, base)41 .expect("base is absolute")42 .to_string_lossy()43 .into_owned()44 }45 }46 }47}4849/// Implements pretty-printing of traces50#[allow(clippy::module_name_repetitions)]51pub trait TraceFormat: Trace {52 fn write_trace(53 &self,54 out: &mut dyn std::fmt::Write,55 error: &Error,56 ) -> Result<(), std::fmt::Error>;57 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {58 let mut out = String::new();59 self.write_trace(&mut out, error)?;60 Ok(out)61 }62 fn as_any(&self) -> &dyn Any;63 fn as_any_mut(&mut self) -> &mut dyn Any;64}6566fn print_code_location(67 out: &mut impl std::fmt::Write,68 start: &CodeLocation,69 end: &CodeLocation,70) -> Result<(), std::fmt::Error> {71 if start.line == end.line {72 if start.column == end.column {73 write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;74 } else {75 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;76 }77 } else {78 write!(79 out,80 "{}:{}-{}:{}",81 start.line,82 end.column.saturating_sub(1),83 start.line,84 end.column85 )?;86 }87 Ok(())88}8990/// vanilla-like jsonnet formatting91#[derive(Trace)]92pub struct CompactFormat {93 pub resolver: PathResolver,94 pub max_trace: usize,95 pub padding: usize,96}97impl Default for CompactFormat {98 fn default() -> Self {99 Self {100 resolver: PathResolver::Absolute,101 max_trace: 20,102 padding: 4,103 }104 }105}106107impl TraceFormat for CompactFormat {108 fn write_trace(109 &self,110 out: &mut dyn std::fmt::Write,111 error: &Error,112 ) -> Result<(), std::fmt::Error> {113 write!(out, "{}", error.error())?;114 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {115 use std::fmt::Write;116117 writeln!(out)?;118 let mut n = path.source_path().path().map_or_else(119 || path.source_path().to_string(),120 |r| self.resolver.resolve(r),121 );122 let mut offset = error.location.offset;123 let is_eof = if offset >= path.code().len() {124 offset = path.code().len().saturating_sub(1);125 true126 } else {127 false128 };129 let mut location = path130 .map_source_locations(&[offset as u32])131 .into_iter()132 .next()133 .unwrap();134 if is_eof {135 location.column += 1;136 }137138 write!(n, ":").unwrap();139 print_code_location(&mut n, &location, &location).unwrap();140 write!(out, "{:<p$}{n}", "", p = self.padding)?;141 }142 let file_names = error143 .trace()144 .0145 .iter()146 .map(|el| &el.location)147 .map(|location| {148 use std::fmt::Write;149 #[allow(clippy::option_if_let_else)]150 if let Some(location) = location {151 let mut resolved_path = match location.0.source_path().path() {152 Some(r) => self.resolver.resolve(r),153 None => location.0.source_path().to_string(),154 };155 // TODO: Process all trace elements first156 let location = location.0.map_source_locations(&[location.1, location.2]);157 write!(resolved_path, ":").unwrap();158 print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();159 write!(resolved_path, ":").unwrap();160 Some(resolved_path)161 } else {162 None163 }164 })165 .collect::<Vec<_>>();166 let align = file_names167 .iter()168 .flatten()169 .map(String::len)170 .max()171 .unwrap_or(0);172 for (el, file) in error.trace().0.iter().zip(file_names) {173 writeln!(out)?;174 if let Some(file) = file {175 write!(176 out,177 "{:<p$}{:<w$} {}",178 "",179 file,180 el.desc,181 p = self.padding,182 w = align183 )?;184 } else {185 write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;186 }187 }188 Ok(())189 }190191 fn as_any(&self) -> &dyn Any {192 self193 }194195 fn as_any_mut(&mut self) -> &mut dyn Any {196 self197 }198}199200#[derive(Trace)]201pub struct JsFormat {202 pub max_trace: usize,203}204impl TraceFormat for JsFormat {205 fn write_trace(206 &self,207 out: &mut dyn std::fmt::Write,208 error: &Error,209 ) -> Result<(), std::fmt::Error> {210 write!(out, "{}", error.error())?;211 for item in &error.trace().0 {212 writeln!(out)?;213 let desc = &item.desc;214 if let Some(source) = &item.location {215 let start_end = source.0.map_source_locations(&[source.1, source.2]);216 let resolved_path = source.0.source_path().path().map_or_else(217 || source.0.source_path().to_string(),218 |r| r.display().to_string(),219 );220221 write!(222 out,223 " at {} ({}:{}:{})",224 desc, resolved_path, start_end[0].line, start_end[0].column,225 )?;226 } else {227 write!(out, " during {desc}")?;228 }229 }230 Ok(())231 }232233 fn as_any(&self) -> &dyn Any {234 self235 }236237 fn as_any_mut(&mut self) -> &mut dyn Any {238 self239 }240}241242/// rustc-like trace displaying243#[cfg(feature = "explaining-traces")]244#[derive(Trace)]245pub struct ExplainingFormat {246 pub resolver: PathResolver,247 pub max_trace: usize,248}249#[cfg(feature = "explaining-traces")]250impl TraceFormat for ExplainingFormat {251 fn write_trace(252 &self,253 out: &mut dyn std::fmt::Write,254 error: &Error,255 ) -> Result<(), std::fmt::Error> {256 write!(out, "{}", error.error())?;257 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {258 writeln!(out)?;259 let offset = error.location.offset;260 let location = path261 .map_source_locations(&[offset as u32])262 .into_iter()263 .next()264 .unwrap();265 let mut end_location = location;266 end_location.offset += 1;267268 self.print_snippet(269 out,270 path.code(),271 path,272 &location,273 &end_location,274 "syntax error",275 )?;276 }277 let trace = &error.trace();278 for item in &trace.0 {279 writeln!(out)?;280 let desc = &item.desc;281 if let Some(source) = &item.location {282 let start_end = source.0.map_source_locations(&[source.1, source.2]);283 self.print_snippet(284 out,285 source.0.code(),286 &source.0,287 &start_end[0],288 &start_end[1],289 desc,290 )?;291 } else {292 write!(out, "{desc}")?;293 }294 }295 Ok(())296 }297298 fn as_any(&self) -> &dyn Any {299 self300 }301302 fn as_any_mut(&mut self) -> &mut dyn Any {303 self304 }305}306307#[cfg(feature = "explaining-traces")]308impl ExplainingFormat {309 fn print_snippet(310 &self,311 out: &mut dyn std::fmt::Write,312 source: &str,313 origin: &Source,314 start: &CodeLocation,315 end: &CodeLocation,316 desc: &str,317 ) -> Result<(), std::fmt::Error> {318 use annotate_snippets::{319 // DisplayList, FormatOptions,320 AnnotationType,321 Renderer,322 Slice,323 Snippet,324 SourceAnnotation,325 };326327 let source_fragment: String = source328 .chars()329 .skip(start.line_start_offset)330 .take(end.line_end_offset - end.line_start_offset)331 .collect();332333 let origin = origin.source_path().path().map_or_else(334 || origin.source_path().to_string(),335 |r| self.resolver.resolve(r),336 );337 let snippet = Snippet {338 // opt: FormatOptions {339 // color: true,340 // ..FormatOptions::default()341 // },342 title: None,343 footer: vec![],344 slices: vec![Slice {345 source: &source_fragment,346 line_start: start.line,347 origin: Some(&origin),348 fold: false,349 annotations: vec![SourceAnnotation {350 label: desc,351 annotation_type: AnnotationType::Error,352 range: (353 start.offset - start.line_start_offset,354 (end.offset.saturating_sub(start.line_start_offset))355 .min(source_fragment.len()),356 ),357 }],358 }],359 };360361 let renderer = Renderer::styled();362 let dl = renderer.render(snippet);363 write!(out, "{dl}")?;364365 Ok(())366 }367}368369#[cfg(feature = "explaining-traces")]370#[derive(Trace)]371pub struct AssStrokeFormat {372 pub resolver: PathResolver,373 pub max_trace: usize,374}375#[cfg(feature = "explaining-traces")]376impl TraceFormat for AssStrokeFormat {377 fn write_trace(378 &self,379 out: &mut dyn std::fmt::Write,380 error: &Error,381 ) -> Result<(), std::fmt::Error> {382 struct ResetData {383 loc: Span,384 }385 use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};386387 write!(out, "{}", error.error())?;388 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {389 writeln!(out)?;390 let offset = error.location.offset;391 let mut builder = SnippetBuilder::new(path.code());392 builder393 .error(Text::single("syntax error".chars(), Formatting::default()))394 .range(offset..=offset)395 .build();396 let source = builder.build();397 let ansi = source_to_ansi(&source);398 write!(out, "{ansi}")?;399 }400 let trace = &error.trace();401 let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);402 let mut last_location: Option<Span> = None;403 let mut flush_builder = |data: Option<ResetData>| {404 use std::fmt::Write;405 let mut out = String::new();406 let location_changed = if let Some(ResetData { loc }) = &data {407 if last_location.as_ref().map(|l| l.0.code()) != Some(loc.0.code()) {408 true409 } else if let (Some(last), new) = (&last_location, loc) {410 // Reverse condition if traceback411 last.1 > new.1 || last.2 > new.2412 } else {413 false414 }415 } else {416 true417 };418 if location_changed {419 if let Some(builder) = snippet_builder.borrow_mut().take() {420 let rendered = builder.build();421 let ansi = source_to_ansi(&rendered);422 if let Some(loc) = &last_location {423 let _ = writeln!(out, "...because of {}", loc.0.source_path());424 }425 let _ = write!(out, "{}", ansi.trim_end());426 }427 last_location = None;428429 if let Some(ResetData { loc }) = data {430 *snippet_builder.borrow_mut() = Some(SnippetBuilder::new(loc.0.code()));431 last_location = Some(loc);432 }433 }434 if out.is_empty() {435 return None;436 }437 Some(out)438 };439 for item in &trace.0 {440 let desc = &item.desc;441 if let Some(source) = &item.location {442 if let Some(flushed) = flush_builder(Some(ResetData {443 loc: source.clone(),444 })) {445 writeln!(out)?;446 write!(out, "{flushed}")?;447 }448 let mut builder = snippet_builder.borrow_mut();449 let builder = builder.as_mut().unwrap();450 builder451 .note(Text::single(desc.chars(), Formatting::default()))452 .range(source.1 as usize..=(source.2 as usize - 1).max(source.1 as usize))453 .build();454 } else {455 if let Some(flushed) = flush_builder(None) {456 writeln!(out)?;457 write!(out, "{flushed}")?;458 }459 write!(out, "{desc}")?;460 }461 }462463 if let Some(flushed) = flush_builder(None) {464 writeln!(out)?;465 write!(out, "{flushed}")?;466 }467 Ok(())468 }469470 fn as_any(&self) -> &dyn Any {471 self472 }473474 fn as_any_mut(&mut self) -> &mut dyn Any {475 self476 }477}crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -376,7 +376,7 @@
State, Val,
function::{builtin::{Builtin, StaticBuiltin, BuiltinParam, ParamName, ParamDefault}, CallLocation, ArgsLike, parse::parse_builtin_call},
Result, Context, typed::Typed,
- parser::ExprLocation,
+ parser::Span,
};
const PARAMS: &'static [BuiltinParam] = &[
#(#params_desc)*
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -385,17 +385,16 @@
#[derive(Clone, PartialEq, Eq, Trace)]
#[trace(skip)]
#[repr(C)]
-pub struct ExprLocation(pub Source, pub u32, pub u32);
-impl ExprLocation {
- pub fn belongs_to(&self, other: &ExprLocation) -> bool {
+pub struct Span(pub Source, pub u32, pub u32);
+impl Span {
+ pub fn belongs_to(&self, other: &Span) -> bool {
other.0 == self.0 && other.1 <= self.1 && other.2 >= self.2
}
}
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(ExprLocation, [u8; 16]);
+static_assertions::assert_eq_size!(Span, (usize, usize));
-impl Debug for ExprLocation {
+impl Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
}
@@ -403,19 +402,32 @@
/// Holds AST expression and its location in source file
#[derive(Clone, PartialEq, Trace)]
-pub struct LocExpr(pub Rc<Expr>, pub ExprLocation);
+pub struct LocExpr(Rc<(Expr, Span)>);
+impl LocExpr {
+ pub fn new(expr: Expr, span: Span) -> Self {
+ Self(Rc::new((expr, span)))
+ }
+ #[inline]
+ pub fn span(&self) -> Span {
+ self.0 .1.clone()
+ }
+ #[inline]
+ pub fn expr(&self) -> &Expr {
+ &self.0 .0
+ }
+}
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(LocExpr, [u8; 24]);
+static_assertions::assert_eq_size!(LocExpr, usize);
impl Debug for LocExpr {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let expr = self.expr();
if f.alternate() {
- write!(f, "{:#?}", self.0)?;
+ write!(f, "{:#?}", expr)?;
} else {
- write!(f, "{:?}", self.0)?;
+ write!(f, "{:?}", expr)?;
}
- write!(f, " from {:?}", self.1)?;
+ write!(f, " from {:?}", self.span())?;
Ok(())
}
}
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -232,7 +232,7 @@
pub rule var_expr(s: &ParserSettings) -> Expr
= n:id() { expr::Expr::Var(n) }
pub rule id_loc(s: &ParserSettings) -> LocExpr
- = a:position!() n:id() b:position!() { LocExpr(Rc::new(expr::Expr::Str(n)), ExprLocation(s.source.clone(), a as u32,b as u32)) }
+ = a:position!() n:id() b:position!() { LocExpr::new(expr::Expr::Str(n), Span(s.source.clone(), a as u32,b as u32)) }
pub rule if_then_else_expr(s: &ParserSettings) -> Expr
= cond:ifspec(s) _ keyword("then") _ cond_then:expr(s) cond_else:(_ keyword("else") _ e:expr(s) {e})? {Expr::IfElse{
cond,
@@ -299,7 +299,7 @@
use UnaryOpType::*;
rule expr(s: &ParserSettings) -> LocExpr
= precedence! {
- start:position!() v:@ end:position!() { LocExpr(Rc::new(v), ExprLocation(s.source.clone(), start as u32, end as u32)) }
+ start:position!() v:@ end:position!() { LocExpr::new(v, Span(s.source.clone(), start as u32, end as u32)) }
--
a:(@) _ binop(<"||">) _ b:@ {expr_bin!(a Or b)}
a:(@) _ binop(<"??">) _ ensure_null_coaelse() b:@ {
@@ -370,10 +370,7 @@
/// Used for importstr values
pub fn string_to_expr(str: IStr, settings: &ParserSettings) -> LocExpr {
let len = str.len();
- LocExpr(
- Rc::new(Expr::Str(str)),
- ExprLocation(settings.source.clone(), 0, len as u32),
- )
+ LocExpr::new(Expr::Str(str), Span(settings.source.clone(), 0, len as u32))
}
#[cfg(test)]
@@ -398,9 +395,9 @@
macro_rules! el {
($expr:expr, $from:expr, $to:expr$(,)?) => {
- LocExpr(
- std::rc::Rc::new($expr),
- ExprLocation(
+ LocExpr::new(
+ $expr,
+ Span(
Source::new_virtual("<test>".into(), IStr::empty()),
$from,
$to,