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
7pub 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 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
56fn 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
77fn public_ty_path<'tcx>(ty: Ty<'tcx>) -> String {
80 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
86pub 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 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 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
134pub 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
158fn 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
197fn 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
213fn 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
256pub 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
278pub 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
314pub 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
336fn 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
371fn 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
398fn 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 ¶m_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 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
434fn 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}