Skip to main content

lisette_syntax/program/
emit_input.rs

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