1use rustc_abi::FIRST_VARIANT;
2use rustc_data_structures::stack::ensure_sufficient_stack;
3use rustc_data_structures::unord::{UnordMap, UnordSet};
4use rustc_hir as hir;
5use rustc_hir::attrs::AttributeKind;
6use rustc_hir::def::DefKind;
7use rustc_hir::find_attr;
8use rustc_middle::query::Providers;
9use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt};
10use rustc_session::declare_lint;
11use rustc_span::{Span, Symbol};
12use tracing::{debug, instrument};
13
14use crate::lints::{BuiltinClashingExtern, BuiltinClashingExternSub};
15use crate::{LintVec, types};
16
17pub(crate) fn provide(providers: &mut Providers) {
18 *providers = Providers { clashing_extern_declarations, ..*providers };
19}
20
21pub(crate) fn get_lints() -> LintVec {
22 vec![CLASHING_EXTERN_DECLARATIONS]
23}
24
25fn clashing_extern_declarations(tcx: TyCtxt<'_>, (): ()) {
26 let mut lint = ClashingExternDeclarations::new();
27 for id in tcx.hir_crate_items(()).foreign_items() {
28 lint.check_foreign_item(tcx, id);
29 }
30}
31
32declare_lint! {
33 pub CLASHING_EXTERN_DECLARATIONS,
68 Warn,
69 "detects when an extern fn has been declared with the same name but different types"
70}
71
72struct ClashingExternDeclarations {
73 seen_decls: UnordMap<Symbol, hir::OwnerId>,
79}
80
81enum SymbolName {
86 Link(Symbol, Span),
88 Normal(Symbol),
90}
91
92impl SymbolName {
93 fn get_name(&self) -> Symbol {
94 match self {
95 SymbolName::Link(s, _) | SymbolName::Normal(s) => *s,
96 }
97 }
98}
99
100impl ClashingExternDeclarations {
101 pub(crate) fn new() -> Self {
102 ClashingExternDeclarations { seen_decls: Default::default() }
103 }
104
105 fn insert(&mut self, tcx: TyCtxt<'_>, fi: hir::ForeignItemId) -> Option<hir::OwnerId> {
108 let did = fi.owner_id.to_def_id();
109 let instance = Instance::new_raw(did, ty::List::identity_for_item(tcx, did));
110 let name = Symbol::intern(tcx.symbol_name(instance).name);
111 if let Some(&existing_id) = self.seen_decls.get(&name) {
112 Some(existing_id)
116 } else {
117 self.seen_decls.insert(name, fi.owner_id)
118 }
119 }
120
121 #[instrument(level = "trace", skip(self, tcx))]
122 fn check_foreign_item<'tcx>(&mut self, tcx: TyCtxt<'tcx>, this_fi: hir::ForeignItemId) {
123 let DefKind::Fn = tcx.def_kind(this_fi.owner_id) else { return };
124 let Some(existing_did) = self.insert(tcx, this_fi) else { return };
125
126 let existing_decl_ty = tcx.type_of(existing_did).skip_binder();
127 let this_decl_ty = tcx.type_of(this_fi.owner_id).instantiate_identity();
128 debug!(
129 "ClashingExternDeclarations: Comparing existing {:?}: {:?} to this {:?}: {:?}",
130 existing_did, existing_decl_ty, this_fi.owner_id, this_decl_ty
131 );
132
133 if !structurally_same_type(
135 tcx,
136 ty::TypingEnv::non_body_analysis(tcx, this_fi.owner_id),
137 existing_decl_ty,
138 this_decl_ty,
139 ) {
140 let orig = name_of_extern_decl(tcx, existing_did);
141
142 let this = tcx.item_name(this_fi.owner_id.to_def_id());
144 let orig = orig.get_name();
145 let previous_decl_label = get_relevant_span(tcx, existing_did);
146 let mismatch_label = get_relevant_span(tcx, this_fi.owner_id);
147 let sub =
148 BuiltinClashingExternSub { tcx, expected: existing_decl_ty, found: this_decl_ty };
149 let decorator = if orig == this {
150 BuiltinClashingExtern::SameName {
151 this,
152 orig,
153 previous_decl_label,
154 mismatch_label,
155 sub,
156 }
157 } else {
158 BuiltinClashingExtern::DiffName {
159 this,
160 orig,
161 previous_decl_label,
162 mismatch_label,
163 sub,
164 }
165 };
166 tcx.emit_node_span_lint(
167 CLASHING_EXTERN_DECLARATIONS,
168 this_fi.hir_id(),
169 mismatch_label,
170 decorator,
171 );
172 }
173 }
174}
175
176fn name_of_extern_decl(tcx: TyCtxt<'_>, fi: hir::OwnerId) -> SymbolName {
180 if let Some((overridden_link_name, overridden_link_name_span)) =
181 tcx.codegen_fn_attrs(fi).symbol_name.map(|overridden_link_name| {
182 (
187 overridden_link_name,
188 find_attr!(tcx.get_all_attrs(fi), AttributeKind::LinkName {span, ..} => *span)
189 .unwrap(),
190 )
191 })
192 {
193 SymbolName::Link(overridden_link_name, overridden_link_name_span)
194 } else {
195 SymbolName::Normal(tcx.item_name(fi.to_def_id()))
196 }
197}
198
199fn get_relevant_span(tcx: TyCtxt<'_>, fi: hir::OwnerId) -> Span {
202 match name_of_extern_decl(tcx, fi) {
203 SymbolName::Normal(_) => tcx.def_span(fi),
204 SymbolName::Link(_, annot_span) => annot_span,
205 }
206}
207
208fn structurally_same_type<'tcx>(
212 tcx: TyCtxt<'tcx>,
213 typing_env: ty::TypingEnv<'tcx>,
214 a: Ty<'tcx>,
215 b: Ty<'tcx>,
216) -> bool {
217 let mut seen_types = UnordSet::default();
218 let result = structurally_same_type_impl(&mut seen_types, tcx, typing_env, a, b);
219 if cfg!(debug_assertions) && result {
220 let a_layout = tcx.layout_of(typing_env.as_query_input(a)).unwrap();
223 let b_layout = tcx.layout_of(typing_env.as_query_input(b)).unwrap();
224 assert_eq!(a_layout.backend_repr, b_layout.backend_repr);
225 assert_eq!(a_layout.size, b_layout.size);
226 assert_eq!(a_layout.align, b_layout.align);
227 }
228 result
229}
230
231fn structurally_same_type_impl<'tcx>(
232 seen_types: &mut UnordSet<(Ty<'tcx>, Ty<'tcx>)>,
233 tcx: TyCtxt<'tcx>,
234 typing_env: ty::TypingEnv<'tcx>,
235 a: Ty<'tcx>,
236 b: Ty<'tcx>,
237) -> bool {
238 debug!("structurally_same_type_impl(tcx, a = {:?}, b = {:?})", a, b);
239
240 let non_transparent_ty = |mut ty: Ty<'tcx>| -> Ty<'tcx> {
243 loop {
244 if let ty::Adt(def, args) = *ty.kind() {
245 let is_transparent = def.repr().transparent();
246 let is_non_null = types::nonnull_optimization_guaranteed(tcx, def);
247 debug!(?ty, is_transparent, is_non_null);
248 if is_transparent && !is_non_null {
249 debug_assert_eq!(def.variants().len(), 1);
250 let v = &def.variant(FIRST_VARIANT);
251 if let Some(field) = types::transparent_newtype_field(tcx, v) {
254 ty = field.ty(tcx, args);
255 continue;
256 }
257 }
258 }
259 debug!("non_transparent_ty -> {:?}", ty);
260 return ty;
261 }
262 };
263
264 let a = non_transparent_ty(a);
265 let b = non_transparent_ty(b);
266
267 if !seen_types.insert((a, b)) {
268 true
271 } else if a == b {
272 true
274 } else {
275 let is_primitive_or_pointer =
277 |ty: Ty<'tcx>| ty.is_primitive() || matches!(ty.kind(), ty::RawPtr(..) | ty::Ref(..));
278
279 ensure_sufficient_stack(|| {
280 match (a.kind(), b.kind()) {
281 (&ty::Adt(a_def, a_gen_args), &ty::Adt(b_def, b_gen_args)) => {
282 if !(a_def.repr().c() && b_def.repr().c()) {
284 return false;
285 }
286 let repr_characteristica =
288 |def: AdtDef<'tcx>| (def.repr().pack, def.repr().align, def.repr().simd());
289 if repr_characteristica(a_def) != repr_characteristica(b_def) {
290 return false;
291 }
292
293 let a_fields = a_def.variants().iter().flat_map(|v| v.fields.iter());
295 let b_fields = b_def.variants().iter().flat_map(|v| v.fields.iter());
296
297 a_fields.eq_by(
299 b_fields,
300 |&ty::FieldDef { did: a_did, .. }, &ty::FieldDef { did: b_did, .. }| {
301 structurally_same_type_impl(
302 seen_types,
303 tcx,
304 typing_env,
305 tcx.type_of(a_did).instantiate(tcx, a_gen_args),
306 tcx.type_of(b_did).instantiate(tcx, b_gen_args),
307 )
308 },
309 )
310 }
311 (ty::Array(a_ty, a_len), ty::Array(b_ty, b_len)) => {
312 a_len == b_len
314 && structurally_same_type_impl(seen_types, tcx, typing_env, *a_ty, *b_ty)
315 }
316 (ty::Slice(a_ty), ty::Slice(b_ty)) => {
317 structurally_same_type_impl(seen_types, tcx, typing_env, *a_ty, *b_ty)
318 }
319 (ty::RawPtr(a_ty, a_mutbl), ty::RawPtr(b_ty, b_mutbl)) => {
320 a_mutbl == b_mutbl
321 && structurally_same_type_impl(seen_types, tcx, typing_env, *a_ty, *b_ty)
322 }
323 (ty::Ref(_a_region, a_ty, a_mut), ty::Ref(_b_region, b_ty, b_mut)) => {
324 a_mut == b_mut
326 && structurally_same_type_impl(seen_types, tcx, typing_env, *a_ty, *b_ty)
327 }
328 (ty::FnDef(..), ty::FnDef(..)) => {
329 let a_poly_sig = a.fn_sig(tcx);
330 let b_poly_sig = b.fn_sig(tcx);
331
332 let a_sig = tcx.instantiate_bound_regions_with_erased(a_poly_sig);
335 let b_sig = tcx.instantiate_bound_regions_with_erased(b_poly_sig);
336
337 (a_sig.abi, a_sig.safety, a_sig.c_variadic)
338 == (b_sig.abi, b_sig.safety, b_sig.c_variadic)
339 && a_sig.inputs().iter().eq_by(b_sig.inputs().iter(), |a, b| {
340 structurally_same_type_impl(seen_types, tcx, typing_env, *a, *b)
341 })
342 && structurally_same_type_impl(
343 seen_types,
344 tcx,
345 typing_env,
346 a_sig.output(),
347 b_sig.output(),
348 )
349 }
350 (ty::Tuple(..), ty::Tuple(..)) => {
351 false
353 }
354 (ty::Dynamic(..), ty::Dynamic(..))
358 | (ty::Error(..), ty::Error(..))
359 | (ty::Closure(..), ty::Closure(..))
360 | (ty::Coroutine(..), ty::Coroutine(..))
361 | (ty::CoroutineWitness(..), ty::CoroutineWitness(..))
362 | (ty::Alias(ty::Projection, ..), ty::Alias(ty::Projection, ..))
363 | (ty::Alias(ty::Inherent, ..), ty::Alias(ty::Inherent, ..))
364 | (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => false,
365
366 (ty::Bool, ty::Bool)
368 | (ty::Char, ty::Char)
369 | (ty::Never, ty::Never)
370 | (ty::Str, ty::Str) => unreachable!(),
371
372 (ty::Adt(..) | ty::Pat(..), _) if is_primitive_or_pointer(b) => {
375 if let Some(a_inner) = types::repr_nullable_ptr(tcx, typing_env, a) {
376 a_inner == b
377 } else {
378 false
379 }
380 }
381 (_, ty::Adt(..) | ty::Pat(..)) if is_primitive_or_pointer(a) => {
382 if let Some(b_inner) = types::repr_nullable_ptr(tcx, typing_env, b) {
383 b_inner == a
384 } else {
385 false
386 }
387 }
388
389 _ => false,
390 }
391 })
392 }
393}