use crate::source::DecodedInput;
use crate::Loc;
use crate::{DiagnosticMessage, ErrorLevel};
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct Diagnostic {
pub level: ErrorLevel,
pub message: DiagnosticMessage,
pub loc: Loc,
}
impl Diagnostic {
pub fn new(level: ErrorLevel, message: DiagnosticMessage, loc: Loc) -> Self {
Self {
level,
message,
loc,
}
}
pub fn render_message(&self) -> String {
self.message.render()
}
pub fn render(&self, input: &DecodedInput) -> Option<String> {
let (line_no, line_loc) = self.loc.expand_to_line(input)?;
let line = line_loc.source(input)?;
let filename = &input.name;
let (_, start_col) = self.loc.begin_line_col(input)?;
let prefix = format!("{}:{}", filename.as_str(), line_no + 1);
let highlight = format!(
"{indent}^{tildes}",
indent = " ".repeat(start_col),
tildes = if self.loc.size() > 0 {
"~".repeat(self.loc.size() - 1)
} else {
"".to_string()
}
);
Some(
format!(
"{prefix}:{start_col}: {level:?}: {message}\n{prefix}: {line}\n{prefix}: {highlight}",
prefix = prefix,
start_col = start_col,
level = self.level,
message = self.message.render(),
line = line,
highlight = highlight
)
.trim()
.to_string(),
)
}
pub fn is_warning(&self) -> bool {
matches!(self.level, ErrorLevel::Warning)
}
pub fn is_error(&self) -> bool {
matches!(self.level, ErrorLevel::Error)
}
}
#[cfg(feature = "compile-with-external-structures")]
use crate::containers::ExternalList;
#[cfg(feature = "compile-with-external-structures")]
type List<T> = ExternalList<T>;
#[cfg(not(feature = "compile-with-external-structures"))]
type List<T> = Vec<T>;
use std::cell::RefCell;
use std::rc::Rc;
#[derive(Debug, Default, Clone)]
pub(crate) struct Diagnostics {
list: Rc<RefCell<List<Diagnostic>>>,
}
impl Diagnostics {
pub(crate) fn new() -> Self {
Self {
list: Rc::new(RefCell::new(List::<Diagnostic>::new())),
}
}
pub(crate) fn emit(&self, diagnostic: Diagnostic) {
self.list.borrow_mut().push(diagnostic)
}
pub(crate) fn take_inner(self) -> List<Diagnostic> {
self.list.replace(List::<Diagnostic>::new())
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "link-with-external-c-structures")]
#[test]
fn test_size_c() {
use super::Diagnostic;
assert_eq!(std::mem::size_of::<Diagnostic>(), 56);
}
#[cfg(feature = "link-with-external-cpp-structures")]
#[test]
fn test_size_cpp() {
use super::Diagnostic;
assert_eq!(std::mem::size_of::<Diagnostic>(), 40);
}
}