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, Serialize, ts_rs::TS, JsonSchema)]
9#[ts(export)]
10pub struct ModuleId(u32);
11
12impl<'de> Deserialize<'de> for ModuleId {
13    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
14        struct ModuleIdVisitor;
15
16        impl serde::de::Visitor<'_> for ModuleIdVisitor {
17            type Value = ModuleId;
18
19            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20                formatter.write_str("a u32 module ID or its decimal string representation")
21            }
22
23            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<ModuleId, E> {
24                u32::try_from(value)
25                    .map(ModuleId)
26                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(value), &self))
27            }
28
29            fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<ModuleId, E> {
30                u32::try_from(value)
31                    .map(ModuleId)
32                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(value), &self))
33            }
34
35            fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<ModuleId, E> {
36                value
37                    .parse::<u32>()
38                    .map(ModuleId)
39                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
40            }
41        }
42
43        // Untagged enums buffer JSON map keys as strings, bypassing serde_json's
44        // usual conversion of numeric keys. Accept those strings without changing
45        // how module IDs are serialized as values or in binary formats.
46        if deserializer.is_human_readable() {
47            deserializer.deserialize_any(ModuleIdVisitor)
48        } else {
49            deserializer.deserialize_u32(ModuleIdVisitor)
50        }
51    }
52}
53
54impl ModuleId {
55    pub fn from_usize(id: usize) -> Self {
56        Self(u32::try_from(id).expect("module ID should fit in a u32"))
57    }
58
59    pub fn as_usize(&self) -> usize {
60        usize::try_from(self.0).expect("module ID should fit in a usize")
61    }
62
63    /// Top-level file is the one being executed.
64    /// Represented by module ID of 0, i.e. the default value.
65    pub fn is_top_level(&self) -> bool {
66        *self == Self::default()
67    }
68}
69
70impl std::fmt::Display for ModuleId {
71    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72        write!(f, "{}", self.0)
73    }
74}
75
76/// The first two items are the start and end points (byte offsets from the start of the file).
77/// The third item is whether the source range belongs to the 'main' file, i.e., the file currently
78/// being rendered/displayed in the editor.
79//
80// Don't use a doc comment for the below since the above goes in the website docs.
81// @see isTopLevelModule() in wasm.ts.
82// TODO we need to handle modules better in the frontend.
83#[derive(Debug, Default, Deserialize, Serialize, PartialEq, Copy, Clone, ts_rs::TS, Hash, Eq, JsonSchema)]
84#[ts(export, type = "[number, number, number]")]
85pub struct SourceRange([usize; 3]);
86
87impl From<[usize; 3]> for SourceRange {
88    fn from(value: [usize; 3]) -> Self {
89        Self(value)
90    }
91}
92
93impl Ord for SourceRange {
94    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
95        // Sort by module id first, then by start and end.
96        let module_id_cmp = self.module_id().cmp(&other.module_id());
97        if module_id_cmp != std::cmp::Ordering::Equal {
98            return module_id_cmp;
99        }
100        let start_cmp = self.start().cmp(&other.start());
101        if start_cmp != std::cmp::Ordering::Equal {
102            return start_cmp;
103        }
104        self.end().cmp(&other.end())
105    }
106}
107
108impl PartialOrd for SourceRange {
109    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
110        Some(self.cmp(other))
111    }
112}
113
114impl From<&SourceRange> for miette::SourceSpan {
115    fn from(source_range: &SourceRange) -> Self {
116        let length = source_range.end() - source_range.start();
117        let start = miette::SourceOffset::from(source_range.start());
118        Self::new(start, length)
119    }
120}
121
122impl From<SourceRange> for miette::SourceSpan {
123    fn from(source_range: SourceRange) -> Self {
124        Self::from(&source_range)
125    }
126}
127
128impl SourceRange {
129    /// Create a new source range.
130    pub fn new(start: usize, end: usize, module_id: ModuleId) -> Self {
131        Self([start, end, module_id.as_usize()])
132    }
133
134    /// A source range that doesn't correspond to any source code.
135    pub fn synthetic() -> Self {
136        Self::default()
137    }
138
139    pub fn merge(mut ranges: impl Iterator<Item = SourceRange>) -> Self {
140        let mut result = ranges.next().unwrap_or_default();
141
142        for r in ranges {
143            debug_assert!(r.0[2] == result.0[2], "Merging source ranges from different files");
144            if r.0[0] < result.0[0] {
145                result.0[0] = r.0[0]
146            }
147            if r.0[1] > result.0[1] {
148                result.0[1] = r.0[1];
149            }
150        }
151
152        result
153    }
154
155    /// True if this is a source range that doesn't correspond to any source
156    /// code.
157    pub fn is_synthetic(&self) -> bool {
158        self.start() == 0 && self.end() == 0
159    }
160
161    /// Get the start of the range.
162    pub fn start(&self) -> usize {
163        self.0[0]
164    }
165
166    /// Get the start of the range as a zero-length SourceRange, effectively collapse `self` to it's
167    /// start.
168    pub fn start_as_range(&self) -> Self {
169        Self([self.0[0], self.0[0], self.0[2]])
170    }
171
172    /// Get the end of the range.
173    pub fn end(&self) -> usize {
174        self.0[1]
175    }
176
177    /// Get the module ID of the range.
178    pub fn module_id(&self) -> ModuleId {
179        ModuleId::from_usize(self.0[2])
180    }
181
182    /// True if this source range is from the top-level module.
183    pub fn is_top_level_module(&self) -> bool {
184        self.module_id().is_top_level()
185    }
186
187    /// Check if the range contains a position.
188    pub fn contains(&self, pos: usize) -> bool {
189        pos >= self.start() && pos <= self.end()
190    }
191
192    /// Check if the range contains another range.  Modules must match.
193    pub fn contains_range(&self, other: &Self) -> bool {
194        self.module_id() == other.module_id() && self.start() <= other.start() && self.end() >= other.end()
195    }
196}