1use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
2
3use ecow::EcoString;
4
5use crate::ast::{BindingId as AstBindingId, Pattern, RestPattern, Span};
6use crate::types::Symbol;
7
8use super::{Definition, File};
9
10#[derive(Debug, Clone, Default)]
11pub struct UnusedInfo {
12 symbols: HashSet<Span>,
13 pub imports_by_module: HashMap<EcoString, HashSet<EcoString>>,
14}
15
16impl UnusedInfo {
17 pub fn mark_binding_unused(&mut self, span: Span) {
18 self.symbols.insert(span);
19 }
20
21 pub fn is_unused_binding(&self, pattern: &Pattern) -> bool {
22 match pattern {
23 Pattern::Identifier { span, .. } => self.symbols.contains(span),
24 Pattern::AsBinding { span, name, .. } => {
25 let name_span = Span::new(
26 span.file_id,
27 span.byte_offset + span.byte_length - name.len() as u32,
28 name.len() as u32,
29 );
30 self.symbols.contains(&name_span)
31 }
32 _ => false,
33 }
34 }
35
36 pub fn is_unused_rest_binding(&self, rest: &RestPattern) -> bool {
37 match rest {
38 RestPattern::Bind { span, .. } => self.symbols.contains(span),
39 _ => false,
40 }
41 }
42
43 pub fn mark_definition_unused(&mut self, span: Span) {
44 self.symbols.insert(span);
45 }
46
47 pub fn is_unused_definition(&self, span: &Span) -> bool {
48 self.symbols.contains(span)
49 }
50
51 pub fn merge(&mut self, other: UnusedInfo) {
52 let UnusedInfo {
53 symbols,
54 imports_by_module,
55 } = other;
56 self.symbols.extend(symbols);
57 for (module, imports) in imports_by_module {
58 self.imports_by_module
59 .entry(module)
60 .or_default()
61 .extend(imports);
62 }
63 }
64}
65
66#[derive(Debug, Clone)]
67pub struct TestFunction {
68 qualified_name: Symbol,
69 pub title: Option<String>,
70 pub doc: Option<String>,
71 pub span: Span,
72}
73
74impl TestFunction {
75 pub fn new(
76 module_id: &str,
77 name: &str,
78 title: Option<String>,
79 doc: Option<String>,
80 span: Span,
81 ) -> Self {
82 Self {
83 qualified_name: Symbol::from_parts(module_id, name),
84 title,
85 doc,
86 span,
87 }
88 }
89
90 pub fn module_id(&self) -> &str {
91 self.qualified_name
92 .without_last_segment()
93 .expect("test names are constructed with a module")
94 }
95
96 pub fn qualified_name(&self) -> &str {
97 self.qualified_name.as_str()
98 }
99
100 pub fn name(&self) -> &str {
101 self.qualified_name.last_segment()
102 }
103}
104
105#[derive(Debug, Clone, Default)]
106pub struct TestIndex {
107 tests: Vec<TestFunction>,
108}
109
110impl TestIndex {
111 pub fn push(&mut self, test: TestFunction) {
112 self.tests.push(test);
113 }
114
115 pub fn tests(&self) -> &[TestFunction] {
116 &self.tests
117 }
118
119 pub fn contains_qualified(&self, qualified_name: &str) -> bool {
120 self.tests
121 .iter()
122 .any(|test| test.qualified_name == qualified_name)
123 }
124}
125
126#[derive(Debug, Clone, Default)]
127pub struct EqualityIndex {
128 by_id: HashMap<String, EqualityInfo>,
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132enum EqualityKind {
133 DeclaredMethod,
134 SynthesizedMethod,
135 UfcsLowered,
136}
137
138#[derive(Debug, Clone)]
139struct EqualityInfo {
140 kind: EqualityKind,
141 private_to_module: Option<String>,
142}
143
144fn visible_from(private_to_module: &Option<String>, current_module: &str) -> bool {
145 match private_to_module {
146 None => true,
147 Some(module) => module == current_module,
148 }
149}
150
151impl EqualityIndex {
152 pub fn insert_declared_method(&mut self, id: String, private_to_module: Option<String>) {
153 self.by_id.insert(
154 id,
155 EqualityInfo {
156 kind: EqualityKind::DeclaredMethod,
157 private_to_module,
158 },
159 );
160 }
161
162 pub fn insert_synthesized_method(&mut self, id: String, private_to_module: Option<String>) {
163 self.by_id.insert(
164 id,
165 EqualityInfo {
166 kind: EqualityKind::SynthesizedMethod,
167 private_to_module,
168 },
169 );
170 }
171
172 pub fn insert_ufcs_lowered(&mut self, id: String, private_to_module: Option<String>) {
173 self.by_id.insert(
174 id,
175 EqualityInfo {
176 kind: EqualityKind::UfcsLowered,
177 private_to_module,
178 },
179 );
180 }
181
182 pub fn usable_from(&self, id: &str, current_module: &str) -> bool {
183 matches!(
184 self.by_id.get(id),
185 Some(EqualityInfo {
186 kind: EqualityKind::DeclaredMethod | EqualityKind::SynthesizedMethod,
187 private_to_module,
188 }) if visible_from(private_to_module, current_module)
189 )
190 }
191
192 pub fn is_ufcs_lowered_from(&self, id: &str, current_module: &str) -> bool {
193 matches!(
194 self.by_id.get(id),
195 Some(EqualityInfo {
196 kind: EqualityKind::UfcsLowered,
197 private_to_module,
198 }) if visible_from(private_to_module, current_module)
199 )
200 }
201
202 pub fn is_synthesized(&self, id: &str) -> bool {
203 matches!(
204 self.by_id.get(id),
205 Some(EqualityInfo {
206 kind: EqualityKind::SynthesizedMethod,
207 ..
208 })
209 )
210 }
211}
212
213#[derive(Debug, Clone, Default)]
214pub struct MutationInfo {
215 bindings: HashMap<AstBindingId, BindingMutation>,
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum BindingMutation {
220 Direct,
221 ThroughAlias,
222}
223
224impl BindingMutation {
225 pub fn merged_with(self, other: Self) -> Self {
226 match (self, other) {
227 (Self::ThroughAlias, _) | (_, Self::ThroughAlias) => Self::ThroughAlias,
228 (Self::Direct, Self::Direct) => Self::Direct,
229 }
230 }
231}
232
233impl MutationInfo {
234 pub fn record(&mut self, id: AstBindingId, mutation: BindingMutation) {
235 self.bindings
236 .entry(id)
237 .and_modify(|current| *current = current.merged_with(mutation))
238 .or_insert(mutation);
239 }
240
241 pub fn mutation(&self, id: AstBindingId) -> Option<BindingMutation> {
242 self.bindings.get(&id).copied()
243 }
244
245 pub fn is_mutated(&self, id: AstBindingId) -> bool {
246 self.bindings.contains_key(&id)
247 }
248
249 pub fn is_alias_mutated(&self, id: AstBindingId) -> bool {
250 self.mutation(id) == Some(BindingMutation::ThroughAlias)
251 }
252}
253
254#[derive(Default)]
255pub struct EmitInput {
256 pub files: HashMap<u32, File>,
257 pub definitions: HashMap<Symbol, Definition>,
258 pub entry_module_id: String,
259 pub unused: UnusedInfo,
260 pub mutations: MutationInfo,
261 pub cached_modules: HashSet<String>,
262 pub equality_index: EqualityIndex,
263 pub test_index: TestIndex,
264 pub go_package_names: HashMap<String, String>,
265 pub go_module_ids: HashSet<String>,
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 fn span(offset: u32) -> Span {
273 Span::new(0, offset, 1)
274 }
275
276 #[test]
277 fn merge_extends_bindings_definitions_and_imports() {
278 let mut a = UnusedInfo::default();
279 a.mark_binding_unused(span(0));
280 a.mark_definition_unused(span(1));
281 a.imports_by_module
282 .insert("m1".into(), HashSet::from_iter(["x".into()]));
283
284 let mut b = UnusedInfo::default();
285 b.mark_binding_unused(span(2));
286 b.mark_definition_unused(span(3));
287 b.imports_by_module
288 .insert("m1".into(), HashSet::from_iter(["y".into()]));
289 b.imports_by_module
290 .insert("m2".into(), HashSet::from_iter(["z".into()]));
291
292 a.merge(b);
293
294 assert_eq!(a.symbols.len(), 4);
295 assert_eq!(a.imports_by_module["m1"].len(), 2);
296 assert_eq!(a.imports_by_module["m2"].len(), 1);
297 }
298}