microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
source/compiler/qsc/src/error.rs
84lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | use miette::Diagnostic; |
| 5 | pub use qsc_data_structures::error::WithSource; |
| 6 | use qsc_frontend::compile::PackageStore; |
| 7 | use std::fmt::{self, Debug, Display, Formatter}; |
| 8 | use thiserror::Error; |
| 9 | |
| 10 | #[derive(Clone, Debug, Error)] |
| 11 | pub struct WithStack<E> { |
| 12 | error: E, |
| 13 | stack_trace: Option<String>, |
| 14 | } |
| 15 | |
| 16 | impl<E> WithStack<E> { |
| 17 | pub(super) fn new(error: E, stack_trace: Option<String>) -> Self { |
| 18 | WithStack { error, stack_trace } |
| 19 | } |
| 20 | |
| 21 | pub(super) fn stack_trace(&self) -> Option<&String> { |
| 22 | self.stack_trace.as_ref() |
| 23 | } |
| 24 | |
| 25 | pub fn error(&self) -> &E { |
| 26 | &self.error |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | impl<E: Display> Display for WithStack<E> { |
| 31 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 32 | std::fmt::Display::fmt(&self.error, f) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | // #[diagnostic(transparent)] does not seem to work with generics |
| 37 | impl<E: Diagnostic> Diagnostic for WithStack<E> { |
| 38 | fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> { |
| 39 | self.error.code() |
| 40 | } |
| 41 | |
| 42 | fn severity(&self) -> Option<miette::Severity> { |
| 43 | self.error.severity() |
| 44 | } |
| 45 | |
| 46 | fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> { |
| 47 | self.error.help() |
| 48 | } |
| 49 | |
| 50 | fn url<'a>(&'a self) -> Option<Box<dyn Display + 'a>> { |
| 51 | self.error.url() |
| 52 | } |
| 53 | |
| 54 | fn source_code(&self) -> Option<&dyn miette::SourceCode> { |
| 55 | self.error.source_code() |
| 56 | } |
| 57 | |
| 58 | fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> { |
| 59 | self.error.labels() |
| 60 | } |
| 61 | |
| 62 | fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> { |
| 63 | self.error.related() |
| 64 | } |
| 65 | |
| 66 | fn diagnostic_source(&self) -> Option<&dyn Diagnostic> { |
| 67 | self.error.diagnostic_source() |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | pub(super) fn from_eval( |
| 72 | error: qsc_eval::Error, |
| 73 | store: &PackageStore, |
| 74 | stack_trace: Option<String>, |
| 75 | ) -> WithStack<WithSource<qsc_eval::Error>> { |
| 76 | let span = error.span(); |
| 77 | |
| 78 | let sources = &store |
| 79 | .get(span.package) |
| 80 | .expect("expected to find package id in store") |
| 81 | .sources; |
| 82 | |
| 83 | WithStack::new(WithSource::from_map(sources, error), stack_trace) |
| 84 | } |
| 85 | |