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