kcl_error/
source_range.rs1use std::fmt;
2
3use schemars::JsonSchema;
4use serde::Deserialize;
5use serde::Serialize;
6
7#[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 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 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#[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 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 pub fn new(start: usize, end: usize, module_id: ModuleId) -> Self {
131 Self([start, end, module_id.as_usize()])
132 }
133
134 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 pub fn is_synthetic(&self) -> bool {
158 self.start() == 0 && self.end() == 0
159 }
160
161 pub fn start(&self) -> usize {
163 self.0[0]
164 }
165
166 pub fn start_as_range(&self) -> Self {
169 Self([self.0[0], self.0[0], self.0[2]])
170 }
171
172 pub fn end(&self) -> usize {
174 self.0[1]
175 }
176
177 pub fn module_id(&self) -> ModuleId {
179 ModuleId::from_usize(self.0[2])
180 }
181
182 pub fn is_top_level_module(&self) -> bool {
184 self.module_id().is_top_level()
185 }
186
187 pub fn contains(&self, pos: usize) -> bool {
189 pos >= self.start() && pos <= self.end()
190 }
191
192 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}