git.delta.rocks / jrsonnet / refs/commits / b5d51b90d7ba

difftreelog

source

crates/jrsonnet-evaluator/src/trace/mod.rs10.9 KiBsourcehistory
1use 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}