Skip to main content

rapx/util/
name.rs

1use crate::def_ids::type_ids::{self, StdAdtType};
2use crate::util::mir_utils;
3use rustc_hir::def_id::DefId;
4use rustc_middle::ty::{GenericArgKind, Ty, TyCtxt, TyKind, print::with_no_trimmed_paths};
5use syn::Expr;
6
7/// The internal `crate::module::…` path of a `DefId` (e.g. `alloc::rcs::rc::Rc`),
8/// normalised from its `def_path_str` debug form.  Used for display/debug and as
9/// the fallback in [`public_def_path`] for items without a `Ty`.
10pub fn get_cleaned_def_path_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
11    let def_id_str = format!("{:?}", def_id);
12    let mut parts: Vec<&str> = def_id_str.split("::").collect();
13
14    // The `DefId` debug form is `DefId(.. ~ crate_name[hash]::path…)`; extract
15    // the crate name *exactly* (not by substring — `free_list_allocator` must
16    // not be misread as `alloc`).
17    let crate_name = def_id_str
18        .split("~ ")
19        .nth(1)
20        .and_then(|p| p.split('[').next())
21        .unwrap_or("");
22
23    let mut remove_first = false;
24    if let Some(first_part) = parts.get_mut(0) {
25        match crate_name {
26            "core" => *first_part = "core",
27            "std" => *first_part = "std",
28            "alloc" => *first_part = "alloc",
29            _ => remove_first = true,
30        }
31    }
32    if remove_first && !parts.is_empty() {
33        parts.remove(0);
34    }
35
36    let new_parts: Vec<String> = parts
37        .into_iter()
38        .filter_map(|s| {
39            if s.contains("{") {
40                if remove_first {
41                    get_struct_name(tcx, def_id)
42                } else {
43                    None
44                }
45            } else {
46                Some(s.to_string())
47            }
48        })
49        .collect();
50
51    let mut cleaned_path = new_parts.join("::");
52    cleaned_path = cleaned_path.trim_end_matches(')').to_string();
53    cleaned_path
54}
55
56/// Extract the implementing struct name from a `DefId` that belongs to an
57/// associated item (method / associated function).
58fn get_struct_name(tcx: TyCtxt<'_>, def_id: DefId) -> Option<String> {
59    if let Some(assoc_item) = tcx.opt_associated_item(def_id)
60        && let Some(impl_id) = assoc_item.impl_container(tcx) {
61            let ty = tcx.type_of(impl_id).skip_binder();
62            let type_name = ty.to_string();
63            let struct_name = type_name
64                .split('<')
65                .next()
66                .unwrap_or("")
67                .split("::")
68                .last()
69                .unwrap_or("")
70                .to_string();
71
72            return Some(struct_name);
73        }
74    None
75}
76
77/// The public path of a type (re-exports resolved: `alloc::rc::Rc`), with the
78/// crate prefix and generic args stripped.  `public_def_path` re-adds the crate.
79fn public_ty_path<'tcx>(ty: Ty<'tcx>) -> String {
80    // Disable "good path" trimming, which depends on the current crate's imports.
81    let full = with_no_trimmed_paths!(ty.to_string());
82    let base = full.split('<').next().unwrap_or(&full);
83    base.split("::").skip(1).collect::<Vec<_>>().join("::")
84}
85
86/// The canonical std JSON asset key for a `DefId`, prefixed by its defining
87/// crate.  Types resolve re-exports; inherent methods keep the `module::method`
88/// shape, except that the private `alloc::rcs` module (Rust 1.96+) is mapped
89/// back to the public `rc`/`sync`.
90pub fn public_def_path<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> String {
91    let defining_crate = tcx.crate_name(def_id.krate).to_string();
92    match tcx.def_kind(def_id) {
93        rustc_hir::def::DefKind::Struct
94        | rustc_hir::def::DefKind::Enum
95        | rustc_hir::def::DefKind::Union
96        | rustc_hir::def::DefKind::TyAlias => {
97            let path = public_ty_path(tcx.type_of(def_id).skip_binder());
98            if path.is_empty() {
99                defining_crate
100            } else {
101                format!("{defining_crate}::{path}")
102            }
103        }
104        rustc_hir::def::DefKind::AssocFn => {
105            let assoc_item = tcx.associated_item(def_id);
106            let name = assoc_item.name();
107            // Trait methods key by the trait; inherent methods by the self type.
108            if let Some(trait_item) = assoc_item.trait_item_def_id() {
109                let trait_path = get_cleaned_def_path_name(tcx, tcx.parent(trait_item));
110                format!("{trait_path}::{name}")
111            } else if let Some(impl_id) = assoc_item.impl_container(tcx) {
112                let self_ty = tcx.type_of(impl_id).skip_binder();
113                let def_path = get_cleaned_def_path_name(tcx, def_id);
114                // Map the private `alloc::rcs` module back to `rc`/`sync`.
115                if matches!(self_ty.kind(), TyKind::Adt(..)) && def_path.contains("::rcs::") {
116                    let type_path = public_ty_path(self_ty);
117                    let module = type_path.rsplit_once("::").map(|(m, _)| m).unwrap_or("");
118                    if module.is_empty() {
119                        def_path
120                    } else {
121                        format!("{defining_crate}::{module}::{name}")
122                    }
123                } else {
124                    def_path
125                }
126            } else {
127                get_cleaned_def_path_name(tcx, def_id)
128            }
129        }
130        _ => get_cleaned_def_path_name(tcx, def_id),
131    }
132}
133
134/// Return the resolved `self` type for a method whose `DefId` points to an
135/// associated item that lives inside an `impl` block returning an ADT, or for
136/// a struct/enum DefId directly (needed for parsing struct-invariant annotations).
137pub fn get_adt_self_ty<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Ty<'tcx>> {
138    if let Some(assoc_item) = tcx.opt_associated_item(def_id) {
139        let impl_id = assoc_item.impl_container(tcx)?;
140        let self_ty = tcx.type_of(impl_id).skip_binder();
141        if matches!(self_ty.kind(), TyKind::Adt(_, _)) {
142            return Some(self_ty);
143        }
144        return None;
145    }
146    if matches!(
147        tcx.def_kind(def_id),
148        rustc_hir::def::DefKind::Struct | rustc_hir::def::DefKind::Enum
149    ) {
150        let self_ty = tcx.type_of(def_id).skip_binder();
151        if matches!(self_ty.kind(), TyKind::Adt(_, _)) {
152            return Some(self_ty);
153        }
154    }
155    None
156}
157
158/// Parse argument names and types from a local function's HIR body.
159/// Recursively unwrap Ref/Paren patterns to find the inner binding identifier.
160/// Needed because `&self` / `&mut self` produce PatKind::Ref(PatKind::Binding(...)).
161fn extract_pat_ident(pat: &rustc_hir::Pat<'_>) -> Option<rustc_span::symbol::Ident> {
162    match &pat.kind {
163        rustc_hir::PatKind::Binding(_, _, ident, _) => Some(*ident),
164        rustc_hir::PatKind::Ref(inner, ..) => extract_pat_ident(inner),
165        _ => None,
166    }
167}
168
169fn parse_local_signature<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> (Vec<String>, Vec<Ty<'tcx>>) {
170    let Some(local_def_id) = def_id.as_local() else {
171        return (vec!["0".to_string()], Vec::new());
172    };
173    let hir_body = tcx.hir_body_owned_by(local_def_id);
174    if hir_body.params.is_empty() {
175        return (vec!["0".to_string()], Vec::new());
176    }
177
178    let params = hir_body.params;
179    let typeck_results = tcx.typeck_body(hir_body.id());
180    let mut param_names = Vec::new();
181    let mut param_tys = Vec::new();
182    for param in params {
183        let ident = extract_pat_ident(param.pat);
184        match ident {
185            Some(name) => {
186                param_names.push(name.name.to_string());
187            }
188            None => {
189                param_names.push(String::new());
190            }
191        }
192        param_tys.push(typeck_results.pat_ty(param.pat));
193    }
194    (param_names, param_tys)
195}
196
197/// Parse argument names and types from an external function's type signature.
198///
199/// Read parameter names from compiler metadata, falling back to numeric
200/// indices (`"0"`, `"1"`, …) when names are unavailable.
201fn parse_outside_signature<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> (Vec<String>, Vec<Ty<'tcx>>) {
202    let sig = tcx.fn_sig(def_id).skip_binder();
203    let param_tys: Vec<Ty<'tcx>> = sig.inputs().skip_binder().to_vec();
204    let idents = tcx.fn_arg_idents(def_id);
205    let args_name = if idents.len() == param_tys.len() && idents.iter().all(Option::is_some) {
206        idents.iter().map(|ident| ident.unwrap().name.to_string()).collect()
207    } else {
208        (0..param_tys.len()).map(|i| i.to_string()).collect()
209    };
210    (args_name, param_tys)
211}
212
213/// Extract parameter names from a HIR trait method declaration and pair them
214/// with types from the function signature.  Handles `TraitFn::Required` (names
215/// directly in the declaration) and `TraitFn::Provided` (names in the body).
216fn parse_trait_fn_sig<'tcx>(
217    tcx: TyCtxt<'tcx>,
218    def_id: DefId,
219) -> Option<(Vec<String>, Vec<Ty<'tcx>>)> {
220    let local_def_id = def_id.as_local()?;
221    if !matches!(tcx.def_kind(def_id), rustc_hir::def::DefKind::AssocFn) {
222        return None;
223    }
224    let trait_item_id = rustc_hir::TraitItemId {
225        owner_id: rustc_hir::OwnerId {
226            def_id: local_def_id,
227        },
228    };
229    let item = tcx.hir_trait_item(trait_item_id);
230    let (_sig, trait_fn) = match &item.kind {
231        rustc_hir::TraitItemKind::Fn(sig, tf) => (sig, tf),
232        _ => return None,
233    };
234    let names: Vec<String> = match trait_fn {
235        rustc_hir::TraitFn::Required(param_names) => param_names
236            .iter()
237            .filter_map(|opt| opt.map(|ident| ident.name.to_string()))
238            .collect(),
239        rustc_hir::TraitFn::Provided(body_id) => {
240            let body = tcx.hir_body(*body_id);
241            body.params
242                .iter()
243                .filter_map(|param| extract_pat_ident(param.pat).map(|i| i.name.to_string()))
244                .collect()
245        }
246    };
247    let sig = tcx.fn_sig(def_id).skip_binder();
248    let param_tys: Vec<Ty<'tcx>> = sig.inputs().skip_binder().to_vec();
249    if names.len() == param_tys.len() {
250        Some((names, param_tys))
251    } else {
252        None
253    }
254}
255
256/// Dispatch argument-name/type parsing to either the local HIR path or the
257/// external type-based path.
258pub fn parse_signature<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> (Vec<String>, Vec<Ty<'tcx>>) {
259    if def_id.as_local().is_some() && tcx.is_mir_available(def_id) {
260        parse_local_signature(tcx, def_id)
261    } else if def_id.is_local() {
262        if let Some((names, tys)) = parse_trait_fn_sig(tcx, def_id) {
263            return (names, tys);
264        }
265        if matches!(
266            tcx.def_kind(def_id),
267            rustc_hir::def::DefKind::Fn | rustc_hir::def::DefKind::AssocFn
268        ) {
269            parse_outside_signature(tcx, def_id)
270        } else {
271            (vec!["0".to_string()], Vec::new())
272        }
273    } else {
274        parse_outside_signature(tcx, def_id)
275    }
276}
277
278/// Walk a `syn::Expr` and produce the root identifier together with any
279/// field projections.
280///
281/// Examples:
282/// - `ptr`         → `("ptr", [])`
283/// - `region.size` → `("region", ["size"])`
284/// - `tuple.0.val` → `("tuple", ["0", "val"])`
285pub fn access_ident_recursive(expr: &Expr) -> Option<(String, Vec<String>)> {
286    match expr {
287        Expr::Path(syn::ExprPath { path, .. }) => {
288            if path.segments.len() == 1 {
289                rap_debug!("expr2 {:?}", expr);
290                let ident = path.segments[0].ident.to_string();
291                Some((ident, Vec::new()))
292            } else {
293                None
294            }
295        }
296        Expr::Field(syn::ExprField { base, member, .. }) => {
297            let (base_ident, mut fields) =
298                if let Some((base_ident, fields)) = access_ident_recursive(base) {
299                    (base_ident, fields)
300                } else {
301                    return None;
302                };
303            let field_name = match member {
304                syn::Member::Named(ident) => ident.to_string(),
305                syn::Member::Unnamed(index) => index.index.to_string(),
306            };
307            fields.push(field_name);
308            Some((base_ident, fields))
309        }
310        _ => None,
311    }
312}
313
314/// Match a type-identifier string to a concrete `Ty`.
315///
316/// Checks in order:
317/// 1. Primitive types (`u32`, `bool`, …)
318/// 2. Generic type parameters in the function signature or `self` type
319pub fn match_ty_with_ident<'tcx>(
320    tcx: TyCtxt<'tcx>,
321    def_id: DefId,
322    type_ident: String,
323) -> Option<Ty<'tcx>> {
324    if let Some(primitive_ty) = match_primitive_type(tcx, &type_ident) {
325        return Some(primitive_ty);
326    }
327    if let Some(std_ty) = match_std_type(tcx, &type_ident) {
328        return Some(std_ty);
329    }
330    if let Some(param_ty) = find_declared_generic_param(tcx, def_id, &type_ident) {
331        return Some(param_ty);
332    }
333    find_generic_param(tcx, def_id, &type_ident)
334}
335
336/// Match a short type name against std types resolved by name-scan (no
337/// lang/diagnostic item), e.g. `std::ascii::Char` (`AsciiChar`) whose `Char`
338/// short name otherwise collides with the primitive `char`.
339fn match_std_type<'tcx>(tcx: TyCtxt<'tcx>, type_ident: &str) -> Option<Ty<'tcx>> {
340    match type_ident {
341        "Char" | "AsciiChar" => {
342            let did = type_ids::def_ids_for_type(StdAdtType::AsciiChar).next()?;
343            let adt = tcx.adt_def(did);
344            Some(Ty::new_adt(
345                tcx,
346                adt,
347                rustc_middle::ty::GenericArgs::empty(),
348            ))
349        }
350        _ => None,
351    }
352}
353
354fn find_declared_generic_param<'tcx>(
355    tcx: TyCtxt<'tcx>,
356    def_id: DefId,
357    type_ident: &str,
358) -> Option<Ty<'tcx>> {
359    tcx.generics_of(def_id)
360        .own_params
361        .iter()
362        .find(|param| param.name.as_str() == type_ident)
363        .map(|param| {
364            tcx.mk_ty_from_kind(TyKind::Param(rustc_middle::ty::ParamTy {
365                index: param.index,
366                name: param.name,
367            }))
368        })
369}
370
371/// Match a string against Rust's primitive types, returning the
372/// corresponding `Ty` from the type context.
373fn match_primitive_type<'tcx>(tcx: TyCtxt<'tcx>, type_ident: &str) -> Option<Ty<'tcx>> {
374    match type_ident {
375        "i8" => Some(tcx.types.i8),
376        "i16" => Some(tcx.types.i16),
377        "i32" => Some(tcx.types.i32),
378        "i64" => Some(tcx.types.i64),
379        "i128" => Some(tcx.types.i128),
380        "isize" => Some(tcx.types.isize),
381        "u8" => Some(tcx.types.u8),
382        "u16" => Some(tcx.types.u16),
383        "u32" => Some(tcx.types.u32),
384        "u64" => Some(tcx.types.u64),
385        "u128" => Some(tcx.types.u128),
386        "usize" => Some(tcx.types.usize),
387        "f16" => Some(tcx.types.f16),
388        "f32" => Some(tcx.types.f32),
389        "f64" => Some(tcx.types.f64),
390        "f128" => Some(tcx.types.f128),
391        "bool" => Some(tcx.types.bool),
392        "char" => Some(tcx.types.char),
393        "str" => Some(tcx.types.str_),
394        _ => None,
395    }
396}
397
398/// Search function parameters (and the `self` type for methods) for a
399/// generic type whose name matches `type_ident`.
400fn find_generic_param<'tcx>(
401    tcx: TyCtxt<'tcx>,
402    def_id: DefId,
403    type_ident: &str,
404) -> Option<Ty<'tcx>> {
405    rap_debug!(
406        "Searching for generic param: {} in {:?}",
407        type_ident,
408        def_id
409    );
410    let (_, param_tys) = parse_signature(tcx, def_id);
411    rap_debug!("Function parameter types: {:?} of {:?}", param_tys, def_id);
412    for &ty in &param_tys {
413        if let Some(found) = find_generic_in_ty(tcx, ty, type_ident) {
414            return Some(found);
415        }
416    }
417
418    if let Some(struct_ty) = get_adt_self_ty(tcx, def_id)
419        && let Some(found) = find_generic_in_ty(tcx, struct_ty, type_ident) {
420            return Some(found);
421        }
422
423    // Search the return type as well, so generic types that only appear there
424    // (e.g. `NonZero<T>` / `Option<NonZero<T>>` in a generic fn) resolve to the
425    // concrete ADT instead of falling back to `never`.
426    let ret_ty = tcx.fn_sig(def_id).skip_binder().output().skip_binder();
427    if let Some(found) = find_generic_in_ty(tcx, ret_ty, type_ident) {
428        return Some(found);
429    }
430
431    None
432}
433
434/// Recursively walk a `Ty` tree looking for a type whose name matches
435/// `type_ident`.
436///
437/// This handles parameter types, pointers, references, slices, arrays,
438/// tuples, and ADT fields.
439fn find_generic_in_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, type_ident: &str) -> Option<Ty<'tcx>> {
440    match ty.kind() {
441        TyKind::Param(param_ty) => {
442            if param_ty.name.as_str() == type_ident {
443                return Some(ty);
444            }
445        }
446        TyKind::RawPtr(ty, _)
447        | TyKind::Ref(_, ty, _)
448        | TyKind::Slice(ty)
449        | TyKind::Array(ty, _) => {
450            if let Some(found) = find_generic_in_ty(tcx, *ty, type_ident) {
451                return Some(found);
452            }
453        }
454        TyKind::Tuple(tys) => {
455            for tuple_ty in tys.iter() {
456                if let Some(found) = find_generic_in_ty(tcx, tuple_ty, type_ident) {
457                    return Some(found);
458                }
459            }
460        }
461        TyKind::Adt(adt_def, substs) => {
462            let name = tcx.item_name(adt_def.did()).to_string();
463            if name == type_ident {
464                return Some(ty);
465            }
466            for field in adt_def.all_fields() {
467                let field_ty = mir_utils::field_ty(tcx, field, substs);
468                if let Some(found) = find_generic_in_ty(tcx, field_ty, type_ident) {
469                    return Some(found);
470                }
471            }
472            for subst in substs.iter() {
473                if let GenericArgKind::Type(subst_ty) = subst.kind()
474                    && let Some(found) = find_generic_in_ty(tcx, subst_ty, type_ident) {
475                        return Some(found);
476                    }
477            }
478        }
479        _ => {}
480    }
481    None
482}
483
484pub fn short_fn_name(tcx: TyCtxt<'_>, def_id: DefId) -> String {
485    let path = tcx.def_path_str(def_id);
486    path.rsplit("::").next().unwrap_or(&path).to_string()
487}
488
489pub fn resolve_field_name(tcx: TyCtxt<'_>, index: &usize, struct_def_id: Option<DefId>) -> String {
490    if let Some(struct_def_id) = struct_def_id
491        && let TyKind::Adt(adt_def, _) = tcx.type_of(struct_def_id).skip_binder().kind()
492    {
493        let variant = adt_def.non_enum_variant();
494        let field_idx = rustc_abi::FieldIdx::from_usize(*index);
495        if field_idx.as_usize() < variant.fields.len() {
496            return variant.fields[field_idx].name.to_string();
497        }
498    }
499    index.to_string()
500}