Skip to main content

rustia/
source_map.rs

1use crate::{CompiledModule, DiagnosticLimits, Error, Result};
2
3/// Keeps error locations aligned with input when a console adds wrapper text.
4///
5/// For example, a console may turn `1 + 2` into `return 1 + 2` before running
6/// it. Pass `SourceMap::generated_prefix(7)` to
7/// [`Chunk::source_map`](crate::Chunk::source_map) to hide the added `return `
8/// from source excerpts and positions. Wrappers cannot contain line breaks.
9/// Script-visible strings are unchanged.
10#[derive(Clone, Copy, Debug, Default)]
11pub struct SourceMap {
12    prefix_bytes: usize,
13    suffix_bytes: usize,
14}
15
16impl SourceMap {
17    /// Marks this many leading bytes as generated text on the first line.
18    pub const fn generated_prefix(prefix_bytes: usize) -> Self {
19        Self {
20            prefix_bytes,
21            suffix_bytes: 0,
22        }
23    }
24
25    /// Removes same-line generated text on both sides of the original input.
26    pub const fn generated_wrapper(prefix_bytes: usize, suffix_bytes: usize) -> Self {
27        Self {
28            prefix_bytes,
29            suffix_bytes,
30        }
31    }
32
33    pub(crate) fn validate(self, source: &[u8]) -> Result<()> {
34        let end = source
35            .len()
36            .checked_sub(self.suffix_bytes)
37            .filter(|end| *end >= self.prefix_bytes)
38            .ok_or_else(|| Error::embed("source-map wrapper exceeds the chunk length"))?;
39        let prefix = source
40            .get(..self.prefix_bytes)
41            .ok_or_else(|| Error::embed("source-map prefix exceeds the chunk length"))?;
42        let suffix = &source[end..];
43        if prefix.contains(&b'\n')
44            || prefix.contains(&b'\r')
45            || suffix.contains(&b'\n')
46            || suffix.contains(&b'\r')
47        {
48            return Err(Error::embed(
49                "source-map wrappers must not contain line breaks",
50            ));
51        }
52        Ok(())
53    }
54
55    pub(crate) fn apply(
56        self,
57        module: &mut CompiledModule,
58        source: &[u8],
59        limits: DiagnosticLimits,
60    ) {
61        if self.prefix_bytes == 0 && self.suffix_bytes == 0 {
62            return;
63        }
64        module.program.diagnostic_prefix_bytes = self.prefix_bytes;
65        module.program.diagnostic_mapped_length =
66            Some(source.len() - self.prefix_bytes - self.suffix_bytes);
67        module.program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
68            &source[self.prefix_bytes..source.len() - self.suffix_bytes],
69            limits.source_bytes,
70        );
71    }
72
73    pub(crate) fn apply_error(
74        self,
75        mut error: Error,
76        source: &[u8],
77        limits: DiagnosticLimits,
78    ) -> Error {
79        if self.prefix_bytes == 0 && self.suffix_bytes == 0 {
80            return error;
81        }
82        if let Some(diagnostic) = &mut error.diagnostic {
83            let diagnostic = std::sync::Arc::make_mut(diagnostic);
84            diagnostic.generated_source = diagnostic.span.is_some_and(|span| {
85                span.start < self.prefix_bytes || span.end > source.len() - self.suffix_bytes
86            });
87            diagnostic.span = diagnostic
88                .span
89                .filter(|_| !diagnostic.generated_source)
90                .and_then(|span| {
91                    Some(crate::DiagnosticSpan {
92                        start: span.start.checked_sub(self.prefix_bytes)?,
93                        end: span.end.checked_sub(self.prefix_bytes)?,
94                    })
95                });
96            diagnostic.snapshot = if diagnostic.generated_source {
97                None
98            } else {
99                crate::SourceSnapshot::copy_with_limit(
100                    &source[self.prefix_bytes..source.len() - self.suffix_bytes],
101                    limits.source_bytes,
102                )
103            };
104        }
105        error
106    }
107}