1use std::{2 any::Any,3 path::{Path, PathBuf},4};56use jrsonnet_gcmodule::Trace;7use jrsonnet_parser::{CodeLocation, Source};89use crate::{error::ErrorKind, Error};101112#[derive(Clone, Trace)]13pub enum PathResolver {14 15 FileName,16 17 Absolute,18 19 Relative(PathBuf),20}2122impl PathResolver {23 24 pub fn new_cwd_fallback() -> Self {25 std::env::current_dir().map_or(Self::Absolute, Self::Relative)26 }27 pub fn resolve(&self, from: &Path) -> String {28 match self {29 Self::FileName => from30 .file_name()31 .expect("file name exists")32 .to_string_lossy()33 .into_owned(),34 Self::Absolute => from.to_string_lossy().into_owned(),35 Self::Relative(base) => {36 if from.is_relative() {37 return from.to_string_lossy().into_owned();38 }39 pathdiff::diff_paths(from, base)40 .expect("base is absolute")41 .to_string_lossy()42 .into_owned()43 }44 }45 }46}474849#[allow(clippy::module_name_repetitions)]50pub trait TraceFormat: Trace {51 fn write_trace(52 &self,53 out: &mut dyn std::fmt::Write,54 error: &Error,55 ) -> Result<(), std::fmt::Error>;56 fn format(&self, error: &Error) -> Result<String, std::fmt::Error> {57 let mut out = String::new();58 self.write_trace(&mut out, error)?;59 Ok(out)60 }61 fn as_any(&self) -> &dyn Any;62 fn as_any_mut(&mut self) -> &mut dyn Any;63}6465fn print_code_location(66 out: &mut impl std::fmt::Write,67 start: &CodeLocation,68 end: &CodeLocation,69) -> Result<(), std::fmt::Error> {70 if start.line == end.line {71 if start.column == end.column {72 write!(out, "{}:{}", start.line, end.column.saturating_sub(1))?;73 } else {74 write!(out, "{}:{}-{}", start.line, start.column - 1, end.column)?;75 }76 } else {77 write!(78 out,79 "{}:{}-{}:{}",80 start.line,81 end.column.saturating_sub(1),82 start.line,83 end.column84 )?;85 }86 Ok(())87}888990#[derive(Trace)]91pub struct CompactFormat {92 pub resolver: PathResolver,93 pub max_trace: usize,94 pub padding: usize,95}96impl Default for CompactFormat {97 fn default() -> Self {98 Self {99 resolver: PathResolver::Absolute,100 max_trace: 20,101 padding: 4,102 }103 }104}105106impl TraceFormat for CompactFormat {107 fn write_trace(108 &self,109 out: &mut dyn std::fmt::Write,110 error: &Error,111 ) -> Result<(), std::fmt::Error> {112 write!(out, "{}", error.error())?;113 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {114 use std::fmt::Write;115116 writeln!(out)?;117 let mut n = path.source_path().path().map_or_else(118 || path.source_path().to_string(),119 |r| self.resolver.resolve(r),120 );121 let mut offset = error.location.offset;122 let is_eof = if offset >= path.code().len() {123 offset = path.code().len().saturating_sub(1);124 true125 } else {126 false127 };128 let mut location = path129 .map_source_locations(&[offset as u32])130 .into_iter()131 .next()132 .unwrap();133 if is_eof {134 location.column += 1;135 }136137 write!(n, ":").unwrap();138 print_code_location(&mut n, &location, &location).unwrap();139 write!(out, "{:<p$}{n}", "", p = self.padding)?;140 }141 let file_names = error142 .trace()143 .0144 .iter()145 .map(|el| &el.location)146 .map(|location| {147 use std::fmt::Write;148 #[allow(clippy::option_if_let_else)]149 if let Some(location) = location {150 let mut resolved_path = match location.0.source_path().path() {151 Some(r) => self.resolver.resolve(r),152 None => location.0.source_path().to_string(),153 };154 155 let location = location.0.map_source_locations(&[location.1, location.2]);156 write!(resolved_path, ":").unwrap();157 print_code_location(&mut resolved_path, &location[0], &location[1]).unwrap();158 write!(resolved_path, ":").unwrap();159 Some(resolved_path)160 } else {161 None162 }163 })164 .collect::<Vec<_>>();165 let align = file_names166 .iter()167 .flatten()168 .map(String::len)169 .max()170 .unwrap_or(0);171 for (el, file) in error.trace().0.iter().zip(file_names) {172 writeln!(out)?;173 if let Some(file) = file {174 write!(175 out,176 "{:<p$}{:<w$} {}",177 "",178 file,179 el.desc,180 p = self.padding,181 w = align182 )?;183 } else {184 write!(out, "{:<p$}{}", "", el.desc, p = self.padding,)?;185 }186 }187 Ok(())188 }189190 fn as_any(&self) -> &dyn Any {191 self192 }193194 fn as_any_mut(&mut self) -> &mut dyn Any {195 self196 }197}198199#[derive(Trace)]200pub struct JsFormat {201 pub max_trace: usize,202}203impl TraceFormat for JsFormat {204 fn write_trace(205 &self,206 out: &mut dyn std::fmt::Write,207 error: &Error,208 ) -> Result<(), std::fmt::Error> {209 write!(out, "{}", error.error())?;210 for item in &error.trace().0 {211 writeln!(out)?;212 let desc = &item.desc;213 if let Some(source) = &item.location {214 let start_end = source.0.map_source_locations(&[source.1, source.2]);215 let resolved_path = source.0.source_path().path().map_or_else(216 || source.0.source_path().to_string(),217 |r| r.display().to_string(),218 );219220 write!(221 out,222 " at {} ({}:{}:{})",223 desc, resolved_path, start_end[0].line, start_end[0].column,224 )?;225 } else {226 write!(out, " during {desc}")?;227 }228 }229 Ok(())230 }231232 fn as_any(&self) -> &dyn Any {233 self234 }235236 fn as_any_mut(&mut self) -> &mut dyn Any {237 self238 }239}240241242#[cfg(feature = "explaining-traces")]243#[derive(Trace)]244pub struct ExplainingFormat {245 pub resolver: PathResolver,246 pub max_trace: usize,247}248#[cfg(feature = "explaining-traces")]249impl TraceFormat for ExplainingFormat {250 fn write_trace(251 &self,252 out: &mut dyn std::fmt::Write,253 error: &Error,254 ) -> Result<(), std::fmt::Error> {255 write!(out, "{}", error.error())?;256 if let ErrorKind::ImportSyntaxError { path, error } = error.error() {257 writeln!(out)?;258 let offset = error.location.offset;259 let location = path260 .map_source_locations(&[offset as u32])261 .into_iter()262 .next()263 .unwrap();264 let mut end_location = location;265 end_location.offset += 1;266267 self.print_snippet(268 out,269 path.code(),270 path,271 &location,272 &end_location,273 "syntax error",274 )?;275 }276 let trace = &error.trace();277 for item in &trace.0 {278 writeln!(out)?;279 let desc = &item.desc;280 if let Some(source) = &item.location {281 let start_end = source.0.map_source_locations(&[source.1, source.2]);282 self.print_snippet(283 out,284 source.0.code(),285 &source.0,286 &start_end[0],287 &start_end[1],288 desc,289 )?;290 } else {291 write!(out, "{desc}")?;292 }293 }294 Ok(())295 }296297 fn as_any(&self) -> &dyn Any {298 self299 }300301 fn as_any_mut(&mut self) -> &mut dyn Any {302 self303 }304}305306impl ExplainingFormat {307 fn print_snippet(308 &self,309 out: &mut dyn std::fmt::Write,310 source: &str,311 origin: &Source,312 start: &CodeLocation,313 end: &CodeLocation,314 desc: &str,315 ) -> Result<(), std::fmt::Error> {316 use annotate_snippets::{317 display_list::{DisplayList, FormatOptions},318 snippet::{AnnotationType, Slice, Snippet, SourceAnnotation},319 };320321 let source_fragment: String = source322 .chars()323 .skip(start.line_start_offset)324 .take(end.line_end_offset - end.line_start_offset)325 .collect();326327 let origin = origin.source_path().path().map_or_else(328 || origin.source_path().to_string(),329 |r| self.resolver.resolve(r),330 );331 let snippet = Snippet {332 opt: FormatOptions {333 color: true,334 ..FormatOptions::default()335 },336 title: None,337 footer: vec![],338 slices: vec![Slice {339 source: &source_fragment,340 line_start: start.line,341 origin: Some(&origin),342 fold: false,343 annotations: vec![SourceAnnotation {344 label: desc,345 annotation_type: AnnotationType::Error,346 range: (347 start.offset - start.line_start_offset,348 (end.offset.saturating_sub(start.line_start_offset))349 .min(source_fragment.len()),350 ),351 }],352 }],353 };354355 let dl = DisplayList::from(snippet);356 write!(out, "{dl}")?;357358 Ok(())359 }360}