Skip to main content

runic_diagnostics/
source.rs

1mod line_column;
2mod source_id;
3mod span;
4
5use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
6use core::fmt;
7
8pub use self::{
9    line_column::*,
10    source_id::{SourceId, SourceKey, SourceNamespace, SourceRevision},
11    span::{SourceSpan, Span, Spanned, TextRange, TextRangeError},
12};
13
14/// A borrowed source resolved from a provider.
15#[derive(Clone, Copy, Debug)]
16pub struct Source<'a> {
17    pub id: SourceId,
18    pub display_name: &'a str,
19    pub byte_len: u32,
20    pub text: Option<&'a str>,
21    pub revision: Option<SourceRevision>,
22}
23
24/// A resolved source that retains its complete provenance key.
25#[derive(Clone, Copy, Debug)]
26pub struct ResolvedSource<'a> {
27    pub key: SourceKey,
28    pub source: Source<'a>,
29}
30
31/// Resolves one source universe by namespaced source ID.
32pub trait SourceProvider {
33    fn get(&self, id: SourceId) -> Option<Source<'_>>;
34
35    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn>;
36
37    /// Returns the most recently registered source with the given display name, if supported.
38    ///
39    /// Display names are not required to be unique. Providers which do not maintain a reverse
40    /// index may leave this operation unsupported.
41    fn find_by_name(&self, _display_name: &str) -> Option<SourceId> {
42        None
43    }
44
45    /// Returns the byte offset of `position`, if the provider supports reverse lookup.
46    fn offset_of(&self, _id: SourceId, _position: LineColumn) -> Option<u32> {
47        None
48    }
49}
50
51/// A cloneable, type-erased source provider suitable for retaining with owned diagnostics.
52#[derive(Clone)]
53pub struct SharedSourceProvider {
54    inner: Arc<dyn SourceProvider + Send + Sync + 'static>,
55}
56
57impl SharedSourceProvider {
58    pub fn new<P>(provider: Arc<P>) -> Self
59    where
60        P: SourceProvider + Send + Sync + 'static,
61    {
62        Self { inner: provider }
63    }
64
65    pub fn from_arc(provider: Arc<dyn SourceProvider + Send + Sync + 'static>) -> Self {
66        Self { inner: provider }
67    }
68
69    pub fn as_provider(&self) -> &(dyn SourceProvider + Send + Sync + 'static) {
70        self.inner.as_ref()
71    }
72}
73
74impl<P> From<Arc<P>> for SharedSourceProvider
75where
76    P: SourceProvider + Send + Sync + 'static,
77{
78    fn from(provider: Arc<P>) -> Self {
79        Self::new(provider)
80    }
81}
82
83impl From<Arc<dyn SourceProvider + Send + Sync + 'static>> for SharedSourceProvider {
84    fn from(provider: Arc<dyn SourceProvider + Send + Sync + 'static>) -> Self {
85        Self::from_arc(provider)
86    }
87}
88
89impl fmt::Debug for SharedSourceProvider {
90    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
91        formatter.write_str("SharedSourceProvider(..)")
92    }
93}
94
95impl SourceProvider for SharedSourceProvider {
96    fn get(&self, id: SourceId) -> Option<Source<'_>> {
97        self.inner.get(id)
98    }
99
100    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
101        self.inner.line_column(id, offset)
102    }
103
104    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
105        self.inner.find_by_name(display_name)
106    }
107
108    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
109        self.inner.offset_of(id, position)
110    }
111}
112
113impl<P> SourceProvider for &P
114where
115    P: SourceProvider + ?Sized,
116{
117    fn get(&self, id: SourceId) -> Option<Source<'_>> {
118        (**self).get(id)
119    }
120
121    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
122        (**self).line_column(id, offset)
123    }
124
125    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
126        (**self).find_by_name(display_name)
127    }
128
129    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
130        (**self).offset_of(id, position)
131    }
132}
133
134impl<P> SourceProvider for &mut P
135where
136    P: SourceProvider + ?Sized,
137{
138    fn get(&self, id: SourceId) -> Option<Source<'_>> {
139        (**self).get(id)
140    }
141
142    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
143        (**self).line_column(id, offset)
144    }
145
146    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
147        (**self).find_by_name(display_name)
148    }
149
150    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
151        (**self).offset_of(id, position)
152    }
153}
154
155impl<P> SourceProvider for Box<P>
156where
157    P: SourceProvider + ?Sized,
158{
159    fn get(&self, id: SourceId) -> Option<Source<'_>> {
160        (**self).get(id)
161    }
162
163    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
164        (**self).line_column(id, offset)
165    }
166
167    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
168        (**self).find_by_name(display_name)
169    }
170
171    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
172        (**self).offset_of(id, position)
173    }
174}
175
176impl<P> SourceProvider for Arc<P>
177where
178    P: SourceProvider + ?Sized,
179{
180    fn get(&self, id: SourceId) -> Option<Source<'_>> {
181        (**self).get(id)
182    }
183
184    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
185        (**self).line_column(id, offset)
186    }
187
188    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
189        (**self).find_by_name(display_name)
190    }
191
192    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
193        (**self).offset_of(id, position)
194    }
195}
196
197#[derive(Clone, Copy, Debug, Default)]
198pub(crate) struct EmptySourceProvider;
199
200pub(crate) static EMPTY_SOURCE_PROVIDER: EmptySourceProvider = EmptySourceProvider;
201
202impl SourceProvider for EmptySourceProvider {
203    fn get(&self, _id: SourceId) -> Option<Source<'_>> {
204        None
205    }
206
207    fn line_column(&self, _id: SourceId, _offset: u32) -> Option<LineColumn> {
208        None
209    }
210}
211
212/// Resolves session and diagnostic-attached source universes without fallback.
213#[derive(Clone, Copy)]
214pub struct LayeredSourceProvider<'a> {
215    session: &'a dyn SourceProvider,
216    attached: Option<&'a dyn SourceProvider>,
217}
218
219impl<'a> LayeredSourceProvider<'a> {
220    pub fn new(session: &'a dyn SourceProvider, attached: Option<&'a dyn SourceProvider>) -> Self {
221        Self { session, attached }
222    }
223
224    pub fn session_only(session: &'a dyn SourceProvider) -> Self {
225        Self::new(session, None)
226    }
227
228    pub fn resolve(&self, key: SourceKey) -> Option<ResolvedSource<'a>> {
229        self.resolve_checked(key).ok()
230    }
231
232    pub(crate) fn resolve_checked(
233        &self,
234        key: SourceKey,
235    ) -> Result<ResolvedSource<'a>, SourceResolveError> {
236        let (provider, id) = self.provider(key).ok_or(SourceResolveError::Missing)?;
237        let source = provider.get(id).ok_or(SourceResolveError::Missing)?;
238        if source.id != id {
239            return Err(SourceResolveError::IdMismatch {
240                returned: source.id,
241            });
242        }
243        if let Some(text) = source.text {
244            let text_len =
245                u32::try_from(text.len()).map_err(|_| SourceResolveError::ByteLengthMismatch {
246                    declared: source.byte_len,
247                    actual: text.len(),
248                })?;
249            if source.byte_len != text_len {
250                return Err(SourceResolveError::ByteLengthMismatch {
251                    declared: source.byte_len,
252                    actual: text.len(),
253                });
254            }
255        }
256        Ok(ResolvedSource { key, source })
257    }
258
259    pub fn line_column(&self, key: SourceKey, offset: u32) -> Option<LineColumn> {
260        let (provider, id) = self.provider(key)?;
261        let resolved = self.resolve(key)?;
262        if offset > resolved.source.byte_len {
263            return None;
264        }
265        let location = provider.line_column(id, offset)?;
266        if let Some(text) = resolved.source.text
267            && line_column_from_text(text, offset) != Some(location)
268        {
269            return None;
270        }
271        Some(location)
272    }
273
274    fn provider(&self, key: SourceKey) -> Option<(&'a dyn SourceProvider, SourceId)> {
275        match key {
276            SourceKey::Session(id) => Some((self.session, id)),
277            SourceKey::Attached(id) => self.attached.map(|provider| (provider, id)),
278        }
279    }
280}
281
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
283pub(crate) enum SourceResolveError {
284    Missing,
285    IdMismatch { returned: SourceId },
286    ByteLengthMismatch { declared: u32, actual: usize },
287}
288
289#[derive(Debug)]
290struct SourceRecord {
291    id: SourceId,
292    display_name: String,
293    text: String,
294    revision: Option<SourceRevision>,
295    line_starts: Box<[u32]>,
296}
297
298/// Built-in owned source provider for `no_std + alloc` applications.
299#[derive(Clone, Debug)]
300pub struct SourceMap {
301    namespace: SourceNamespace,
302    next_local: Option<u32>,
303    sources: Vec<Arc<SourceRecord>>,
304}
305
306impl SourceMap {
307    pub const fn new(namespace: SourceNamespace) -> Self {
308        assert!(!namespace.is_unknown(), "source maps require a known namespace");
309        Self {
310            namespace,
311            next_local: Some(0),
312            sources: Vec::new(),
313        }
314    }
315
316    pub const fn namespace(&self) -> SourceNamespace {
317        self.namespace
318    }
319
320    pub fn len(&self) -> usize {
321        self.sources.len()
322    }
323
324    pub fn is_empty(&self) -> bool {
325        self.sources.is_empty()
326    }
327
328    /// Returns the most recently inserted source with the given display name.
329    pub fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
330        self.sources
331            .iter()
332            .rev()
333            .find(|source| source.display_name == display_name)
334            .map(|source| source.id)
335    }
336
337    pub fn validate_source_len(bytes: usize) -> Result<u32, SourceMapError> {
338        u32::try_from(bytes).map_err(|_| SourceMapError::SourceTooLarge { bytes })
339    }
340
341    pub fn insert(
342        &mut self,
343        display_name: impl Into<String>,
344        text: impl Into<String>,
345        revision: Option<SourceRevision>,
346    ) -> Result<SourceId, SourceMapError> {
347        let text = text.into();
348        let byte_len = Self::validate_source_len(text.len())?;
349        let local = self.next_local.ok_or(SourceMapError::SourceIdExhausted)?;
350        let id = SourceId::new(self.namespace, local);
351        let line_starts = line_starts(&text, byte_len);
352        let next_local = local.checked_add(1);
353
354        self.sources.push(Arc::new(SourceRecord {
355            id,
356            display_name: display_name.into(),
357            text,
358            revision,
359            line_starts,
360        }));
361        self.next_local = next_local;
362        Ok(id)
363    }
364
365    /// Returns the byte offset of `position` in source `id`, the inverse of `line_column`.
366    ///
367    /// A column one past the last character of a line addresses the line end.
368    pub fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
369        let record = self.record(id)?;
370        let line_start = *record.line_starts.get(position.line_index().to_usize())?;
371        let line_start = usize::try_from(line_start).ok()?;
372        let rest = record.text.get(line_start..)?;
373        let line = rest.split_once('\n').map_or(rest, |(line, _)| line);
374        let column = position.column_index().to_usize();
375        let in_line = match line.char_indices().nth(column) {
376            Some((index, _)) => index,
377            None if line.chars().count() == column => line.len(),
378            None => return None,
379        };
380        u32::try_from(line_start + in_line).ok()
381    }
382
383    /// Reads `path` and registers it under its path as display name.
384    ///
385    /// A path that is already registered returns the existing id without re-reading the file.
386    #[cfg(feature = "std")]
387    pub fn load_file(&mut self, path: impl AsRef<std::path::Path>) -> std::io::Result<SourceId> {
388        let path = path.as_ref();
389        let display_name = path.to_string_lossy().into_owned();
390        if let Some(id) = self.find_by_name(&display_name) {
391            return Ok(id);
392        }
393        let text = std::fs::read_to_string(path)?;
394        self.insert(display_name, text, None).map_err(std::io::Error::other)
395    }
396
397    fn record(&self, id: SourceId) -> Option<&SourceRecord> {
398        if id.namespace() != self.namespace {
399            return None;
400        }
401        let index = usize::try_from(id.local()).ok()?;
402        let record = self.sources.get(index)?.as_ref();
403        (record.id == id).then_some(record)
404    }
405
406    #[cfg(test)]
407    pub(crate) fn set_next_local_for_test(&mut self, next: Option<u32>) {
408        self.next_local = next;
409    }
410}
411
412impl SourceProvider for SourceMap {
413    fn get(&self, id: SourceId) -> Option<Source<'_>> {
414        let record = self.record(id)?;
415        Some(Source {
416            id: record.id,
417            display_name: &record.display_name,
418            byte_len: u32::try_from(record.text.len()).ok()?,
419            text: Some(&record.text),
420            revision: record.revision,
421        })
422    }
423
424    fn line_column(&self, id: SourceId, offset: u32) -> Option<LineColumn> {
425        let record = self.record(id)?;
426        let offset = usize::try_from(offset).ok()?;
427        if offset > record.text.len() || !record.text.is_char_boundary(offset) {
428            return None;
429        }
430        let offset_u32 = u32::try_from(offset).ok()?;
431        let line_index = record
432            .line_starts
433            .partition_point(|line_start| *line_start <= offset_u32)
434            .checked_sub(1)?;
435        let line_start = usize::try_from(record.line_starts[line_index]).ok()?;
436        let line = u32::try_from(line_index).ok()?.checked_add(1)?;
437        let column = u32::try_from(record.text[line_start..offset].chars().count())
438            .ok()?
439            .checked_add(1)?;
440        LineColumn::new(line, column)
441    }
442
443    fn find_by_name(&self, display_name: &str) -> Option<SourceId> {
444        SourceMap::find_by_name(self, display_name)
445    }
446
447    fn offset_of(&self, id: SourceId, position: LineColumn) -> Option<u32> {
448        SourceMap::offset_of(self, id, position)
449    }
450}
451
452#[derive(Clone, Debug, Eq, PartialEq)]
453pub enum SourceMapError {
454    SourceTooLarge { bytes: usize },
455    SourceIdExhausted,
456}
457
458impl fmt::Display for SourceMapError {
459    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
460        match self {
461            Self::SourceTooLarge { bytes } => {
462                write!(formatter, "source length {bytes} exceeds u32::MAX")
463            }
464            Self::SourceIdExhausted => formatter.write_str("source ID space is exhausted"),
465        }
466    }
467}
468
469impl core::error::Error for SourceMapError {}
470
471fn line_starts(text: &str, byte_len: u32) -> Box<[u32]> {
472    let mut starts = Vec::new();
473    starts.push(0);
474    for (index, byte) in text.bytes().enumerate() {
475        if byte == b'\n' {
476            let next = index + 1;
477            if next <= usize::try_from(byte_len).unwrap_or(usize::MAX) {
478                starts.push(u32::try_from(next).expect("validated source length fits in u32"));
479            }
480        }
481    }
482    starts.into_boxed_slice()
483}
484
485fn line_column_from_text(text: &str, offset: u32) -> Option<LineColumn> {
486    let offset = usize::try_from(offset).ok()?;
487    if offset > text.len() || !text.is_char_boundary(offset) {
488        return None;
489    }
490    let prefix = &text[..offset];
491    let line = u32::try_from(prefix.bytes().filter(|byte| *byte == b'\n').count())
492        .ok()?
493        .checked_add(1)?;
494    let line_start = prefix.rfind('\n').map_or(0, |index| index + 1);
495    let column = u32::try_from(text[line_start..offset].chars().count()).ok()?.checked_add(1)?;
496    LineColumn::new(line, column)
497}
498
499#[cfg(test)]
500mod tests {
501    use alloc::{format, string::ToString};
502
503    use super::*;
504
505    #[test]
506    fn offset_of_inverts_line_column() {
507        let namespace = SourceNamespace::new(core::num::NonZeroU32::new(7).unwrap());
508        let mut map = SourceMap::new(namespace);
509        let id = map.insert("a.runic", "ab\ncd\u{e9}\n", None).unwrap();
510        // Every char boundary, including each line end and the end of input.
511        for offset in [0u32, 1, 2, 3, 4, 5, 7, 8] {
512            let position = map.line_column(id, offset).unwrap();
513            assert_eq!(map.offset_of(id, position), Some(offset), "offset {offset}");
514        }
515        assert_eq!(map.offset_of(id, LineColumn::new(9, 1).unwrap()), None);
516        assert_eq!(map.offset_of(id, LineColumn::new(1, 9).unwrap()), None);
517    }
518
519    #[test]
520    fn offset_of_is_forwarded_by_provider_wrappers() {
521        let namespace = SourceNamespace::new(core::num::NonZeroU32::new(9).unwrap());
522        let mut map = SourceMap::new(namespace);
523        let id = map.insert("a.runic", "ab\ncd\n", None).unwrap();
524        let position = LineColumn::new(2, 1).unwrap();
525        let expected = Some(3);
526        assert_eq!(map.offset_of(id, position), expected);
527
528        let dynamic: &dyn SourceProvider = &map;
529        assert_eq!(dynamic.offset_of(id, position), expected, "&dyn SourceProvider");
530        assert_eq!(SourceProvider::offset_of(&&map, id, position), expected, "&P");
531        assert_eq!(SourceProvider::offset_of(&&mut map, id, position), expected, "&mut P");
532
533        let arc = Arc::new(map);
534        assert_eq!(SourceProvider::offset_of(&arc, id, position), expected, "Arc<P>");
535        let dynamic: &dyn SourceProvider = &arc;
536        assert_eq!(dynamic.offset_of(id, position), expected, "&dyn over Arc<P>");
537        let shared = SharedSourceProvider::new(arc.clone());
538        assert_eq!(shared.offset_of(id, position), expected, "SharedSourceProvider");
539        let boxed: Box<dyn SourceProvider> = Box::new(arc);
540        assert_eq!(SourceProvider::offset_of(&boxed, id, position), expected, "Box<P>");
541    }
542
543    #[cfg(feature = "std")]
544    #[test]
545    fn load_file_registers_once_per_path() {
546        let dir = std::env::temp_dir().join(format!("runic-diag-{}", std::process::id()));
547        std::fs::create_dir_all(&dir).unwrap();
548        let path = dir.join("m.runic");
549        std::fs::write(&path, "hello\n").unwrap();
550        let namespace = SourceNamespace::new(core::num::NonZeroU32::new(8).unwrap());
551        let mut map = SourceMap::new(namespace);
552        let first = map.load_file(&path).unwrap();
553        let second = map.load_file(&path).unwrap();
554        assert_eq!(first, second);
555        assert_eq!(map.get(first).unwrap().text, Some("hello\n"));
556        assert!(map.load_file(dir.join("missing.runic")).is_err());
557        std::fs::remove_dir_all(&dir).unwrap();
558    }
559
560    #[test]
561    fn ranges_and_spans_preserve_checked_provenance() {
562        assert!(core::mem::size_of::<SourceSpan>() < 32);
563        assert_eq!(TextRange::new(4, 3), Err(TextRangeError::Reversed { start: 4, end: 3 }));
564        let empty = TextRange::new(u32::MAX, u32::MAX).unwrap();
565        assert!(empty.is_empty());
566
567        if usize::BITS > u32::BITS {
568            let too_large = usize::try_from(u32::MAX).unwrap() + 1;
569            assert_eq!(
570                TextRange::try_from_usize(too_large, too_large),
571                Err(TextRangeError::OffsetTooLarge { offset: too_large })
572            );
573        }
574
575        let id = SourceId::new(SourceNamespace::new_unchecked(7), 9);
576        let session = SourceSpan::session(id, empty).with_revision(SourceRevision(11));
577        let attached = SourceSpan::attached(id, empty);
578        assert_eq!(session.source(), SourceKey::Session(id));
579        assert_eq!(session.revision(), Some(SourceRevision(11)));
580        assert_eq!(session.range(), empty);
581        assert_eq!(attached.source(), SourceKey::Attached(id));
582        assert_ne!(session.source(), attached.source());
583    }
584
585    #[test]
586    fn source_map_ids_are_namespaced_monotonic_and_failed_insertions_do_not_mutate() {
587        let mut first = SourceMap::new(SourceNamespace::new_unchecked(1));
588        let mut second = SourceMap::new(SourceNamespace::new_unchecked(2));
589        let first_id = first.insert("a", "text", None).unwrap();
590        let next_id = first.insert("b", "", Some(SourceRevision(2))).unwrap();
591        let second_id = second.insert("a", "text", None).unwrap();
592        assert_eq!(first_id.local(), 0);
593        assert_eq!(next_id.local(), 1);
594        assert_ne!(first_id, second_id);
595        assert_eq!(first.len(), 2);
596
597        first.set_next_local_for_test(None);
598        assert_eq!(first.insert("never", "inserted", None), Err(SourceMapError::SourceIdExhausted));
599        assert_eq!(first.len(), 2);
600
601        if usize::BITS > u32::BITS {
602            let too_large = usize::try_from(u32::MAX).unwrap() + 1;
603            assert_eq!(
604                SourceMap::validate_source_len(too_large),
605                Err(SourceMapError::SourceTooLarge { bytes: too_large })
606            );
607        }
608    }
609
610    #[test]
611    fn source_map_clone_is_an_immutable_snapshot() {
612        let namespace = SourceNamespace::new_unchecked(7);
613        let mut sources = SourceMap::new(namespace);
614        let first = sources.insert("module.runic", "begin\nend", None).unwrap();
615        let snapshot = sources.clone();
616
617        let latest = sources.insert("module.runic", "begin\nnop\nend", None).unwrap();
618
619        assert_eq!(snapshot.len(), 1);
620        assert_eq!(snapshot.find_by_name("module.runic"), Some(first));
621        assert_eq!(sources.find_by_name("module.runic"), Some(latest));
622        assert!(snapshot.get(latest).is_none());
623        assert_eq!(snapshot.get(first).unwrap().text, Some("begin\nend"));
624    }
625
626    #[test]
627    #[should_panic(expected = "source maps require a known namespace")]
628    fn source_map_rejects_the_reserved_unknown_namespace() {
629        let _ = SourceMap::new(SourceNamespace::UNKNOWN);
630    }
631
632    #[test]
633    fn shared_source_provider_delegates_and_hides_implementation_details() {
634        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(8));
635        let id = sources.insert("module.runic", "begin\nend", None).unwrap();
636        let shared = SharedSourceProvider::from(Arc::new(sources));
637
638        assert_eq!(shared.get(id).unwrap().display_name, "module.runic");
639        assert_eq!(shared.line_column(id, 6), LineColumn::new(2, 1));
640        assert_eq!(shared.find_by_name("module.runic"), Some(id));
641        assert_eq!(format!("{shared:?}"), "SharedSourceProvider(..)");
642
643        let erased: Arc<dyn SourceProvider + Send + Sync> = Arc::new(shared);
644        let erased = SharedSourceProvider::from(erased);
645        assert_eq!(erased.find_by_name("module.runic"), Some(id));
646    }
647
648    #[test]
649    fn line_columns_are_one_based_scalar_coordinates_with_lf_line_breaks() {
650        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(1));
651        let id = sources.insert("unicode", "a😀e\u{301}\r\nz\n", None).unwrap();
652        let cases = [
653            (0, (1, 1)),
654            (1, (1, 2)),
655            (5, (1, 3)),
656            (6, (1, 4)),
657            (8, (1, 5)),
658            (9, (1, 6)),
659            (10, (2, 1)),
660            (11, (2, 2)),
661            (12, (3, 1)),
662        ];
663        for (offset, (line, column)) in cases {
664            let line = LineNumber::new(line).unwrap();
665            let column = ColumnNumber::new(column).unwrap();
666            let location = sources.line_column(id, offset).unwrap();
667            assert_eq!((location.line(), location.column()), (line, column));
668        }
669        assert_eq!(sources.line_column(id, 2), None);
670        assert_eq!(sources.line_column(id, 13), None);
671        assert_eq!(LineColumn::new(0, 1), None);
672        assert_eq!(LineColumn::new(1, 0), None);
673    }
674
675    #[test]
676    fn layered_resolution_never_collapses_provenance_or_accepts_bad_providers() {
677        let namespace = SourceNamespace::new_unchecked(5);
678        let mut session = SourceMap::new(namespace);
679        let mut attached = SourceMap::new(namespace);
680        let session_id = session.insert("same", "session", None).unwrap();
681        let attached_id = attached.insert("same", "attached", None).unwrap();
682        assert_eq!(session_id, attached_id);
683
684        let layered = LayeredSourceProvider::new(&session, Some(&attached));
685        assert_eq!(
686            layered.resolve(SourceKey::Session(session_id)).unwrap().source.text,
687            Some("session")
688        );
689        assert_eq!(
690            layered.resolve(SourceKey::Attached(attached_id)).unwrap().source.text,
691            Some("attached")
692        );
693        assert!(
694            LayeredSourceProvider::session_only(&session)
695                .resolve(SourceKey::Attached(attached_id))
696                .is_none()
697        );
698
699        struct BadProvider {
700            requested: SourceId,
701            returned: SourceId,
702            bad_len: bool,
703            bad_location: bool,
704        }
705
706        impl SourceProvider for BadProvider {
707            fn get(&self, id: SourceId) -> Option<Source<'_>> {
708                (id == self.requested).then_some(Source {
709                    id: self.returned,
710                    display_name: "bad",
711                    byte_len: if self.bad_len { 99 } else { 1 },
712                    text: Some("x"),
713                    revision: None,
714                })
715            }
716
717            fn line_column(&self, _id: SourceId, _offset: u32) -> Option<LineColumn> {
718                LineColumn::new(1, u32::from(self.bad_location) + 1)
719            }
720        }
721
722        let other = SourceId::new(namespace, 99);
723        let wrong_id = BadProvider {
724            requested: session_id,
725            returned: other,
726            bad_len: false,
727            bad_location: false,
728        };
729        assert!(
730            LayeredSourceProvider::session_only(&wrong_id)
731                .resolve(SourceKey::Session(session_id))
732                .is_none()
733        );
734        let wrong_len = BadProvider {
735            requested: session_id,
736            returned: session_id,
737            bad_len: true,
738            bad_location: false,
739        };
740        assert!(
741            LayeredSourceProvider::session_only(&wrong_len)
742                .resolve(SourceKey::Session(session_id))
743                .is_none()
744        );
745        let wrong_location = BadProvider {
746            requested: session_id,
747            returned: session_id,
748            bad_len: false,
749            bad_location: true,
750        };
751        let wrong_location = LayeredSourceProvider::session_only(&wrong_location);
752        assert_eq!(wrong_location.line_column(SourceKey::Session(session_id), 0), None);
753        assert_eq!(wrong_location.line_column(SourceKey::Session(session_id), 2), None);
754    }
755
756    #[test]
757    fn source_map_is_transport_safe() {
758        fn require<T: Send + Sync>() {}
759        require::<SourceMap>();
760
761        let empty_name = "".to_string();
762        let mut sources = SourceMap::new(SourceNamespace::new_unchecked(1));
763        let id = sources.insert(empty_name, "", None).unwrap();
764        let source = sources.get(id).unwrap();
765        assert_eq!(source.display_name, "");
766        assert_eq!(source.byte_len, 0);
767        assert_eq!(sources.line_column(id, 0), LineColumn::new(1, 1));
768    }
769}