charon_lib/transform/
remove_unused_self_clause.rs

1//! We have added an explicit `Self: Trait` clause to the function and global items that correspond
2//! to a trait method/associated const declaration. This pass removes the clause in question if it
3//! is not used by the item.
4use derive_generic_visitor::*;
5use std::collections::HashSet;
6
7use crate::ast::*;
8
9use super::{ctx::TransformPass, TransformCtx};
10
11struct FoundClause;
12
13struct UsesClauseVisitor(TraitClauseId);
14impl Visitor for UsesClauseVisitor {
15    type Break = FoundClause;
16}
17
18/// Visit an item looking for uses of the given clause.
19impl VisitAst for UsesClauseVisitor {
20    fn visit_trait_clause_id(&mut self, x: &TraitClauseId) -> ControlFlow<Self::Break> {
21        if *x == self.0 {
22            Break(FoundClause)
23        } else {
24            Continue(())
25        }
26    }
27    fn visit_trait_clause(&mut self, _: &TraitClause) -> ControlFlow<Self::Break> {
28        // Don't look inside the clause declaration as this will always contain the
29        // `TraitClauseId`.
30        Continue(())
31    }
32    fn visit_fun_decl(&mut self, x: &FunDecl) -> ControlFlow<Self::Break> {
33        if let Err(Opaque) = x.body {
34            // For function without bodies we can't know whether the clause is used so we err on
35            // the side of it being used.
36            return Break(FoundClause);
37        }
38        self.visit_inner(x)
39    }
40}
41
42#[derive(Visitor)]
43struct RemoveSelfVisitor {
44    remove_in: HashSet<AnyTransId>,
45}
46
47impl RemoveSelfVisitor {
48    fn process_item(&self, id: impl Into<AnyTransId>, args: &mut GenericArgs) {
49        if self.remove_in.contains(&id.into()) {
50            args.trait_refs
51                .remove_and_shift_ids(TraitClauseId::from_raw(0));
52        }
53    }
54}
55impl VisitAstMut for RemoveSelfVisitor {
56    fn enter_type_decl_ref(&mut self, x: &mut TypeDeclRef) {
57        match x.id {
58            TypeId::Adt(id) => self.process_item(id, &mut x.generics),
59            TypeId::Tuple => {}
60            TypeId::Builtin(_) => {}
61        }
62    }
63    fn enter_fun_decl_ref(&mut self, x: &mut FunDeclRef) {
64        self.process_item(x.id, &mut x.generics);
65    }
66    fn enter_fn_ptr(&mut self, x: &mut FnPtr) {
67        match x.func.as_ref() {
68            FunIdOrTraitMethodRef::Fun(FunId::Regular(id)) => {
69                self.process_item(*id, &mut x.generics)
70            }
71            FunIdOrTraitMethodRef::Fun(FunId::Builtin(_)) => {}
72            FunIdOrTraitMethodRef::Trait(..) => {}
73        }
74    }
75    fn enter_global_decl_ref(&mut self, x: &mut GlobalDeclRef) {
76        self.process_item(x.id, &mut x.generics);
77    }
78    fn enter_trait_impl_ref(&mut self, x: &mut TraitImplRef) {
79        self.process_item(x.id, &mut x.generics);
80    }
81}
82
83pub struct Transform;
84impl TransformPass for Transform {
85    fn transform_ctx(&self, ctx: &mut TransformCtx) {
86        if !ctx.options.remove_unused_self_clauses {
87            return;
88        }
89        let self_clause_id = TraitClauseId::from_raw(0);
90        let mut doesnt_use_self: HashSet<AnyTransId> = Default::default();
91
92        // We explore only items with an explicit `Self` clause, namely method and associated const
93        // declarations.
94        for tdecl in &ctx.translated.trait_decls {
95            let methods = tdecl.methods().map(|(_, bound_fn)| bound_fn.skip_binder.id);
96            // For consts, we need to explore the corresponding initializer body.
97            let consts = tdecl
98                .const_defaults
99                .iter()
100                .filter_map(|(_, x)| ctx.translated.global_decls.get(x.id))
101                .map(|gdecl| gdecl.init);
102            let funs = methods
103                .chain(consts)
104                .filter_map(|id: FunDeclId| ctx.translated.fun_decls.get(id));
105            for fun in funs {
106                match fun.drive(&mut UsesClauseVisitor(self_clause_id)) {
107                    Continue(()) => {
108                        doesnt_use_self.insert(fun.def_id.into());
109                        if let Some(gid) = fun.is_global_initializer {
110                            doesnt_use_self.insert(gid.into());
111                        }
112                    }
113                    Break(FoundClause) => {}
114                }
115            }
116        }
117
118        // In each item, remove the first clause and renumber the others.
119        for &id in &doesnt_use_self {
120            let Some(mut item) = ctx.translated.get_item_mut(id) else {
121                continue;
122            };
123            item.generic_params()
124                .trait_clauses
125                .remove_and_shift_ids(self_clause_id);
126            item.dyn_visit_mut(|clause_id: &mut TraitClauseId| {
127                *clause_id = TraitClauseId::from_usize(clause_id.index() - 1);
128            });
129        }
130
131        // Update any `GenericArgs` destined for the items we just changed.
132        RemoveSelfVisitor {
133            remove_in: doesnt_use_self,
134        }
135        .visit_by_val_infallible(&mut ctx.translated);
136    }
137}