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