Skip to main content

lisette_syntax/program/
emit_input.rs

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    pub module_id: String,
69    pub qualified_name: String,
70    pub title: Option<String>,
71    pub doc: Option<String>,
72    pub span: Span,
73}
74
75#[derive(Debug, Clone, Default)]
76pub struct TestIndex {
77    tests: Vec<TestFunction>,
78}
79
80impl TestIndex {
81    pub fn push(&mut self, test: TestFunction) {
82        self.tests.push(test);
83    }
84
85    pub fn tests(&self) -> &[TestFunction] {
86        &self.tests
87    }
88
89    pub fn contains_qualified(&self, qualified_name: &str) -> bool {
90        self.tests
91            .iter()
92            .any(|t| t.qualified_name == qualified_name)
93    }
94}
95
96#[derive(Debug, Clone, Default)]
97pub struct EqualityIndex {
98    by_id: HashMap<String, EqualityInfo>,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102enum EqualityKind {
103    DeclaredMethod,
104    SynthesizedMethod,
105    UfcsLowered,
106}
107
108#[derive(Debug, Clone)]
109struct EqualityInfo {
110    kind: EqualityKind,
111    private_to_module: Option<String>,
112}
113
114fn visible_from(private_to_module: &Option<String>, current_module: &str) -> bool {
115    match private_to_module {
116        None => true,
117        Some(module) => module == current_module,
118    }
119}
120
121impl EqualityIndex {
122    pub fn insert_declared_method(&mut self, id: String, private_to_module: Option<String>) {
123        self.by_id.insert(
124            id,
125            EqualityInfo {
126                kind: EqualityKind::DeclaredMethod,
127                private_to_module,
128            },
129        );
130    }
131
132    pub fn insert_synthesized_method(&mut self, id: String, private_to_module: Option<String>) {
133        self.by_id.insert(
134            id,
135            EqualityInfo {
136                kind: EqualityKind::SynthesizedMethod,
137                private_to_module,
138            },
139        );
140    }
141
142    pub fn insert_ufcs_lowered(&mut self, id: String, private_to_module: Option<String>) {
143        self.by_id.insert(
144            id,
145            EqualityInfo {
146                kind: EqualityKind::UfcsLowered,
147                private_to_module,
148            },
149        );
150    }
151
152    pub fn usable_from(&self, id: &str, current_module: &str) -> bool {
153        matches!(
154            self.by_id.get(id),
155            Some(EqualityInfo {
156                kind: EqualityKind::DeclaredMethod | EqualityKind::SynthesizedMethod,
157                private_to_module,
158            }) if visible_from(private_to_module, current_module)
159        )
160    }
161
162    pub fn is_ufcs_lowered_from(&self, id: &str, current_module: &str) -> bool {
163        matches!(
164            self.by_id.get(id),
165            Some(EqualityInfo {
166                kind: EqualityKind::UfcsLowered,
167                private_to_module,
168            }) if visible_from(private_to_module, current_module)
169        )
170    }
171
172    pub fn is_synthesized(&self, id: &str) -> bool {
173        matches!(
174            self.by_id.get(id),
175            Some(EqualityInfo {
176                kind: EqualityKind::SynthesizedMethod,
177                ..
178            })
179        )
180    }
181}
182
183#[derive(Debug, Clone, Default)]
184pub struct MutationInfo {
185    bindings: HashMap<AstBindingId, BindingMutation>,
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub enum BindingMutation {
190    Direct,
191    ThroughAlias,
192}
193
194impl BindingMutation {
195    pub fn merged_with(self, other: Self) -> Self {
196        match (self, other) {
197            (Self::ThroughAlias, _) | (_, Self::ThroughAlias) => Self::ThroughAlias,
198            (Self::Direct, Self::Direct) => Self::Direct,
199        }
200    }
201}
202
203impl MutationInfo {
204    pub fn record(&mut self, id: AstBindingId, mutation: BindingMutation) {
205        self.bindings
206            .entry(id)
207            .and_modify(|current| *current = current.merged_with(mutation))
208            .or_insert(mutation);
209    }
210
211    pub fn mutation(&self, id: AstBindingId) -> Option<BindingMutation> {
212        self.bindings.get(&id).copied()
213    }
214
215    pub fn is_mutated(&self, id: AstBindingId) -> bool {
216        self.bindings.contains_key(&id)
217    }
218
219    pub fn is_alias_mutated(&self, id: AstBindingId) -> bool {
220        self.mutation(id) == Some(BindingMutation::ThroughAlias)
221    }
222}
223
224#[derive(Default)]
225pub struct EmitInput {
226    pub files: HashMap<u32, File>,
227    pub definitions: HashMap<Symbol, Definition>,
228    pub entry_module_id: String,
229    pub unused: UnusedInfo,
230    pub mutations: MutationInfo,
231    pub cached_modules: HashSet<String>,
232    pub ufcs_methods: HashSet<(String, String)>,
233    pub equality_index: EqualityIndex,
234    pub test_index: TestIndex,
235    pub go_package_names: HashMap<String, String>,
236    pub go_module_ids: HashSet<String>,
237}
238
239#[cfg(test)]
240mod tests {
241    use super::*;
242
243    fn span(offset: u32) -> Span {
244        Span::new(0, offset, 1)
245    }
246
247    #[test]
248    fn merge_extends_bindings_definitions_and_imports() {
249        let mut a = UnusedInfo::default();
250        a.mark_binding_unused(span(0));
251        a.mark_definition_unused(span(1));
252        a.imports_by_module
253            .insert("m1".into(), HashSet::from_iter(["x".into()]));
254
255        let mut b = UnusedInfo::default();
256        b.mark_binding_unused(span(2));
257        b.mark_definition_unused(span(3));
258        b.imports_by_module
259            .insert("m1".into(), HashSet::from_iter(["y".into()]));
260        b.imports_by_module
261            .insert("m2".into(), HashSet::from_iter(["z".into()]));
262
263        a.merge(b);
264
265        assert_eq!(a.symbols.len(), 4);
266        assert_eq!(a.imports_by_module["m1"].len(), 2);
267        assert_eq!(a.imports_by_module["m2"].len(), 1);
268    }
269}