Skip to main content

rapx/util/
path.rs

1use crate::compat::GenericArgsRef;
2use itertools::Itertools;
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::{DefId, LOCAL_CRATE};
5use rustc_middle::ty::{self, Ty, TyCtxt, TyKind};
6use std::collections::HashMap;
7
8/// A utility to resolve the actual visible path for re-export items.
9pub struct PathResolver<'tcx> {
10    tcx: TyCtxt<'tcx>,
11    path_map: HashMap<DefId, String>,
12}
13
14pub fn get_path_resolver<'tcx>(tcx: TyCtxt<'tcx>) -> PathResolver<'tcx> {
15    let mut resolver = PathResolver::new(tcx);
16    resolver.build(LOCAL_CRATE.as_def_id(), String::new());
17    resolver
18}
19
20fn join_path_with_double_colon(parts: &[&str]) -> String {
21    parts.iter().filter(|s| !s.is_empty()).join("::")
22}
23
24impl<'tcx> PathResolver<'tcx> {
25    fn new(tcx: TyCtxt<'tcx>) -> Self {
26        PathResolver {
27            tcx,
28            path_map: HashMap::new(),
29        }
30    }
31
32    fn build(&mut self, mod_id: DefId, current_path: String) {
33        rap_trace!("enter module: {:?}, path: {}", mod_id, current_path);
34        let childs = if mod_id.is_local() {
35            self.tcx.module_children_local(mod_id.expect_local())
36        } else {
37            self.tcx.module_children(mod_id)
38        };
39
40        for child in childs {
41            rap_trace!(
42                "processing child: {:?}, ident = {}",
43                child.res,
44                child.ident.as_str()
45            );
46            if !child.vis.is_public() || child.ident.as_str() == "_" {
47                continue;
48            }
49            if let Some(did) = child.res.opt_def_id() {
50                let path = join_path_with_double_colon(&[&current_path, child.ident.as_str()]);
51                self.path_map.entry(did).or_insert(path.clone());
52                if self.tcx.def_kind(did).is_module_like() {
53                    self.build(did, path);
54                }
55            }
56        }
57    }
58
59    fn non_assoc_path_str(&self, def_id: DefId) -> String {
60        match self.path_map.get(&def_id) {
61            Some(path) => path.clone(),
62            None => {
63                // if def_id is from local crate, but we cannot find it in path_map,
64                // report this error.
65                if def_id.is_local() {
66                    rap_error!(
67                        "[PathResolver] cannot find path for {:?}, fallback to self.tcx.def_path_str",
68                        def_id
69                    );
70                }
71                self.tcx.def_path_str(def_id)
72            }
73        }
74    }
75
76    pub fn path_exists(&self, did: DefId) -> bool {
77        let Some((assoc_id, kind)) = self.tcx.assoc_parent(did) else {
78            // check non associated item
79            return did.is_local() && self.path_map.contains_key(&did)
80            // for did from other crate, we rely on tcx.visibility, 
81            // which is not 100% accurate, but should be good enough in most cases.
82                || !did.is_local() && self.tcx.visibility(did).is_public();
83        };
84
85        if !self.tcx.visibility(did).is_public() {
86            return false;
87        }
88
89        match kind {
90            DefKind::Impl { .. } => {
91                let self_ty = self
92                    .tcx
93                    .type_of(assoc_id)
94                    .instantiate_identity()
95                    .skip_norm_wip();
96                match self_ty.kind() {
97                    // Theoretically, we need to check visibility of generic args.
98                    // However, it is a bit complicated and we currently do not consider it.
99                    TyKind::Adt(adt_def, _) => self.path_exists(adt_def.did()),
100                    _ => true,
101                }
102            }
103            DefKind::Trait => self.path_exists(assoc_id),
104            _ => panic!(
105                "unexpected parent kind: {:?} for assoc item: {:?}",
106                kind, did
107            ),
108        }
109    }
110
111    pub fn ty_str(&self, ty: Ty<'tcx>) -> String {
112        match ty.kind() {
113            TyKind::Adt(adt_def, args) => self.path_str_with_args(adt_def.did(), *args),
114            TyKind::Array(inner_ty, const_) => {
115                format!("[{};{}]", self.ty_str(*inner_ty), const_)
116            }
117            TyKind::Tuple(tys) => {
118                format!("({})", tys.iter().map(|ty| self.ty_str(ty)).join(", "))
119            }
120            TyKind::Ref(region, inner_ty, mutability) => {
121                format!(
122                    "&{} {}{}",
123                    region,
124                    mutability.prefix_str(),
125                    self.ty_str(*inner_ty)
126                )
127            }
128            TyKind::RawPtr(inner_ty, mutability) => {
129                format!("*{} {}", mutability.ptr_str(), self.ty_str(*inner_ty))
130            }
131            TyKind::Slice(inner_ty) => {
132                format!("[{}]", self.ty_str(*inner_ty))
133            }
134            TyKind::Alias(is_rigid, alias_ty) => match alias_ty.kind {
135                ty::AliasTyKind::Projection { def_id } => {
136                    self.path_str_with_args(def_id, alias_ty.args)
137                }
138                ty::AliasTyKind::Opaque { .. } => {
139                    let ty_str = alias_ty.to_ty(self.tcx, *is_rigid).to_string();
140                    rap_warn!(
141                        "encounter opaque type {}, type string might be private",
142                        ty_str
143                    );
144                    ty_str
145                }
146                kind => {
147                    panic!(
148                        "unexpected alias kind: {:?} for alias_ty: {:?}",
149                        kind, alias_ty
150                    );
151                }
152            },
153            _ => ty.to_string(),
154        }
155    }
156
157    #[allow(unused)]
158    pub fn path_str(&self, def_id: DefId) -> String {
159        self.path_str_with_args(def_id, ty::GenericArgs::identity_for_item(self.tcx, def_id))
160    }
161
162    pub fn path_str_with_args(&self, def_id: DefId, args: GenericArgsRef<'tcx>) -> String {
163        // `{assoc_path}::{item_name}`
164        if let Some((assoc_id, kind)) = self.tcx.assoc_parent(def_id) {
165            rap_trace!("assoc item: {:?} => {:?}", assoc_id, kind);
166            // the number of generic of assoc parent
167            let num_generic = self.tcx.generics_of(assoc_id).own_params.len();
168
169            let (parent_args, own_args) = args.as_slice().split_at(num_generic);
170
171            let parent_path_str = match kind {
172                // Trait Impl
173                DefKind::Impl { of_trait: true } => {
174                    let trait_ref = self
175                        .tcx
176                        .impl_trait_ref(assoc_id)
177                        .instantiate(self.tcx, parent_args);
178
179                    let trait_ref = trait_ref.skip_norm_wip();
180
181                    self.qualified_path_str(
182                        trait_ref.self_ty(),
183                        trait_ref.def_id,
184                        &trait_ref.args.as_slice()[1..],
185                    )
186                }
187                // inherent impl
188                DefKind::Impl { of_trait: false } => {
189                    let self_ty = self
190                        .tcx
191                        .type_of(assoc_id)
192                        .instantiate(self.tcx, parent_args);
193                    let self_ty = self_ty.skip_norm_wip();
194                    self.ty_str(self_ty)
195                }
196                // Trait
197                DefKind::Trait => {
198                    self.qualified_path_str(parent_args[0].expect_ty(), assoc_id, &parent_args[1..])
199                }
200                _ => {
201                    unreachable!(
202                        "unexpected assoc parent: {:?} => {:?}, def_id: {:?}, path: {:?}",
203                        assoc_id,
204                        kind,
205                        def_id,
206                        self.tcx.def_path_str_with_args(def_id, args)
207                    );
208                }
209            };
210
211            let args_str = self.non_syn_generic_args_str(def_id, own_args);
212
213            join_path_with_double_colon(&[
214                &parent_path_str,
215                self.tcx.item_name(def_id).as_str(),
216                &args_str,
217            ])
218        } else {
219            // non assoc item
220            let path_str = self.non_assoc_path_str(def_id);
221            let args_str = self.non_syn_generic_args_str(def_id, args.as_slice());
222            join_path_with_double_colon(&[path_str.as_str(), args_str.as_str()])
223        }
224    }
225
226    pub fn generic_arg_str(&self, arg: ty::GenericArg<'tcx>) -> String {
227        match arg.kind() {
228            ty::GenericArgKind::Lifetime(_) => "'_".to_string(),
229            ty::GenericArgKind::Type(ty) => self.ty_str(ty),
230            ty::GenericArgKind::Const(const_) => format!("{}", const_),
231        }
232    }
233
234    /// Format `<Self as Trait<args>>` for a trait impl or trait-associated item.
235    fn qualified_path_str(
236        &self,
237        self_ty: Ty<'tcx>,
238        trait_id: DefId,
239        args: &[ty::GenericArg<'tcx>],
240    ) -> String {
241        let self_ty_str = self.ty_str(self_ty);
242        let trait_str = self.non_assoc_path_str(trait_id);
243        if args.is_empty() {
244            format!("<{} as {}>", self_ty_str, trait_str)
245        } else {
246            format!(
247                "<{} as {}{}>",
248                self_ty_str,
249                trait_str,
250                self.generic_args_str(args)
251            )
252        }
253    }
254
255    fn generic_args_str(&self, generic_args: &[ty::GenericArg<'tcx>]) -> String {
256        format!(
257            "<{}>",
258            generic_args
259                .iter()
260                .map(|arg| self.generic_arg_str(*arg))
261                .join(", ")
262        )
263    }
264
265    fn non_syn_generic_args_str(&self, def_id: DefId, args: &[ty::GenericArg<'tcx>]) -> String {
266        let defs = self.tcx.generics_of(def_id).own_params.as_slice();
267
268        assert!(defs.len() == args.len());
269
270        let non_syn_args = args
271            .iter()
272            .zip(defs.iter())
273            .filter_map(|(arg, param)| {
274                if param.kind.is_synthetic() {
275                    None
276                } else {
277                    Some(*arg)
278                }
279            })
280            .collect_vec();
281
282        // No suffix for empty generic args, e.g. render `foo` instead of `foo::<>`.
283        if non_syn_args.is_empty() {
284            String::new()
285        } else {
286            self.generic_args_str(&non_syn_args)
287        }
288    }
289}