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.rsdiffbeforeafterboth1use std::{2 cmp::Ordering,3 convert::Infallible,4 fmt::{Debug, Display},5 path::PathBuf,6};78use jrsonnet_gcmodule::Trace;9use jrsonnet_interner::IStr;10use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};11use jrsonnet_types::ValType;12use thiserror::Error;1314use crate::{15 function::{builtin::ParamDefault, CallLocation},16 stdlib::format::FormatError,17 typed::TypeLocError,18 val::ConvertNumValueError,19 ObjValue,20};2122pub(crate) fn format_found(list: &[IStr], what: &str) -> String {23 if list.is_empty() {24 return String::new();25 }26 let mut out = String::new();27 out.push_str("\nThere is ");28 out.push_str(what);29 if list.len() > 1 {30 out.push('s');31 }32 out.push_str(" with similar name");33 if list.len() > 1 {34 out.push('s');35 }36 out.push_str(" present: ");37 for (i, v) in list.iter().enumerate() {38 if i != 0 {39 out.push_str(", ");40 }41 out.push_str(v as &str);42 }43 out44}4546fn format_signature(sig: &FunctionSignature) -> String {47 let mut out = String::new();48 out.push_str("\nFunction has the following signature: ");49 out.push('(');50 if sig.is_empty() {51 out.push_str("/*no arguments*/");52 } else {53 for (i, (name, default)) in sig.iter().enumerate() {54 if i != 0 {55 out.push_str(", ");56 }57 if let Some(name) = name {58 out.push_str(name);59 } else {60 out.push_str("<unnamed>");61 }62 match default {63 ParamDefault::None => {}64 ParamDefault::Exists => out.push_str(" = <default>"),65 ParamDefault::Literal(lit) => {66 out.push_str(" = ");67 out.push_str(lit);68 }69 }70 }71 }72 out.push(')');73 out74}7576const fn format_empty_str(str: &str) -> &str {77 if str.is_empty() {78 "\"\" (empty string)"79 } else {80 str81 }82}8384pub(crate) fn suggest_object_fields(v: &ObjValue, key: IStr) -> Vec<IStr> {85 let mut heap = Vec::new();86 for field in v.fields_ex(87 true,88 #[cfg(feature = "exp-preserve-order")]89 false,90 ) {91 let conf = strsim::jaro_winkler(field.as_str(), key.as_str());92 if conf < 0.8 {93 continue;94 }95 assert!(field.as_str() != key.as_str(), "looks like string pooling failure, please write any info regarding this crash to https://github.com/CertainLach/jrsonnet/issues/113, thanks!");9697 heap.push((conf, field));98 }99 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));100 heap.into_iter().map(|v| v.1).collect()101}102103type FunctionSignature = Vec<(Option<IStr>, ParamDefault)>;104105/// Possible errors106#[allow(missing_docs)]107#[derive(Error, Debug, Clone, Trace)]108#[non_exhaustive]109pub enum ErrorKind {110 #[error("intrinsic not found: {0}")]111 IntrinsicNotFound(IStr),112113 #[error("operator {0} does not operate on type {1}")]114 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),115 #[error("binary operation {1} {0} {2} is not implemented")]116 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),117118 #[error("no top level object in this context")]119 NoTopLevelObjectFound,120 #[error("self is only usable inside objects")]121 CantUseSelfOutsideOfObject,122 #[error("no super found")]123 NoSuperFound,124125 #[error("for loop can only iterate over arrays")]126 InComprehensionCanOnlyIterateOverArray,127128 #[error("array out of bounds: {0} is not within [0,{1})")]129 ArrayBoundsError(isize, usize),130 #[error("string out of bounds: {0} is not within [0,{1})")]131 StringBoundsError(usize, usize),132133 #[error("assert failed: {}", format_empty_str(.0))]134 AssertionFailed(IStr),135136 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]137 VariableIsNotDefined(IStr, Vec<IStr>),138 #[error("duplicate local var: {0}")]139 DuplicateLocalVar(IStr),140141 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]142 TypeMismatch(&'static str, Vec<ValType>, ValType),143 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]144 NoSuchField(IStr, Vec<IStr>),145146 #[error("only functions can be called, got {0}")]147 OnlyFunctionsCanBeCalledGot(ValType),148 #[error("parameter {0} is not defined")]149 UnknownFunctionParameter(String),150 #[error("argument {0} is already bound")]151 BindingParameterASecondTime(IStr),152 #[error("too many args, function has {0}{}", format_signature(.1))]153 TooManyArgsFunctionHas(usize, FunctionSignature),154 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]155 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),156157 #[error("external variable is not defined: {0}")]158 UndefinedExternalVariable(IStr),159160 #[error("field name should be string, got {0}")]161 FieldMustBeStringGot(ValType),162 #[error("duplicate field name: {}", format_empty_str(.0))]163 DuplicateFieldName(IStr),164165 #[error("attempted to index array with string {}", format_empty_str(.0))]166 AttemptedIndexAnArrayWithString(IStr),167 #[error("{0} index type should be {1}, got {2}")]168 ValueIndexMustBeTypeGot(ValType, ValType, ValType),169 #[error("cant index into {0}")]170 CantIndexInto(ValType),171 #[error("{0} is not indexable")]172 ValueIsNotIndexable(ValType),173174 #[error("super can't be used standalone")]175 StandaloneSuper,176177 #[error("can't resolve {1} from {0}")]178 ImportFileNotFound(SourcePath, String),179 #[error("can't resolve absolute {0}")]180 AbsoluteImportFileNotFound(PathBuf),181 #[error("resolved file not found: {:?}", .0)]182 ResolvedFileNotFound(SourcePath),183 #[error("can't import {0}: is a directory")]184 ImportIsADirectory(SourcePath),185 #[error("imported file is not valid utf-8: {0:?}")]186 ImportBadFileUtf8(SourcePath),187 #[error("import io error: {0}")]188 ImportIo(String),189 #[error("tried to import {1} from {0}, but imports are not supported")]190 ImportNotSupported(SourcePath, String),191 #[error("tried to import {0}, but absolute imports are not supported")]192 AbsoluteImportNotSupported(PathBuf),193 #[error("can't import from virtual file")]194 CantImportFromVirtualFile,195 #[error(196 "syntax error: {}",197 // Peg has no fancier way to handle critical parsing errors https://github.com/kevinmehall/rust-peg/issues/225198 {.error.expected.tokens().find(|t| t.starts_with("!!!")).map_or_else(|| {199 format!(200 "expected {}, got {:?}",201 .error.expected,202 .path.code().chars().nth(error.location.offset)203 .map_or_else(|| "EOF".into(), |c| c.to_string())204 )205 }, |v| v[3..].into())}206 )]207 ImportSyntaxError {208 path: Source,209 #[trace(skip)]210 error: Box<jrsonnet_parser::ParseError>,211 },212213 #[error("runtime error: {}", format_empty_str(.0))]214 RuntimeError(IStr),215 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]216 StackOverflow,217 #[error("infinite recursion detected")]218 InfiniteRecursionDetected,219 #[error("tried to index by fractional value")]220 FractionalIndex,221 #[error("attempted to divide by zero")]222 DivisionByZero,223224 #[error("string manifest output is not an string")]225 StringManifestOutputIsNotAString,226 #[error("stream manifest output is not an array")]227 StreamManifestOutputIsNotAArray,228 #[error("multi manifest output is not an object")]229 MultiManifestOutputIsNotAObject,230231 #[error("cant recurse stream manifest")]232 StreamManifestOutputCannotBeRecursed,233 #[error("stream manifest output cannot consist of raw strings")]234 StreamManifestCannotNestString,235236 #[error("{}", format_empty_str(.0))]237 ImportCallbackError(String),238 #[error("invalid unicode codepoint: {0}")]239 InvalidUnicodeCodepointGot(u32),240241 #[error("convert num value: {0}")]242 ConvertNumValue(#[from] ConvertNumValueError),243244 #[error("format error: {0}")]245 Format(#[from] FormatError),246 #[error("type error: {0}")]247 TypeError(TypeLocError),248249 #[cfg(feature = "anyhow-error")]250 #[error(transparent)]251 Other(#[trace(skip)] std::rc::Rc<anyhow::Error>),252}253254#[cfg(feature = "anyhow-error")]255impl From<anyhow::Error> for Error {256 fn from(e: anyhow::Error) -> Self {257 Self::new(ErrorKind::Other(std::rc::Rc::new(e)))258 }259}260261impl From<ErrorKind> for Error {262 fn from(e: ErrorKind) -> Self {263 Self::new(e)264 }265}266267impl From<Infallible> for Error {268 fn from(_value: Infallible) -> Self {269 unreachable!()270 }271}272273/// Single stack trace frame274#[derive(Clone, Debug, Trace)]275pub struct StackTraceElement {276 /// Source of this frame277 /// Some frames only act as description, without attached source278 pub location: Option<ExprLocation>,279 /// Frame description280 pub desc: String,281}282#[derive(Debug, Clone, Trace)]283pub struct StackTrace(pub Vec<StackTraceElement>);284285#[derive(Clone, Trace)]286pub struct Error(Box<(ErrorKind, StackTrace)>);287impl Error {288 pub fn new(e: ErrorKind) -> Self {289 Self(Box::new((e, StackTrace(vec![]))))290 }291292 pub const fn error(&self) -> &ErrorKind {293 &(self.0).0294 }295 pub fn error_mut(&mut self) -> &mut ErrorKind {296 &mut (self.0).0297 }298 pub const fn trace(&self) -> &StackTrace {299 &(self.0).1300 }301 pub fn trace_mut(&mut self) -> &mut StackTrace {302 &mut (self.0).1303 }304}305impl Display for Error {306 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {307 writeln!(f, "{}", self.0 .0)?;308 for el in &self.0 .1 .0 {309 write!(f, "\t{}", el.desc)?;310 if let Some(loc) = &el.location {311 write!(f, "at {}", loc.0 .0 .0)?;312 loc.0.map_source_locations(&[loc.1, loc.2]);313 }314 writeln!(f)?;315 }316 Ok(())317 }318}319impl Debug for Error {320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {321 f.debug_tuple("LocError").field(&self.0).finish()322 }323}324impl std::error::Error for Error {}325326pub trait ErrorSource {327 fn to_location(self) -> Option<ExprLocation>;328}329impl ErrorSource for &LocExpr {330 fn to_location(self) -> Option<ExprLocation> {331 Some(self.1.clone())332 }333}334impl ErrorSource for &ExprLocation {335 fn to_location(self) -> Option<ExprLocation> {336 Some(self.clone())337 }338}339impl ErrorSource for CallLocation<'_> {340 fn to_location(self) -> Option<ExprLocation> {341 self.0.cloned()342 }343}344345pub type Result<V, E = Error> = std::result::Result<V, E>;346pub trait ResultExt: Sized {347 #[must_use]348 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;349 #[must_use]350 fn description(self, msg: &str) -> Self {351 self.with_description(|| msg)352 }353354 #[must_use]355 fn with_description_src<O: Into<String>>(356 self,357 src: impl ErrorSource,358 msg: impl FnOnce() -> O,359 ) -> Self;360 #[must_use]361 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {362 self.with_description_src(src, || msg)363 }364}365impl<T> ResultExt for Result<T, Error> {366 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {367 if let Err(e) = &mut self {368 let trace = e.trace_mut();369 trace.0.push(StackTraceElement {370 location: None,371 desc: msg().into(),372 });373 }374 self375 }376377 fn with_description_src<O: Into<String>>(378 mut self,379 src: impl ErrorSource,380 msg: impl FnOnce() -> O,381 ) -> Self {382 if let Err(e) = &mut self {383 let trace = e.trace_mut();384 trace.0.push(StackTraceElement {385 location: src.to_location(),386 desc: msg().into(),387 });388 }389 self390 }391}392393#[macro_export]394macro_rules! bail {395 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {396 return Err($w$(::$i)*$(($($tt)*))?.into())397 };398 ($w:ident$(::$i:ident)*$({$($tt:tt)*})?) => {399 return Err($w$(::$i)*$({$($tt)*})?.into())400 };401 ($l:literal$(, $($tt:tt)*)?) => {402 return Err($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)).into())403 };404}405406#[macro_export]407macro_rules! runtime_error {408 ($l:literal$(, $($tt:tt)*)?) => {409 $crate::error::Error::from($crate::error::ErrorKind::RuntimeError($crate::jrsonnet_macros::format_istr!($l$(, $($tt)*)?)))410 };411}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.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -5,7 +5,7 @@
};
use jrsonnet_gcmodule::Trace;
-use jrsonnet_parser::{CodeLocation, ExprLocation, Source};
+use jrsonnet_parser::{CodeLocation, Source, Span};
use crate::{error::ErrorKind, Error};
@@ -380,7 +380,7 @@
error: &Error,
) -> Result<(), std::fmt::Error> {
struct ResetData {
- loc: ExprLocation,
+ loc: Span,
}
use hi_doc::{source_to_ansi, Formatting, SnippetBuilder, Text};
@@ -399,7 +399,7 @@
}
let trace = &error.trace();
let snippet_builder: RefCell<Option<SnippetBuilder>> = RefCell::new(None);
- let mut last_location: Option<ExprLocation> = None;
+ let mut last_location: Option<Span> = None;
let mut flush_builder = |data: Option<ResetData>| {
use std::fmt::Write;
let mut out = String::new();
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,