js2zig_core/zigir/
source_span.rs1#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
6pub struct SourceSpan {
7 pub js_line: usize,
9 pub js_col: usize,
11 pub js_file: String,
13}
14
15impl SourceSpan {
16 pub fn new(line: usize, col: usize) -> Self {
17 Self {
18 js_line: line,
19 js_col: col,
20 js_file: String::new(),
21 }
22 }
23
24 pub fn with_file(line: usize, col: usize, file: String) -> Self {
25 Self {
26 js_line: line,
27 js_col: col,
28 js_file: file,
29 }
30 }
31
32 pub fn to_loc_string(&self) -> String {
34 format!("{}:{}", self.js_line, self.js_col)
35 }
36}
37
38impl std::fmt::Display for SourceSpan {
39 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40 if self.js_file.is_empty() {
41 write!(f, "{}:{}", self.js_line, self.js_col)
42 } else {
43 write!(f, "{}:{}:{}", self.js_file, self.js_line, self.js_col)
44 }
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50pub enum DiagnosticLevel {
51 Warning,
52 Error,
53}
54
55#[derive(Debug, Clone)]
57pub struct IrDiagnostic {
58 pub level: DiagnosticLevel,
59 pub span: Option<SourceSpan>,
60 pub message: String,
61}
62
63impl IrDiagnostic {
64 pub fn warning(message: String) -> Self {
65 Self {
66 level: DiagnosticLevel::Warning,
67 span: None,
68 message,
69 }
70 }
71
72 pub fn error(message: String) -> Self {
73 Self {
74 level: DiagnosticLevel::Error,
75 span: None,
76 message,
77 }
78 }
79
80 pub fn with_span(mut self, span: SourceSpan) -> Self {
81 self.span = Some(span);
82 self
83 }
84}
85
86impl std::fmt::Display for IrDiagnostic {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 let level = match self.level {
89 DiagnosticLevel::Warning => "warning",
90 DiagnosticLevel::Error => "error",
91 };
92 match &self.span {
93 Some(span) => write!(f, "[{}] {}: {}", level, span, self.message),
94 None => write!(f, "[{}] {}", level, self.message),
95 }
96 }
97}
98
99#[cfg(test)]
100mod tests {
101 use super::*;
102
103 #[test]
104 fn test_source_span_display() {
105 let span = SourceSpan::new(10, 5);
106 assert_eq!(format!("{}", span), "10:5");
107 }
108
109 #[test]
110 fn test_source_span_with_file() {
111 let span = SourceSpan::with_file(10, 5, "main.js".to_string());
112 assert_eq!(format!("{}", span), "main.js:10:5");
113 }
114
115 #[test]
116 fn test_diagnostic_warning() {
117 let d = IrDiagnostic::warning("unused variable".to_string());
118 assert_eq!(format!("{}", d), "[warning] unused variable");
119 }
120
121 #[test]
122 fn test_diagnostic_error_with_span() {
123 let d = IrDiagnostic::error("type mismatch".to_string()).with_span(SourceSpan::new(3, 7));
124 assert_eq!(format!("{}", d), "[error] 3:7: type mismatch");
125 }
126}