source_lang/error.rs
1//! The error type returned when a source cannot be added to a map.
2
3use alloc::boxed::Box;
4use core::fmt;
5
6/// The reason a source could not be added to a [`SourceMap`](crate::SourceMap).
7///
8/// Adding a source can fail four ways, each a distinct, defined outcome rather
9/// than a panic or a silent corruption of the coordinate bookkeeping:
10///
11/// - the source is larger than the map's per-source ceiling
12/// ([`Oversize`](Self::Oversize)),
13/// - it does not fit in what remains of the shared 32-bit position space
14/// ([`SpaceExhausted`](Self::SpaceExhausted)),
15/// - its bytes are not valid UTF-8 ([`NotUtf8`](Self::NotUtf8)), or
16/// - the file behind a path could not be read ([`Io`](Self::Io), `std` only).
17///
18/// Every variant names the source it concerns so the failure is actionable when
19/// it is logged far from the call that produced it.
20///
21/// The enum is `#[non_exhaustive]`: a downstream `match` must include a wildcard
22/// arm, so later additions never force a breaking change on callers.
23///
24/// # Examples
25///
26/// ```
27/// use source_lang::{SourceMap, SourceMapError};
28///
29/// let mut map = SourceMap::new();
30/// // Raw bytes that are not valid UTF-8 are rejected, naming the source.
31/// let err = map.add_bytes("blob.bin", &[0xff, 0xfe]).unwrap_err();
32/// assert!(matches!(err, SourceMapError::NotUtf8 { .. }));
33/// ```
34#[derive(Clone, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub enum SourceMapError {
37 /// The source is larger than the map's configured per-source ceiling.
38 ///
39 /// The ceiling defaults to `u32::MAX` — the addressing limit of the global
40 /// position space — and can be lowered with
41 /// [`SourceMap::set_max_source_len`](crate::SourceMap::set_max_source_len) to
42 /// bound how much a single untrusted input may load. For a file, the size is
43 /// checked against the path's metadata *before* the bytes are read, so an
44 /// oversize file is never pulled into memory.
45 Oversize {
46 /// Display name of the source that was rejected.
47 name: Box<str>,
48 /// Byte length of the source.
49 len: u64,
50 },
51
52 /// The source did not fit in what remained of the map's global space.
53 ///
54 /// Returned when the source is no larger than the per-source ceiling but
55 /// still exceeds the bytes left in the shared 32-bit position space — because
56 /// earlier sources have consumed the remainder — or when the map already
57 /// holds the maximum number of sources. The map is left unchanged, so the
58 /// caller may start a fresh map or split the input.
59 SpaceExhausted {
60 /// Byte length of the source that was rejected.
61 needed: u64,
62 /// Bytes of global position space that remained available.
63 available: u64,
64 },
65
66 /// The source's bytes are not valid UTF-8.
67 ///
68 /// A `SourceMap` stores text, so input from
69 /// [`add_bytes`](crate::SourceMap::add_bytes) or a file is validated before
70 /// it is stored. A truncated multi-byte sequence or stray binary byte is
71 /// reported here rather than stored as corrupt text.
72 NotUtf8 {
73 /// Display name of the source whose bytes failed validation.
74 name: Box<str>,
75 },
76
77 /// A file's contents could not be read from disk.
78 ///
79 /// Returned by [`add_file`](crate::SourceMap::add_file) when opening or
80 /// reading the path fails — a missing file, a directory, or a permission
81 /// error. The [`std::io::ErrorKind`] distinguishes the cause without carrying
82 /// a non-comparable [`std::io::Error`], so this variant stays `Clone` and
83 /// `Eq` like the rest.
84 #[cfg(feature = "std")]
85 #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
86 Io {
87 /// Display name of the source (the path that was requested).
88 name: Box<str>,
89 /// The category of I/O failure.
90 kind: std::io::ErrorKind,
91 },
92}
93
94impl fmt::Display for SourceMapError {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 match self {
97 Self::Oversize { name, len } => write!(
98 f,
99 "source `{name}` of {len} bytes exceeds the maximum source length",
100 ),
101 Self::SpaceExhausted { needed, available } => write!(
102 f,
103 "source of {needed} bytes does not fit in the {available} bytes \
104 remaining in the global position space",
105 ),
106 Self::NotUtf8 { name } => {
107 write!(f, "source `{name}` is not valid UTF-8")
108 }
109 #[cfg(feature = "std")]
110 Self::Io { name, kind } => write!(f, "source `{name}` could not be read: {kind}"),
111 }
112 }
113}
114
115impl core::error::Error for SourceMapError {}
116
117#[cfg(test)]
118mod tests {
119 extern crate alloc;
120 use alloc::boxed::Box;
121 use alloc::string::ToString;
122
123 use super::*;
124
125 #[test]
126 fn test_space_exhausted_display_names_both_figures() {
127 let err = SourceMapError::SpaceExhausted {
128 needed: 10,
129 available: 4,
130 };
131 let text = err.to_string();
132 assert!(text.contains("10 bytes"), "{text}");
133 assert!(text.contains("4 bytes"), "{text}");
134 }
135
136 #[test]
137 fn test_oversize_display_names_source_and_length() {
138 let err = SourceMapError::Oversize {
139 name: Box::from("big.rs"),
140 len: 5_000_000_000,
141 };
142 let text = err.to_string();
143 assert!(text.contains("big.rs"), "{text}");
144 assert!(text.contains("5000000000"), "{text}");
145 }
146
147 #[test]
148 fn test_not_utf8_display_names_source() {
149 let err = SourceMapError::NotUtf8 {
150 name: Box::from("blob.bin"),
151 };
152 assert!(err.to_string().contains("blob.bin"));
153 }
154
155 #[cfg(feature = "std")]
156 #[test]
157 fn test_io_display_names_source_and_kind() {
158 let err = SourceMapError::Io {
159 name: Box::from("missing.rs"),
160 kind: std::io::ErrorKind::NotFound,
161 };
162 let text = err.to_string();
163 assert!(text.contains("missing.rs"), "{text}");
164 }
165
166 #[test]
167 fn test_error_is_clonable_and_equatable() {
168 let a = SourceMapError::SpaceExhausted {
169 needed: 1,
170 available: 0,
171 };
172 let b = a.clone();
173 assert_eq!(a, b);
174 }
175}