difftreelog
refactor remove trace format from state
in: master
5 files changed
cmds/jrsonnet/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -51,6 +51,9 @@
input: InputOpts,
#[clap(flatten)]
general: GeneralOpts,
+
+ #[clap(flatten)]
+ trace: TraceOpts,
#[clap(flatten)]
manifest: ManifestOpts,
#[clap(flatten)]
@@ -114,9 +117,15 @@
fn main_catch(opts: Opts) -> bool {
let s = State::default();
+ let trace = opts
+ .trace
+ .configure(&s)
+ .expect("this configurator doesn't fail");
if let Err(e) = main_real(&s, opts) {
if let Error::Evaluation(e) = e {
- eprintln!("{}", s.stringify_err(&e));
+ let mut out = String::new();
+ trace.write_trace(&mut out, &e).expect("format error");
+ eprintln!("{out}")
} else {
eprintln!("{}", e);
}
crates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -76,9 +76,6 @@
std: StdOpts,
#[clap(flatten)]
- trace: TraceOpts,
-
- #[clap(flatten)]
gc: GcOpts,
}
@@ -90,7 +87,6 @@
);
fn configure(&self, s: &State) -> Result<Self::Guards> {
// Configure trace first, because tla-code/ext-code can throw
- self.trace.configure(s)?;
let misc_guards = self.misc.configure(s)?;
let tla_guards = self.tla.configure(s)?;
self.std.configure(s)?;
crates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,7 +1,7 @@
use clap::{Parser, ValueEnum};
use jrsonnet_evaluator::{
error::Result,
- trace::{CompactFormat, ExplainingFormat, PathResolver},
+ trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat},
State,
};
@@ -27,21 +27,25 @@
max_trace: usize,
}
impl ConfigureState for TraceOpts {
- type Guards = ();
- fn configure(&self, s: &State) -> Result<()> {
+ type Guards = Box<dyn TraceFormat>;
+ fn configure(&self, _s: &State) -> Result<Self::Guards> {
let resolver = PathResolver::new_cwd_fallback();
- match self
+ let max_trace = self.max_trace;
+ let format: Box<dyn TraceFormat> = match self
.trace_format
.as_ref()
.unwrap_or(&TraceFormatName::Compact)
{
- TraceFormatName::Compact => s.set_trace_format(CompactFormat {
+ TraceFormatName::Compact => Box::new(CompactFormat {
resolver,
padding: 4,
+ max_trace,
}),
- TraceFormatName::Explaining => s.set_trace_format(ExplainingFormat { resolver }),
- }
- s.set_max_trace(self.max_trace);
- Ok(())
+ TraceFormatName::Explaining => Box::new(ExplainingFormat {
+ resolver,
+ max_trace,
+ }),
+ };
+ Ok(format)
}
}
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth1use std::{2 fmt::{Debug, Display},3 path::PathBuf,4};56use jrsonnet_gcmodule::Trace;7use jrsonnet_interner::IStr;8use jrsonnet_parser::{BinaryOpType, ExprLocation, LocExpr, Source, SourcePath, UnaryOpType};9use jrsonnet_types::ValType;10use thiserror::Error;1112use crate::{function::CallLocation, stdlib::format::FormatError, typed::TypeLocError};1314fn format_found(list: &[IStr], what: &str) -> String {15 if list.is_empty() {16 return String::new();17 }18 let mut out = String::new();19 out.push_str("\nThere is ");20 out.push_str(what);21 if list.len() > 1 {22 out.push('s');23 }24 out.push_str(" with similar name");25 if list.len() > 1 {26 out.push('s');27 }28 out.push_str(" present: ");29 for (i, v) in list.iter().enumerate() {30 if i != 0 {31 out.push_str(", ");32 }33 out.push_str(v as &str);34 }35 out36}3738fn format_signature(sig: &FunctionSignature) -> String {39 let mut out = String::new();40 out.push_str("\nFunction has the following signature: ");41 out.push('(');42 if sig.is_empty() {43 out.push_str("/*no arguments*/");44 } else {45 for (i, (name, has_default)) in sig.iter().enumerate() {46 if i != 0 {47 out.push_str(", ");48 }49 if let Some(name) = name {50 out.push_str(name);51 } else {52 out.push_str("<unnamed>");53 }54 if *has_default {55 out.push_str(" = <default>");56 }57 }58 }59 out.push(')');60 out61}6263const fn format_empty_str(str: &str) -> &str {64 if str.is_empty() {65 "\"\" (empty string)"66 } else {67 str68 }69}7071type FunctionSignature = Vec<(Option<IStr>, bool)>;7273/// Possible errors74#[allow(missing_docs)]75#[derive(Error, Debug, Clone, Trace)]76#[non_exhaustive]77pub enum Error {78 #[error("intrinsic not found: {0}")]79 IntrinsicNotFound(IStr),8081 #[error("operator {0} does not operate on type {1}")]82 UnaryOperatorDoesNotOperateOnType(UnaryOpType, ValType),83 #[error("binary operation {1} {0} {2} is not implemented")]84 BinaryOperatorDoesNotOperateOnValues(BinaryOpType, ValType, ValType),8586 #[error("no top level object in this context")]87 NoTopLevelObjectFound,88 #[error("self is only usable inside objects")]89 CantUseSelfOutsideOfObject,90 #[error("no super found")]91 NoSuperFound,9293 #[error("for loop can only iterate over arrays")]94 InComprehensionCanOnlyIterateOverArray,9596 #[error("array out of bounds: {0} is not within [0,{1})")]97 ArrayBoundsError(usize, usize),98 #[error("string out of bounds: {0} is not within [0,{1})")]99 StringBoundsError(usize, usize),100101 #[error("assert failed: {}", format_empty_str(.0))]102 AssertionFailed(IStr),103104 #[error("variable is not defined: {0}{}", format_found(.1, "variable"))]105 VariableIsNotDefined(IStr, Vec<IStr>),106 #[error("duplicate local var: {0}")]107 DuplicateLocalVar(IStr),108109 #[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]110 TypeMismatch(&'static str, Vec<ValType>, ValType),111 #[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]112 NoSuchField(IStr, Vec<IStr>),113114 #[error("only functions can be called, got {0}")]115 OnlyFunctionsCanBeCalledGot(ValType),116 #[error("parameter {0} is not defined")]117 UnknownFunctionParameter(String),118 #[error("argument {0} is already bound")]119 BindingParameterASecondTime(IStr),120 #[error("too many args, function has {0}{}", format_signature(.1))]121 TooManyArgsFunctionHas(usize, FunctionSignature),122 #[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]123 FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),124125 #[error("external variable is not defined: {0}")]126 UndefinedExternalVariable(IStr),127128 #[error("field name should be string, got {0}")]129 FieldMustBeStringGot(ValType),130 #[error("duplicate field name: {}", format_empty_str(.0))]131 DuplicateFieldName(IStr),132133 #[error("attempted to index array with string {}", format_empty_str(.0))]134 AttemptedIndexAnArrayWithString(IStr),135 #[error("{0} index type should be {1}, got {2}")]136 ValueIndexMustBeTypeGot(ValType, ValType, ValType),137 #[error("cant index into {0}")]138 CantIndexInto(ValType),139 #[error("{0} is not indexable")]140 ValueIsNotIndexable(ValType),141142 #[error("super can't be used standalone")]143 StandaloneSuper,144145 #[error("can't resolve {1} from {0}")]146 ImportFileNotFound(SourcePath, String),147 #[error("can't resolve absolute {0}")]148 AbsoluteImportFileNotFound(PathBuf),149 #[error("resolved file not found: {:?}", .0)]150 ResolvedFileNotFound(SourcePath),151 #[error("can't import {0}: is a directory")]152 ImportIsADirectory(SourcePath),153 #[error("imported file is not valid utf-8: {0:?}")]154 ImportBadFileUtf8(SourcePath),155 #[error("import io error: {0}")]156 ImportIo(String),157 #[error("tried to import {1} from {0}, but imports are not supported")]158 ImportNotSupported(SourcePath, String),159 #[error("tried to import {0}, but absolute imports are not supported")]160 AbsoluteImportNotSupported(PathBuf),161 #[error("can't import from virtual file")]162 CantImportFromVirtualFile,163 #[error(164 "syntax error: expected {}, got {:?}",165 .error.expected,166 .path.code().chars().nth(error.location.offset)167 .map_or_else(|| "EOF".into(), |c| c.to_string())168 )]169 ImportSyntaxError {170 path: Source,171 #[trace(skip)]172 error: Box<jrsonnet_parser::ParseError>,173 },174175 #[error("runtime error: {}", format_empty_str(.0))]176 RuntimeError(IStr),177 #[error("stack overflow, try to reduce recursion, or set --max-stack to bigger value")]178 StackOverflow,179 #[error("infinite recursion detected")]180 InfiniteRecursionDetected,181 #[error("tried to index by fractional value")]182 FractionalIndex,183 #[error("attempted to divide by zero")]184 DivisionByZero,185186 #[error("string manifest output is not an string")]187 StringManifestOutputIsNotAString,188 #[error("stream manifest output is not an array")]189 StreamManifestOutputIsNotAArray,190 #[error("multi manifest output is not an object")]191 MultiManifestOutputIsNotAObject,192193 #[error("cant recurse stream manifest")]194 StreamManifestOutputCannotBeRecursed,195 #[error("stream manifest output cannot consist of raw strings")]196 StreamManifestCannotNestString,197198 #[error("{}", format_empty_str(.0))]199 ImportCallbackError(String),200 #[error("invalid unicode codepoint: {0}")]201 InvalidUnicodeCodepointGot(u32),202203 #[error("format error: {0}")]204 Format(#[from] FormatError),205 #[error("type error: {0}")]206 TypeError(TypeLocError),207208 #[cfg(feature = "anyhow-error")]209 #[error(transparent)]210 Other(Rc<anyhow::Error>),211}212213#[cfg(feature = "anyhow-error")]214impl From<anyhow::Error> for LocError {215 fn from(e: anyhow::Error) -> Self {216 Self::new(Error::Other(Rc::new(e)))217 }218}219220impl From<Error> for LocError {221 fn from(e: Error) -> Self {222 Self::new(e)223 }224}225226/// Single stack trace frame227#[derive(Clone, Debug, Trace)]228pub struct StackTraceElement {229 /// Source of this frame230 /// Some frames only act as description, without attached source231 pub location: Option<ExprLocation>,232 /// Frame description233 pub desc: String,234}235#[derive(Debug, Clone, Trace)]236pub struct StackTrace(pub Vec<StackTraceElement>);237238#[derive(Clone, Trace)]239pub struct LocError(Box<(Error, StackTrace)>);240impl LocError {241 pub fn new(e: Error) -> Self {242 Self(Box::new((e, StackTrace(vec![]))))243 }244245 pub const fn error(&self) -> &Error {246 &(self.0).0247 }248 pub fn error_mut(&mut self) -> &mut Error {249 &mut (self.0).0250 }251 pub const fn trace(&self) -> &StackTrace {252 &(self.0).1253 }254 pub fn trace_mut(&mut self) -> &mut StackTrace {255 &mut (self.0).1256 }257}258impl Display for LocError {259 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {260 writeln!(f, "{}", self.0 .0)?;261 for el in &self.0 .1 .0 {262 write!(f, "\t{}", el.desc)?;263 if let Some(loc) = &el.location {264 write!(f, "at {}", loc.0 .0 .0)?;265 // loc.0266 loc.0.map_source_locations(&[loc.1, loc.2]);267 }268 writeln!(f)?;269 }270 Ok(())271 }272}273impl Debug for LocError {274 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {275 f.debug_tuple("LocError").field(&self.0).finish()276 }277}278279pub trait ErrorSource {280 fn to_location(self) -> Option<ExprLocation>;281}282impl ErrorSource for &LocExpr {283 fn to_location(self) -> Option<ExprLocation> {284 Some(self.1.clone())285 }286}287impl ErrorSource for &ExprLocation {288 fn to_location(self) -> Option<ExprLocation> {289 Some(self.clone())290 }291}292impl ErrorSource for CallLocation<'_> {293 fn to_location(self) -> Option<ExprLocation> {294 self.0.cloned()295 }296}297298pub type Result<V, E = LocError> = std::result::Result<V, E>;299pub trait ResultExt: Sized {300 #[must_use]301 fn with_description<O: Into<String>>(self, msg: impl FnOnce() -> O) -> Self;302 #[must_use]303 fn description(self, msg: &str) -> Self {304 self.with_description(|| msg)305 }306307 #[must_use]308 fn with_description_src<O: Into<String>>(309 self,310 src: impl ErrorSource,311 msg: impl FnOnce() -> O,312 ) -> Self;313 #[must_use]314 fn description_src(self, src: impl ErrorSource, msg: &str) -> Self {315 self.with_description_src(src, || msg)316 }317}318impl<T> ResultExt for Result<T, LocError> {319 fn with_description<O: Into<String>>(mut self, msg: impl FnOnce() -> O) -> Self {320 if let Err(e) = &mut self {321 let trace = e.trace_mut();322 trace.0.push(StackTraceElement {323 location: None,324 desc: msg().into(),325 });326 }327 self328 }329330 fn with_description_src<O: Into<String>>(331 mut self,332 src: impl ErrorSource,333 msg: impl FnOnce() -> O,334 ) -> Self {335 if let Err(e) = &mut self {336 let trace = e.trace_mut();337 trace.0.push(StackTraceElement {338 location: src.to_location(),339 desc: msg().into(),340 });341 }342 self343 }344}345346#[macro_export]347macro_rules! throw {348 ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {349 return Err($w$(::$i)*$(($($tt)*))?.into())350 };351 ($l:literal) => {352 return Err($crate::error::Error::RuntimeError($l.into()).into())353 };354 ($l:literal, $($tt:tt)*) => {355 return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())356 };357}crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -1,9 +1,12 @@
-use std::path::{Path, PathBuf};
+use std::{
+ any::Any,
+ path::{Path, PathBuf},
+};
use jrsonnet_gcmodule::Trace;
use jrsonnet_parser::{CodeLocation, Source};
-use crate::{error::Error, LocError, State};
+use crate::{error::Error, LocError};
/// The way paths should be displayed
#[derive(Clone, Trace)]
@@ -48,9 +51,15 @@
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- s: &State,
error: &LocError,
) -> Result<(), std::fmt::Error>;
+ fn format(&self, error: &LocError) -> Result<String, std::fmt::Error> {
+ let mut out = String::new();
+ self.write_trace(&mut out, error)?;
+ Ok(out)
+ }
+ fn as_any(&self) -> &dyn Any;
+ fn as_any_mut(&mut self) -> &mut dyn Any;
}
fn print_code_location(
@@ -81,14 +90,23 @@
#[derive(Trace)]
pub struct CompactFormat {
pub resolver: PathResolver,
+ pub max_trace: usize,
pub padding: usize,
}
+impl Default for CompactFormat {
+ fn default() -> Self {
+ Self {
+ resolver: PathResolver::Absolute,
+ max_trace: 20,
+ padding: 4,
+ }
+ }
+}
impl TraceFormat for CompactFormat {
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- _s: &State,
error: &LocError,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
@@ -168,15 +186,24 @@
}
Ok(())
}
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
#[derive(Trace)]
-pub struct JsFormat;
+pub struct JsFormat {
+ pub max_trace: usize,
+}
impl TraceFormat for JsFormat {
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- _s: &State,
error: &LocError,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
@@ -201,6 +228,14 @@
}
Ok(())
}
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
/// rustc-like trace displaying
@@ -208,13 +243,13 @@
#[derive(Trace)]
pub struct ExplainingFormat {
pub resolver: PathResolver,
+ pub max_trace: usize,
}
#[cfg(feature = "explaining-traces")]
impl TraceFormat for ExplainingFormat {
fn write_trace(
&self,
out: &mut dyn std::fmt::Write,
- _s: &State,
error: &LocError,
) -> Result<(), std::fmt::Error> {
write!(out, "{}", error.error())?;
@@ -258,6 +293,14 @@
}
Ok(())
}
+
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
impl ExplainingFormat {