Skip to main content

rd_source/
diagnostic.rs

1use std::{fmt, ops::Range};
2
3use rd_ast::RdDocument;
4
5use crate::source_map::RdSourceMap;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct SourcePosition {
9    line: u32,
10    column: u32,
11}
12impl SourcePosition {
13    pub fn line(&self) -> u32 {
14        self.line
15    }
16    pub fn column(&self) -> u32 {
17        self.column
18    }
19}
20impl SourcePosition {
21    pub(crate) fn new(line: u32, column: u32) -> Self {
22        Self { line, column }
23    }
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct SourceSpan {
28    bytes: Range<usize>,
29    start: SourcePosition,
30    end: SourcePosition,
31}
32impl SourceSpan {
33    pub(crate) fn new(bytes: Range<usize>, start: SourcePosition, end: SourcePosition) -> Self {
34        Self { bytes, start, end }
35    }
36}
37impl SourceSpan {
38    pub fn bytes(&self) -> Range<usize> {
39        self.bytes.clone()
40    }
41    pub fn start(&self) -> &SourcePosition {
42        &self.start
43    }
44    pub fn end(&self) -> &SourcePosition {
45        &self.end
46    }
47}
48
49/// A parsed Rd document, its diagnostics, and the source map for that exact
50/// parser snapshot. Equality intentionally compares only the document and
51/// diagnostics; use the explicit source-map projection when provenance is
52/// significant.
53#[derive(Debug, Clone)]
54pub struct Parsed {
55    document: RdDocument,
56    diagnostics: Vec<Diagnostic>,
57    source_map: RdSourceMap,
58}
59impl Parsed {
60    pub(crate) fn new(
61        document: RdDocument,
62        diagnostics: Vec<Diagnostic>,
63        source_map: RdSourceMap,
64    ) -> Self {
65        Self {
66            document,
67            diagnostics,
68            source_map,
69        }
70    }
71    pub fn document(&self) -> &RdDocument {
72        &self.document
73    }
74    pub fn diagnostics(&self) -> &[Diagnostic] {
75        &self.diagnostics
76    }
77    /// Returns the exact source map for this parsed document snapshot.
78    ///
79    /// The map is tied to this parse result's original input and uses exact
80    /// canonical-path lookup. It is not a map for independently constructed
81    /// or RDS-lowered ASTs.
82    pub fn source_map(&self) -> &RdSourceMap {
83        &self.source_map
84    }
85    /// Decomposes this parse result, intentionally discarding source-map
86    /// provenance.
87    pub fn into_parts(self) -> (RdDocument, Vec<Diagnostic>) {
88        (self.document, self.diagnostics)
89    }
90    /// Decomposes this parse result while retaining its source-map provenance.
91    pub fn into_parts_with_source_map(self) -> (RdDocument, Vec<Diagnostic>, RdSourceMap) {
92        (self.document, self.diagnostics, self.source_map)
93    }
94}
95
96impl PartialEq for Parsed {
97    fn eq(&self, other: &Self) -> bool {
98        self.document == other.document && self.diagnostics == other.diagnostics
99    }
100}
101
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub struct Diagnostic {
104    severity: Severity,
105    code: DiagnosticCode,
106    message: String,
107    span: SourceSpan,
108}
109impl Diagnostic {
110    pub(crate) fn new(
111        severity: Severity,
112        code: DiagnosticCode,
113        message: impl Into<String>,
114        span: SourceSpan,
115    ) -> Self {
116        Self {
117            severity,
118            code,
119            message: message.into(),
120            span,
121        }
122    }
123    pub fn severity(&self) -> &Severity {
124        &self.severity
125    }
126    pub fn code(&self) -> &DiagnosticCode {
127        &self.code
128    }
129    pub fn message(&self) -> &str {
130        &self.message
131    }
132    pub fn span(&self) -> &SourceSpan {
133        &self.span
134    }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138#[non_exhaustive]
139pub enum Severity {
140    Warning,
141    Error,
142}
143
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145#[non_exhaustive]
146pub enum DiagnosticCode {
147    UnexpectedClosingDelimiter,
148    UnexpectedOpeningDelimiter,
149    UnclosedGroup,
150    UnclosedOption,
151    MissingArgument,
152    UnknownTag,
153    TagNotAllowedHere,
154    InvalidOptionSyntax,
155    InvalidArity,
156    UnexpectedToken,
157    UnexpectedEndIf,
158    MissingEndIf,
159    UnexpectedConditional,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163#[non_exhaustive]
164pub enum ParseError {
165    InvalidUtf8 {
166        valid_up_to: usize,
167        error_len: Option<usize>,
168    },
169    NulByte {
170        offset: usize,
171    },
172    UnsupportedEncoding {
173        name: String,
174        span: Option<SourceSpan>,
175    },
176    InputTooLarge,
177    NestingLimitExceeded {
178        span: SourceSpan,
179    },
180}
181impl fmt::Display for ParseError {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            Self::InvalidUtf8 {
185                valid_up_to,
186                error_len,
187            } => write!(f, "invalid UTF-8 at {valid_up_to} (length {error_len:?})"),
188            Self::NulByte { offset } => write!(f, "embedded NUL byte at {offset}"),
189            Self::UnsupportedEncoding { name, .. } => write!(f, "unsupported encoding: {name}"),
190            Self::InputTooLarge => f.write_str("input is too large"),
191            Self::NestingLimitExceeded { .. } => f.write_str("nesting limit exceeded"),
192        }
193    }
194}
195impl std::error::Error for ParseError {}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    #[test]
201    fn hard_input_errors_report_utf8_and_nul() {
202        assert_eq!(
203            crate::parse(b"a\0b"),
204            Err(ParseError::NulByte { offset: 1 })
205        );
206        assert_eq!(
207            crate::parse(&[b'a', 0xe2, 0x82]),
208            Err(ParseError::InvalidUtf8 {
209                valid_up_to: 1,
210                error_len: None
211            })
212        );
213        assert_eq!(
214            crate::parse(&[0xff]),
215            Err(ParseError::InvalidUtf8 {
216                valid_up_to: 0,
217                error_len: Some(1)
218            })
219        );
220    }
221    #[test]
222    fn empty_and_whitespace_documents_are_preserved() {
223        assert!(crate::parse(b"").unwrap().document().nodes().is_empty());
224        let document = crate::parse(b" \t\n").unwrap().into_parts().0;
225        assert_eq!(document.nodes(), &[rd_ast::RdNode::Text(" \t\n".into())]);
226    }
227}