1use alloc::{
2 borrow::ToOwned,
3 format,
4 string::{String, ToString},
5 vec::Vec,
6};
7use core::{error::Error, fmt, ops::Range};
8
9use crate::{error::replace_control_chars, Arena, Handle, UniqueArena};
10
11#[derive(Clone, Copy, Debug, PartialEq, Default)]
13#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
14pub struct Span {
15 start: u32,
16 end: u32,
17}
18
19impl Span {
20 pub const UNDEFINED: Self = Self { start: 0, end: 0 };
21
22 pub const fn new(start: u32, end: u32) -> Self {
26 Span { start, end }
27 }
28
29 pub const fn until(&self, other: &Self) -> Self {
31 Span {
32 start: self.start,
33 end: other.end,
34 }
35 }
36
37 pub fn subsume(&mut self, other: Self) {
40 *self = if !self.is_defined() {
41 other
43 } else if !other.is_defined() {
44 *self
46 } else {
47 Span {
49 start: self.start.min(other.start),
50 end: self.end.max(other.end),
51 }
52 }
53 }
54
55 pub fn total_span<T: Iterator<Item = Self>>(from: T) -> Self {
58 let mut span: Self = Default::default();
59 for other in from {
60 span.subsume(other);
61 }
62 span
63 }
64
65 pub fn to_range(self) -> Option<Range<usize>> {
67 if self.is_defined() {
68 Some(self.start as usize..self.end as usize)
69 } else {
70 None
71 }
72 }
73
74 pub fn is_defined(&self) -> bool {
76 *self != Self::default()
77 }
78
79 pub fn location(&self, source: &str) -> SourceLocation {
81 let prefix = &source[..self.start as usize];
82 let line_number = prefix.matches('\n').count() as u32 + 1;
83 let line_start = prefix.rfind('\n').map(|pos| pos + 1).unwrap_or(0) as u32;
84 let line_position = self.start - line_start + 1;
85
86 SourceLocation {
87 line_number,
88 line_position,
89 offset: self.start,
90 length: self.end - self.start,
91 }
92 }
93}
94
95impl From<Range<usize>> for Span {
96 fn from(range: Range<usize>) -> Self {
97 Span {
98 start: range.start as u32,
99 end: range.end as u32,
100 }
101 }
102}
103
104impl core::ops::Index<Span> for str {
105 type Output = str;
106
107 #[inline]
108 fn index(&self, span: Span) -> &str {
109 &self[span.start as usize..span.end as usize]
110 }
111}
112
113#[derive(Copy, Clone, Debug, PartialEq, Eq)]
122pub struct SourceLocation {
123 pub line_number: u32,
125 pub line_position: u32,
127 pub offset: u32,
129 pub length: u32,
131}
132
133pub type SpanContext = (Span, String);
135
136#[derive(Debug, Clone)]
138pub struct WithSpan<E> {
139 inner: E,
140 spans: Vec<SpanContext>,
141}
142
143impl<E> fmt::Display for WithSpan<E>
144where
145 E: fmt::Display,
146{
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 self.inner.fmt(f)
149 }
150}
151
152#[cfg(test)]
153impl<E> PartialEq for WithSpan<E>
154where
155 E: PartialEq,
156{
157 fn eq(&self, other: &Self) -> bool {
158 self.inner.eq(&other.inner)
159 }
160}
161
162impl<E> Error for WithSpan<E>
163where
164 E: Error,
165{
166 fn source(&self) -> Option<&(dyn Error + 'static)> {
167 self.inner.source()
168 }
169}
170
171impl<E> WithSpan<E> {
172 pub const fn new(inner: E) -> Self {
174 Self {
175 inner,
176 spans: Vec::new(),
177 }
178 }
179
180 pub fn into_inner(self) -> E {
182 self.inner
183 }
184
185 pub const fn as_inner(&self) -> &E {
186 &self.inner
187 }
188
189 pub fn spans(&self) -> impl ExactSizeIterator<Item = &SpanContext> {
191 self.spans.iter()
192 }
193
194 pub fn with_span<S>(mut self, span: Span, description: S) -> Self
196 where
197 S: ToString,
198 {
199 if span.is_defined() {
200 self.spans.push((span, description.to_string()));
201 }
202 self
203 }
204
205 pub fn with_context(self, span_context: SpanContext) -> Self {
207 let (span, description) = span_context;
208 self.with_span(span, description)
209 }
210
211 pub(crate) fn with_handle<T, A: SpanProvider<T>>(self, handle: Handle<T>, arena: &A) -> Self {
214 self.with_context(arena.get_span_context(handle))
215 }
216
217 pub fn into_other<E2>(self) -> WithSpan<E2>
219 where
220 E2: From<E>,
221 {
222 WithSpan {
223 inner: self.inner.into(),
224 spans: self.spans,
225 }
226 }
227
228 pub fn and_then<F, E2>(self, func: F) -> WithSpan<E2>
231 where
232 F: FnOnce(E) -> WithSpan<E2>,
233 {
234 let mut res = func(self.inner);
235 res.spans.extend(self.spans);
236 res
237 }
238
239 pub fn location(&self, source: &str) -> Option<SourceLocation> {
241 if self.spans.is_empty() || source.is_empty() {
242 return None;
243 }
244
245 Some(self.spans[0].0.location(source))
246 }
247
248 pub(crate) fn diagnostic(&self) -> codespan_reporting::diagnostic::Diagnostic<()>
249 where
250 E: Error,
251 {
252 use codespan_reporting::diagnostic::{Diagnostic, Label};
253 let diagnostic = Diagnostic::error()
254 .with_message(self.inner.to_string())
255 .with_labels(
256 self.spans()
257 .map(|&(span, ref desc)| {
258 Label::primary((), span.to_range().unwrap()).with_message(desc.to_owned())
259 })
260 .collect(),
261 )
262 .with_notes({
263 let mut notes = Vec::new();
264 let mut source: &dyn Error = &self.inner;
265 while let Some(next) = Error::source(source) {
266 notes.push(next.to_string());
267 source = next;
268 }
269 notes
270 });
271 diagnostic
272 }
273
274 #[cfg(feature = "stderr")]
276 pub fn emit_to_stderr(&self, source: &str)
277 where
278 E: Error,
279 {
280 self.emit_to_stderr_with_path(source, "wgsl")
281 }
282
283 #[cfg(feature = "stderr")]
285 pub fn emit_to_stderr_with_path(&self, source: &str, path: &str)
286 where
287 E: Error,
288 {
289 use codespan_reporting::{files, term};
290
291 let files = files::SimpleFile::new(path, replace_control_chars(source));
292 let config = term::Config::default();
293
294 cfg_if::cfg_if! {
295 if #[cfg(feature = "termcolor")] {
296 let writer = term::termcolor::StandardStream::stderr(term::termcolor::ColorChoice::Auto);
297 } else {
298 let writer = std::io::stderr();
299 }
300 }
301
302 term::emit(&mut writer.lock(), &config, &files, &self.diagnostic())
303 .expect("cannot write error");
304 }
305
306 pub fn emit_to_string(&self, source: &str) -> String
308 where
309 E: Error,
310 {
311 self.emit_to_string_with_path(source, "wgsl")
312 }
313
314 pub fn emit_to_string_with_path(&self, source: &str, path: &str) -> String
316 where
317 E: Error,
318 {
319 use codespan_reporting::{files, term};
320
321 let files = files::SimpleFile::new(path, replace_control_chars(source));
322 let config = term::Config::default();
323
324 let mut writer = crate::error::DiagnosticBuffer::new();
325 term::emit(writer.inner_mut(), &config, &files, &self.diagnostic())
326 .expect("cannot write error");
327 writer.into_string()
328 }
329}
330
331pub(crate) trait AddSpan: Sized {
333 type Output;
335
336 fn with_span(self) -> Self::Output;
338 fn with_span_static(self, span: Span, description: &'static str) -> Self::Output;
340 fn with_span_context(self, span_context: SpanContext) -> Self::Output;
342 fn with_span_handle<T, A: SpanProvider<T>>(self, handle: Handle<T>, arena: &A) -> Self::Output;
344}
345
346impl<E> AddSpan for E {
347 type Output = WithSpan<Self>;
348
349 fn with_span(self) -> WithSpan<Self> {
350 WithSpan::new(self)
351 }
352
353 fn with_span_static(self, span: Span, description: &'static str) -> WithSpan<Self> {
354 WithSpan::new(self).with_span(span, description)
355 }
356
357 fn with_span_context(self, span_context: SpanContext) -> WithSpan<Self> {
358 WithSpan::new(self).with_context(span_context)
359 }
360
361 fn with_span_handle<T, A: SpanProvider<T>>(
362 self,
363 handle: Handle<T>,
364 arena: &A,
365 ) -> WithSpan<Self> {
366 WithSpan::new(self).with_handle(handle, arena)
367 }
368}
369
370pub(crate) trait SpanProvider<T> {
372 fn get_span(&self, handle: Handle<T>) -> Span;
373 fn get_span_context(&self, handle: Handle<T>) -> SpanContext {
374 match self.get_span(handle) {
375 x if !x.is_defined() => (Default::default(), "".to_string()),
376 known => (
377 known,
378 format!("{} {:?}", core::any::type_name::<T>(), handle),
379 ),
380 }
381 }
382}
383
384impl<T> SpanProvider<T> for Arena<T> {
385 fn get_span(&self, handle: Handle<T>) -> Span {
386 self.get_span(handle)
387 }
388}
389
390impl<T> SpanProvider<T> for UniqueArena<T> {
391 fn get_span(&self, handle: Handle<T>) -> Span {
392 self.get_span(handle)
393 }
394}
395
396pub(crate) trait MapErrWithSpan<E, E2>: Sized {
399 type Output: Sized;
401
402 fn map_err_inner<F, E3>(self, func: F) -> Self::Output
403 where
404 F: FnOnce(E) -> WithSpan<E3>,
405 E2: From<E3>;
406}
407
408impl<T, E, E2> MapErrWithSpan<E, E2> for Result<T, WithSpan<E>> {
409 type Output = Result<T, WithSpan<E2>>;
410
411 fn map_err_inner<F, E3>(self, func: F) -> Result<T, WithSpan<E2>>
412 where
413 F: FnOnce(E) -> WithSpan<E3>,
414 E2: From<E3>,
415 {
416 self.map_err(|e| e.and_then(func).into_other::<E2>())
417 }
418}
419
420#[test]
421fn span_location() {
422 let source = "12\n45\n\n89\n";
423 assert_eq!(
424 Span { start: 0, end: 1 }.location(source),
425 SourceLocation {
426 line_number: 1,
427 line_position: 1,
428 offset: 0,
429 length: 1
430 }
431 );
432 assert_eq!(
433 Span { start: 1, end: 2 }.location(source),
434 SourceLocation {
435 line_number: 1,
436 line_position: 2,
437 offset: 1,
438 length: 1
439 }
440 );
441 assert_eq!(
442 Span { start: 2, end: 3 }.location(source),
443 SourceLocation {
444 line_number: 1,
445 line_position: 3,
446 offset: 2,
447 length: 1
448 }
449 );
450 assert_eq!(
451 Span { start: 3, end: 5 }.location(source),
452 SourceLocation {
453 line_number: 2,
454 line_position: 1,
455 offset: 3,
456 length: 2
457 }
458 );
459 assert_eq!(
460 Span { start: 4, end: 6 }.location(source),
461 SourceLocation {
462 line_number: 2,
463 line_position: 2,
464 offset: 4,
465 length: 2
466 }
467 );
468 assert_eq!(
469 Span { start: 5, end: 6 }.location(source),
470 SourceLocation {
471 line_number: 2,
472 line_position: 3,
473 offset: 5,
474 length: 1
475 }
476 );
477 assert_eq!(
478 Span { start: 6, end: 7 }.location(source),
479 SourceLocation {
480 line_number: 3,
481 line_position: 1,
482 offset: 6,
483 length: 1
484 }
485 );
486 assert_eq!(
487 Span { start: 7, end: 8 }.location(source),
488 SourceLocation {
489 line_number: 4,
490 line_position: 1,
491 offset: 7,
492 length: 1
493 }
494 );
495 assert_eq!(
496 Span { start: 8, end: 9 }.location(source),
497 SourceLocation {
498 line_number: 4,
499 line_position: 2,
500 offset: 8,
501 length: 1
502 }
503 );
504 assert_eq!(
505 Span { start: 9, end: 10 }.location(source),
506 SourceLocation {
507 line_number: 4,
508 line_position: 3,
509 offset: 9,
510 length: 1
511 }
512 );
513 assert_eq!(
514 Span { start: 10, end: 11 }.location(source),
515 SourceLocation {
516 line_number: 5,
517 line_position: 1,
518 offset: 10,
519 length: 1
520 }
521 );
522}