Skip to main content

kcl_error/
source_range.rs

1use std::fmt;
2
3use schemars::JsonSchema;
4use serde::Deserialize;
5use serde::Serialize;
6
7/// Identifier of a source file.  Uses a u32 to keep the size small.
8#[derive(Debug, Default, Ord, PartialOrd, Eq, PartialEq, Clone, Copy, Hash, Deserialize, Serialize, ts_rs::TS)]
9#[ts(export)]
10pub struct ModuleId(u32);
11
12impl ModuleId {
13    pub fn from_usize(id: usize) -> Self {
14        Self(u32::try_from(id).expect("module ID should fit in a u32"))
15    }
16
17    pub fn as_usize(&self) -> usize {
18        usize::try_from(self.0).expect("module ID should fit in a usize")
19    }
20
21    /// Top-level file is the one being executed.
22    /// Represented by module ID of 0, i.e. the default value.
23    pub fn is_top_level(&self) -> bool {
24        *self == Self::default()
25    }
26}
27
28impl std::fmt::Display for ModuleId {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        write!(f, "{}", self.0)
31    }
32}
33
34/// The first two items are the start and end points (byte offsets from the start of the file).
35/// The third item is whether the source range belongs to the 'main' file, i.e., the file currently
36/// being rendered/displayed in the editor.
37//
38// Don't use a doc comment for the below since the above goes in the website docs.
39// @see isTopLevelModule() in wasm.ts.
40// TODO we need to handle modules better in the frontend.
41#[derive(Debug, Default, Deserialize, Serialize, PartialEq, Copy, Clone, ts_rs::TS, Hash, Eq, JsonSchema)]
42#[ts(export, type = "[number, number, number]")]
43pub struct SourceRange([usize; 3]);
44
45impl From<[usize; 3]> for SourceRange {
46    fn from(value: [usize; 3]) -> Self {
47        Self(value)
48    }
49}
50
51impl Ord for SourceRange {
52    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
53        // Sort by module id first, then by start and end.
54        let module_id_cmp = self.module_id().cmp(&other.module_id());
55        if module_id_cmp != std::cmp::Ordering::Equal {
56            return module_id_cmp;
57        }
58        let start_cmp = self.start().cmp(&other.start());
59        if start_cmp != std::cmp::Ordering::Equal {
60            return start_cmp;
61        }
62        self.end().cmp(&other.end())
63    }
64}
65
66impl PartialOrd for SourceRange {
67    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
68        Some(self.cmp(other))
69    }
70}
71
72impl From<&SourceRange> for miette::SourceSpan {
73    fn from(source_range: &SourceRange) -> Self {
74        let length = source_range.end() - source_range.start();
75        let start = miette::SourceOffset::from(source_range.start());
76        Self::new(start, length)
77    }
78}
79
80impl From<SourceRange> for miette::SourceSpan {
81    fn from(source_range: SourceRange) -> Self {
82        Self::from(&source_range)
83    }
84}
85
86impl SourceRange {
87    /// Create a new source range.
88    pub fn new(start: usize, end: usize, module_id: ModuleId) -> Self {
89        Self([start, end, module_id.as_usize()])
90    }
91
92    /// A source range that doesn't correspond to any source code.
93    pub fn synthetic() -> Self {
94        Self::default()
95    }
96
97    pub fn merge(mut ranges: impl Iterator<Item = SourceRange>) -> Self {
98        let mut result = ranges.next().unwrap_or_default();
99
100        for r in ranges {
101            debug_assert!(r.0[2] == result.0[2], "Merging source ranges from different files");
102            if r.0[0] < result.0[0] {
103                result.0[0] = r.0[0]
104            }
105            if r.0[1] > result.0[1] {
106                result.0[1] = r.0[1];
107            }
108        }
109
110        result
111    }
112
113    /// True if this is a source range that doesn't correspond to any source
114    /// code.
115    pub fn is_synthetic(&self) -> bool {
116        self.start() == 0 && self.end() == 0
117    }
118
119    /// Get the start of the range.
120    pub fn start(&self) -> usize {
121        self.0[0]
122    }
123
124    /// Get the start of the range as a zero-length SourceRange, effectively collapse `self` to it's
125    /// start.
126    pub fn start_as_range(&self) -> Self {
127        Self([self.0[0], self.0[0], self.0[2]])
128    }
129
130    /// Get the end of the range.
131    pub fn end(&self) -> usize {
132        self.0[1]
133    }
134
135    /// Get the module ID of the range.
136    pub fn module_id(&self) -> ModuleId {
137        ModuleId::from_usize(self.0[2])
138    }
139
140    /// True if this source range is from the top-level module.
141    pub fn is_top_level_module(&self) -> bool {
142        self.module_id().is_top_level()
143    }
144
145    /// Check if the range contains a position.
146    pub fn contains(&self, pos: usize) -> bool {
147        pos >= self.start() && pos <= self.end()
148    }
149
150    /// Check if the range contains another range.  Modules must match.
151    pub fn contains_range(&self, other: &Self) -> bool {
152        self.module_id() == other.module_id() && self.start() <= other.start() && self.end() >= other.end()
153    }
154}