1use std::iter;
2use std::ops::ControlFlow;
34use bitflags::bitflags;
5use rustc_abi::VariantIdx;
6use rustc_data_structures::fx::FxHashSet;
7use rustc_errors::{DiagMessage, msg};
8use rustc_hir::def::CtorKind;
9use rustc_hir::intravisit::Visitor;
10use rustc_hir::{selfas hir, AmbigArg};
11use rustc_lint_defs::{declare_lint, declare_lint_pass};
12use rustc_middle::ty::{
13self, Adt, AdtDef, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable,
14TypeVisitableExt, Unnormalized,
15};
16use rustc_span::def_id::LocalDefId;
17use rustc_span::{Span, bug, sym};
18use rustc_target::spec::Os;
19use tracing::debug;
2021use super::repr_nullable_ptr;
22use crate::diagnostics::{ImproperCTypes, UsesPowerAlignment};
23use crate::{LateContext, LateLintPass, LintContext};
2425#[doc =
r" The `improper_ctypes` lint detects incorrect use of types in foreign"]
#[doc = r" modules."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r#" unsafe extern "C" {"#]
#[doc = r" static STATIC: String;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The compiler has several checks to verify that types used in `extern`"]
#[doc = r" blocks are safe and follow certain rules to ensure proper"]
#[doc =
r" compatibility with the foreign interfaces. This lint is issued when it"]
#[doc =
r" detects a probable mistake in a definition. The lint usually should"]
#[doc =
r" provide a description of the issue, along with possibly a hint on how"]
#[doc = r" to resolve it."]
static IMPROPER_CTYPES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "IMPROPER_CTYPES",
default_level: ::rustc_lint_defs::Warn,
desc: "proper use of libc types in foreign modules",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
26/// The `improper_ctypes` lint detects incorrect use of types in foreign
27 /// modules.
28 ///
29 /// ### Example
30 ///
31 /// ```rust
32 /// unsafe extern "C" {
33 /// static STATIC: String;
34 /// }
35 /// ```
36 ///
37 /// {{produces}}
38 ///
39 /// ### Explanation
40 ///
41 /// The compiler has several checks to verify that types used in `extern`
42 /// blocks are safe and follow certain rules to ensure proper
43 /// compatibility with the foreign interfaces. This lint is issued when it
44 /// detects a probable mistake in a definition. The lint usually should
45 /// provide a description of the issue, along with possibly a hint on how
46 /// to resolve it.
47IMPROPER_CTYPES,
48 Warn,
49"proper use of libc types in foreign modules"
50}5152#[doc = r" The `improper_ctypes_definitions` lint detects incorrect use of"]
#[doc = r" [`extern` function] definitions."]
#[doc = r""]
#[doc =
r" [`extern` function]: https://doc.rust-lang.org/reference/items/functions.html#extern-function-qualifier"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" # #![allow(unused)]"]
#[doc = r#" pub extern "C" fn str_type(p: &str) { }"#]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" There are many parameter and return types that may be specified in an"]
#[doc =
r" `extern` function that are not compatible with the given ABI. This"]
#[doc =
r" lint is an alert that these types should not be used. The lint usually"]
#[doc =
r" should provide a description of the issue, along with possibly a hint"]
#[doc = r" on how to resolve it."]
static IMPROPER_CTYPES_DEFINITIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "IMPROPER_CTYPES_DEFINITIONS",
default_level: ::rustc_lint_defs::Warn,
desc: "proper use of libc types in foreign item definitions",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
53/// The `improper_ctypes_definitions` lint detects incorrect use of
54 /// [`extern` function] definitions.
55 ///
56 /// [`extern` function]: https://doc.rust-lang.org/reference/items/functions.html#extern-function-qualifier
57 ///
58 /// ### Example
59 ///
60 /// ```rust
61 /// # #![allow(unused)]
62 /// pub extern "C" fn str_type(p: &str) { }
63 /// ```
64 ///
65 /// {{produces}}
66 ///
67 /// ### Explanation
68 ///
69 /// There are many parameter and return types that may be specified in an
70 /// `extern` function that are not compatible with the given ABI. This
71 /// lint is an alert that these types should not be used. The lint usually
72 /// should provide a description of the issue, along with possibly a hint
73 /// on how to resolve it.
74IMPROPER_CTYPES_DEFINITIONS,
75 Warn,
76"proper use of libc types in foreign item definitions"
77}7879#[doc = r" The `uses_power_alignment` lint detects specific `repr(C)`"]
#[doc = r" aggregates on AIX."]
#[doc =
r#" In its platform C ABI, AIX uses the "power" (as in PowerPC) alignment"#]
#[doc =
r" rule (detailed in https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=data-using-alignment-modes#alignment),"]
#[doc = r" which can also be set for XLC by `#pragma align(power)` or"]
#[doc = r" `-qalign=power`. Aggregates with a floating-point type as the"]
#[doc =
r#" recursively first field (as in "at offset 0") modify the layout of"#]
#[doc =
r" *subsequent* fields of the associated structs to use an alignment value"]
#[doc = r" where the floating-point type is aligned on a 4-byte boundary."]
#[doc = r""]
#[doc =
r" Effectively, subsequent floating-point fields act as-if they are `repr(packed(4))`. This"]
#[doc =
r" would be unsound to do in a `repr(C)` type without all the restrictions that come with"]
#[doc =
r" `repr(packed)`. Rust instead chooses a layout that maintains soundness of Rust code, at the"]
#[doc = r" expense of incompatibility with C code."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,ignore (fails on non-powerpc64-ibm-aix)"]
#[doc = r" #[repr(C)]"]
#[doc = r" pub struct Floats {"]
#[doc = r" a: f64,"]
#[doc = r" b: u8,"]
#[doc = r" c: f64,"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This will produce:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc =
r" warning: repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type"]
#[doc = r" --> <source>:5:3"]
#[doc = r" |"]
#[doc = r" 5 | c: f64,"]
#[doc = r" | ^^^^^^"]
#[doc = r" |"]
#[doc = r" = note: `#[warn(uses_power_alignment)]` on by default"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The power alignment rule specifies that the above struct has the"]
#[doc = r" following alignment:"]
#[doc = r" - offset_of!(Floats, a) == 0"]
#[doc = r" - offset_of!(Floats, b) == 8"]
#[doc = r" - offset_of!(Floats, c) == 12"]
#[doc = r""]
#[doc =
r" However, Rust currently aligns `c` at `offset_of!(Floats, c) == 16`."]
#[doc =
r" Using offset 12 would be unsound since `f64` generally must be 8-aligned on this target."]
#[doc = r" Thus, a warning is produced for the above struct."]
static USES_POWER_ALIGNMENT: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "USES_POWER_ALIGNMENT",
default_level: ::rustc_lint_defs::Warn,
desc: "Structs do not follow the power alignment rule under repr(C)",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
80/// The `uses_power_alignment` lint detects specific `repr(C)`
81 /// aggregates on AIX.
82 /// In its platform C ABI, AIX uses the "power" (as in PowerPC) alignment
83 /// rule (detailed in https://www.ibm.com/docs/en/xl-c-and-cpp-aix/16.1?topic=data-using-alignment-modes#alignment),
84 /// which can also be set for XLC by `#pragma align(power)` or
85 /// `-qalign=power`. Aggregates with a floating-point type as the
86 /// recursively first field (as in "at offset 0") modify the layout of
87 /// *subsequent* fields of the associated structs to use an alignment value
88 /// where the floating-point type is aligned on a 4-byte boundary.
89 ///
90 /// Effectively, subsequent floating-point fields act as-if they are `repr(packed(4))`. This
91 /// would be unsound to do in a `repr(C)` type without all the restrictions that come with
92 /// `repr(packed)`. Rust instead chooses a layout that maintains soundness of Rust code, at the
93 /// expense of incompatibility with C code.
94 ///
95 /// ### Example
96 ///
97 /// ```rust,ignore (fails on non-powerpc64-ibm-aix)
98 /// #[repr(C)]
99 /// pub struct Floats {
100 /// a: f64,
101 /// b: u8,
102 /// c: f64,
103 /// }
104 /// ```
105 ///
106 /// This will produce:
107 ///
108 /// ```text
109 /// warning: repr(C) does not follow the power alignment rule. This may affect platform C ABI compatibility for this type
110 /// --> <source>:5:3
111 /// |
112 /// 5 | c: f64,
113 /// | ^^^^^^
114 /// |
115 /// = note: `#[warn(uses_power_alignment)]` on by default
116 /// ```
117 ///
118 /// ### Explanation
119 ///
120 /// The power alignment rule specifies that the above struct has the
121 /// following alignment:
122 /// - offset_of!(Floats, a) == 0
123 /// - offset_of!(Floats, b) == 8
124 /// - offset_of!(Floats, c) == 12
125 ///
126 /// However, Rust currently aligns `c` at `offset_of!(Floats, c) == 16`.
127 /// Using offset 12 would be unsound since `f64` generally must be 8-aligned on this target.
128 /// Thus, a warning is produced for the above struct.
129USES_POWER_ALIGNMENT,
130 Warn,
131"Structs do not follow the power alignment rule under repr(C)"
132}133134pub struct ImproperCTypesLint;
#[automatically_derived]
impl ::core::marker::Copy for ImproperCTypesLint { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ImproperCTypesLint { }
#[automatically_derived]
impl ::core::clone::Clone for ImproperCTypesLint {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for ImproperCTypesLint {
fn name(&self) -> &'static str { "ImproperCTypesLint" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPROPER_CTYPES, IMPROPER_CTYPES_DEFINITIONS,
USES_POWER_ALIGNMENT]))
}
}
impl ImproperCTypesLint {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[IMPROPER_CTYPES, IMPROPER_CTYPES_DEFINITIONS,
USES_POWER_ALIGNMENT]))
}
}declare_lint_pass!(ImproperCTypesLint => [
135 IMPROPER_CTYPES,
136 IMPROPER_CTYPES_DEFINITIONS,
137 USES_POWER_ALIGNMENT
138]);
139140/// A common pattern in this lint is to attempt normalize_erasing_regions,
141/// but keep the original type if it were to fail.
142/// This may or may not be supported in the logic behind the `Unnormalized` wrapper,
143/// (FIXME?)
144/// but it should be enough for non-wrapped types to be as normalised as this lint needs them to be.
145fn maybe_normalize_erasing_regions<'tcx>(
146 cx: &LateContext<'tcx>,
147 value: Unnormalized<'tcx, Ty<'tcx>>,
148) -> Ty<'tcx> {
149// Use `TypingMode::Borrowck` so the new solver doesn't reveal opaque types since we're now
150 // past hir typeck. If we were to attempt to reveal more opaque types, dropping the
151 // `InferCtxt` would ICE (see #156352).
152let typing_env = if let Some(body_id) = cx.enclosing_body {
153let body_def_id = cx.tcx.hir_enclosing_body_owner(body_id.hir_id);
154 ty::TypingEnv::new(cx.param_env, ty::TypingMode::borrowck(cx.tcx, body_def_id))
155 } else {
156cx.typing_env()
157 };
158cx.tcx.try_normalize_erasing_regions(typing_env, value).unwrap_or(value.skip_norm_wip())
159}
160161/// Check a variant of a non-exhaustive enum for improper ctypes
162///
163/// We treat `#[non_exhaustive] enum` as "ensure that code will compile if new variants are added".
164/// This includes linting, on a best-effort basis. There are valid additions that are unlikely.
165///
166/// Adding a data-carrying variant to an existing C-like enum that is passed to C is "unlikely",
167/// so we don't need the lint to account for it.
168/// e.g. going from enum Foo { A, B, C } to enum Foo { A, B, C, D(u32) }.
169pub(crate) fn check_non_exhaustive_variant(
170 non_exhaustive_variant_list: bool,
171 variant: &ty::VariantDef,
172) -> ControlFlow<DiagMessage, ()> {
173// non_exhaustive suggests it is possible that someone might break ABI
174 // see: https://github.com/rust-lang/rust/issues/44109#issuecomment-537583344
175 // so warn on complex enums being used outside their crate
176if non_exhaustive_variant_list {
177// which is why we only warn about really_tagged_union reprs from https://rust.tf/rfc2195
178 // with an enum like `#[repr(u8)] enum Enum { A(DataA), B(DataB), }`
179 // but exempt enums with unit ctors like C's (e.g. from rust-bindgen)
180if variant_has_complex_ctor(variant) {
181return ControlFlow::Break(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this enum is non-exhaustive"))msg!("this enum is non-exhaustive"));
182 }
183 }
184185if variant.field_list_has_applicable_non_exhaustive() {
186return ControlFlow::Break(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this enum has non-exhaustive variants"))msg!("this enum has non-exhaustive variants"));
187 }
188189 ControlFlow::Continue(())
190}
191192fn variant_has_complex_ctor(variant: &ty::VariantDef) -> bool {
193// CtorKind::Const means a "unit" ctor
194 !#[allow(non_exhaustive_omitted_patterns)] match variant.ctor_kind() {
Some(CtorKind::Const) => true,
_ => false,
}matches!(variant.ctor_kind(), Some(CtorKind::Const))195}
196197/// Per-struct-field function that checks if a struct definition follows
198/// the Power alignment Rule (see the `check_struct_for_power_alignment` function).
199fn check_arg_for_power_alignment<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
200let tcx = cx.tcx;
201if !(tcx.sess.target.os == Os::Aix) {
::core::panicking::panic("assertion failed: tcx.sess.target.os == Os::Aix")
};assert!(tcx.sess.target.os == Os::Aix);
202203// Structs (under repr(C)) follow the power alignment rule if:
204 // - the first field of the struct is a floating-point type that
205 // is greater than 4-bytes, or
206 // - the first field of the struct is an aggregate whose
207 // recursively first field is a floating-point type greater than
208 // 4 bytes.
209if ty.is_floating_point() && ty.primitive_size(tcx).bytes() > 4 {
210return true;
211 } else if let Adt(adt_def, _) = ty.kind()
212 && adt_def.is_struct()
213 && adt_def.repr().c()
214 && !adt_def.repr().packed()
215 && adt_def.repr().align.is_none()
216 {
217let struct_variant = adt_def.variant(VariantIdx::ZERO);
218// Within a nested struct, all fields are examined to correctly
219 // report if any fields after the nested struct within the
220 // original struct are misaligned.
221for struct_field in &struct_variant.fields {
222let field_ty = tcx.type_of(struct_field.did).instantiate_identity().skip_norm_wip();
223if check_arg_for_power_alignment(cx, field_ty) {
224return true;
225 }
226 }
227 }
228return false;
229}
230231/// Check a struct definition for respect of the Power alignment Rule (as in PowerPC),
232/// which should be respected in the "aix" target OS.
233/// To do so, we must follow one of the two following conditions:
234/// - The first field of the struct must be floating-point type that
235/// is greater than 4-bytes.
236/// - The first field of the struct must be an aggregate whose
237/// recursively first field is a floating-point type greater than
238/// 4 bytes.
239fn check_struct_for_power_alignment<'tcx>(
240 cx: &LateContext<'tcx>,
241 item: &'tcx hir::Item<'tcx>,
242 adt_def: AdtDef<'tcx>,
243) {
244let tcx = cx.tcx;
245246// Only consider structs (not enums or unions) on AIX.
247if tcx.sess.target.os != Os::Aix || !adt_def.is_struct() {
248return;
249 }
250251// The struct must be repr(C), but ignore it if it explicitly specifies its alignment with
252 // either `align(N)` or `packed(N)`.
253if adt_def.repr().c() && !adt_def.repr().packed() && adt_def.repr().align.is_none() {
254let struct_variant_data = item.expect_struct().2;
255for field_def in struct_variant_data.fields().iter().skip(1) {
256// Struct fields (after the first field) are checked for the
257 // power alignment rule, as fields after the first are likely
258 // to be the fields that are misaligned.
259let ty = tcx.type_of(field_def.def_id).instantiate_identity().skip_norm_wip();
260if check_arg_for_power_alignment(cx, ty) {
261 cx.emit_span_lint(USES_POWER_ALIGNMENT, field_def.span, UsesPowerAlignment);
262 }
263 }
264 }
265}
266267/// Annotates whether we are in the context of an item *defined* in rust
268/// and exposed to an FFI boundary,
269/// or the context of an item from elsewhere, whose interface is re-*declared* in rust.
270#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for CItemKind { }
#[automatically_derived]
impl ::core::clone::Clone for CItemKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for CItemKind { }Copy)]
271enum CItemKind {
272 Declaration,
273 Definition,
274}
275276/// Annotates whether we are in the context of a function's argument types or return type.
277#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FnPos { }
#[automatically_derived]
impl ::core::clone::Clone for FnPos {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for FnPos { }Copy)]
278enum FnPos {
279 Arg,
280 Ret,
281}
282283enum FfiResult<'tcx> {
284 FfiSafe,
285 FfiPhantom(Ty<'tcx>),
286 FfiUnsafe { ty: Ty<'tcx>, reason: DiagMessage, help: Option<DiagMessage> },
287}
288289/// The result when a type has been checked but perhaps not completely. `None` indicates that
290/// FFI safety/unsafety has not yet been determined, `Some(res)` indicates that the safety/unsafety
291/// in the `FfiResult` is final.
292type PartialFfiResult<'tcx> = Option<FfiResult<'tcx>>;
293294/// What type indirection points to a given type.
295#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IndirectionKind { }
#[automatically_derived]
impl ::core::clone::Clone for IndirectionKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for IndirectionKind { }Copy)]
296enum IndirectionKind {
297/// Box (valid non-null pointer, owns pointee).
298Box,
299/// Ref (valid non-null pointer, borrows pointee).
300Ref,
301/// Raw pointer (not necessarily non-null or valid. no info on ownership).
302RawPtr,
303}
304305#[doc = r" VisitorState flags that are linked with the root type's use."]
#[doc =
r" (These are the permanent part of the state, kept when visiting new Ty.)"]
struct RootUseFlags(<RootUseFlags as
::bitflags::__private::PublicFlags>::Internal);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for RootUseFlags { }
#[automatically_derived]
impl ::core::clone::Clone for RootUseFlags {
#[inline]
fn clone(&self) -> Self {
let _:
::core::clone::AssertParamIsClone<<RootUseFlags as
::bitflags::__private::PublicFlags>::Internal>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for RootUseFlags { }
#[automatically_derived]
impl ::core::fmt::Debug for RootUseFlags {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_tuple_field1_finish(f, "RootUseFlags",
&&self.0)
}
}
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for RootUseFlags { }
#[automatically_derived]
impl ::core::cmp::PartialEq for RootUseFlags {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for RootUseFlags {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _:
::core::cmp::AssertParamIsEq<<RootUseFlags as
::bitflags::__private::PublicFlags>::Internal>;
}
}
impl RootUseFlags {
#[doc = r" For use in (externally-linked) static variables."]
#[allow(deprecated, non_upper_case_globals,)]
pub const STATIC: Self = Self::from_bits_retain(0b000001);
#[doc = r" For use in functions in general."]
#[allow(deprecated, non_upper_case_globals,)]
pub const FUNC: Self = Self::from_bits_retain(0b000010);
#[doc =
r" For variables in function returns (implicitly: not for static variables)."]
#[allow(deprecated, non_upper_case_globals,)]
pub const FN_RETURN: Self = Self::from_bits_retain(0b000100);
#[doc =
r" For variables in functions/variables which are defined in rust."]
#[allow(deprecated, non_upper_case_globals,)]
pub const DEFINED: Self = Self::from_bits_retain(0b001000);
#[doc = r" For times where we are only defining the type of something"]
#[doc = r" (struct/enum/union definitions, FnPtrs)."]
#[allow(deprecated, non_upper_case_globals,)]
pub const THEORETICAL: Self = Self::from_bits_retain(0b010000);
}
impl ::bitflags::Flags for RootUseFlags {
const FLAGS: &'static [::bitflags::Flag<RootUseFlags>] =
&[{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("STATIC", RootUseFlags::STATIC)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("FUNC", RootUseFlags::FUNC)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("FN_RETURN", RootUseFlags::FN_RETURN)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("DEFINED", RootUseFlags::DEFINED)
},
{
#[allow(deprecated, non_upper_case_globals,)]
::bitflags::Flag::new("THEORETICAL",
RootUseFlags::THEORETICAL)
}];
type Bits = u8;
fn bits(&self) -> u8 { RootUseFlags::bits(self) }
fn from_bits_retain(bits: u8) -> RootUseFlags {
RootUseFlags::from_bits_retain(bits)
}
}
#[allow(dead_code, deprecated, unused_doc_comments, unused_attributes,
unused_mut, unused_imports, non_upper_case_globals, clippy ::
assign_op_pattern, clippy :: indexing_slicing, clippy :: same_name_method,
clippy :: iter_without_into_iter,)]
const _: () =
{
#[repr(transparent)]
struct InternalBitFlags(u8);
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalBitFlags { }
#[automatically_derived]
impl ::core::clone::Clone for InternalBitFlags {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}
#[automatically_derived]
impl ::core::marker::Copy for InternalBitFlags { }
#[automatically_derived]
impl ::core::marker::StructuralPartialEq for InternalBitFlags { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InternalBitFlags {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}
#[automatically_derived]
impl ::core::cmp::Eq for InternalBitFlags {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}
#[automatically_derived]
impl ::core::cmp::PartialOrd for InternalBitFlags {
#[inline]
fn partial_cmp(&self, other: &Self)
-> ::core::option::Option<::core::cmp::Ordering> {
::core::option::Option::Some(::core::cmp::Ord::cmp(self,
other))
}
}
#[automatically_derived]
impl ::core::cmp::Ord for InternalBitFlags {
#[inline]
fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
::core::cmp::Ord::cmp(&self.0, &other.0)
}
}
#[automatically_derived]
impl ::core::hash::Hash for InternalBitFlags {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&self.0, state)
}
}
impl ::bitflags::__private::PublicFlags for RootUseFlags {
type Primitive = u8;
type Internal = InternalBitFlags;
}
impl ::bitflags::__private::core::default::Default for
InternalBitFlags {
#[inline]
fn default() -> Self { InternalBitFlags::empty() }
}
impl ::bitflags::__private::core::fmt::Debug for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
if self.is_empty() {
f.write_fmt(format_args!("{0:#x}",
<u8 as ::bitflags::Bits>::EMPTY))
} else {
::bitflags::__private::core::fmt::Display::fmt(self, f)
}
}
}
impl ::bitflags::__private::core::fmt::Display for InternalBitFlags {
fn fmt(&self,
f: &mut ::bitflags::__private::core::fmt::Formatter<'_>)
-> ::bitflags::__private::core::fmt::Result {
::bitflags::parser::to_writer(&RootUseFlags(*self), f)
}
}
impl ::bitflags::__private::core::str::FromStr for InternalBitFlags {
type Err = ::bitflags::parser::ParseError;
fn from_str(s: &str)
->
::bitflags::__private::core::result::Result<Self,
Self::Err> {
::bitflags::parser::from_str::<RootUseFlags>(s).map(|flags|
flags.0)
}
}
impl ::bitflags::__private::core::convert::AsRef<u8> for
InternalBitFlags {
fn as_ref(&self) -> &u8 { &self.0 }
}
impl ::bitflags::__private::core::convert::From<u8> for
InternalBitFlags {
fn from(bits: u8) -> Self { Self::from_bits_retain(bits) }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl InternalBitFlags {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self {
Self(<u8 as ::bitflags::Bits>::EMPTY)
}
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self {
let mut truncated = <u8 as ::bitflags::Bits>::EMPTY;
let mut i = 0;
{
{
let flag =
<RootUseFlags as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<RootUseFlags as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<RootUseFlags as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<RootUseFlags as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
{
{
let flag =
<RootUseFlags as
::bitflags::Flags>::FLAGS[i].value().bits();
truncated = truncated | flag;
i += 1;
}
};
let _ = i;
Self(truncated)
}
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0 }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
let truncated = Self::from_bits_truncate(bits).0;
if truncated == bits {
::bitflags::__private::core::option::Option::Some(Self(bits))
} else { ::bitflags::__private::core::option::Option::None }
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(bits & Self::all().0)
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self { Self(bits) }
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
{
if name == "STATIC" {
return ::bitflags::__private::core::option::Option::Some(Self(RootUseFlags::STATIC.bits()));
}
};
;
{
if name == "FUNC" {
return ::bitflags::__private::core::option::Option::Some(Self(RootUseFlags::FUNC.bits()));
}
};
;
{
if name == "FN_RETURN" {
return ::bitflags::__private::core::option::Option::Some(Self(RootUseFlags::FN_RETURN.bits()));
}
};
;
{
if name == "DEFINED" {
return ::bitflags::__private::core::option::Option::Some(Self(RootUseFlags::DEFINED.bits()));
}
};
;
{
if name == "THEORETICAL" {
return ::bitflags::__private::core::option::Option::Some(Self(RootUseFlags::THEORETICAL.bits()));
}
};
;
let _ = name;
::bitflags::__private::core::option::Option::None
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool {
self.0 == <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool {
Self::all().0 | self.0 == self.0
}
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0 & other.0 != <u8 as ::bitflags::Bits>::EMPTY
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0 & other.0 == other.0
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) {
*self = Self(self.0).union(other);
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) {
*self = Self(self.0).difference(other);
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) {
*self = Self(self.0).symmetric_difference(other);
}
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
if value { self.insert(other); } else { self.remove(other); }
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0 & other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0 & !other.0)
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0 ^ other.0)
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self::from_bits_truncate(!self.0)
}
}
impl ::bitflags::__private::core::fmt::Binary for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for InternalBitFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for InternalBitFlags {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: InternalBitFlags) -> Self {
self.union(other)
}
}
impl ::bitflags::__private::core::ops::BitOrAssign for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for InternalBitFlags {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for
InternalBitFlags {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for InternalBitFlags {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for
InternalBitFlags {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for InternalBitFlags {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for InternalBitFlags
{
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for InternalBitFlags {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<InternalBitFlags> for
InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<InternalBitFlags>
for InternalBitFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl InternalBitFlags {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<RootUseFlags> {
::bitflags::iter::Iter::__private_const_new(<RootUseFlags as
::bitflags::Flags>::FLAGS,
RootUseFlags::from_bits_retain(self.bits()),
RootUseFlags::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<RootUseFlags> {
::bitflags::iter::IterNames::__private_const_new(<RootUseFlags
as ::bitflags::Flags>::FLAGS,
RootUseFlags::from_bits_retain(self.bits()),
RootUseFlags::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for
InternalBitFlags {
type Item = RootUseFlags;
type IntoIter = ::bitflags::iter::Iter<RootUseFlags>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
impl InternalBitFlags {
/// Returns a mutable reference to the raw value of the flags currently stored.
#[inline]
pub fn bits_mut(&mut self) -> &mut u8 { &mut self.0 }
}
#[allow(dead_code, deprecated, unused_attributes)]
impl RootUseFlags {
/// Get a flags value with all bits unset.
#[inline]
pub const fn empty() -> Self { Self(InternalBitFlags::empty()) }
/// Get a flags value with all known bits set.
#[inline]
pub const fn all() -> Self { Self(InternalBitFlags::all()) }
/// Get the underlying bits value.
///
/// The returned value is exactly the bits set in this flags value.
#[inline]
pub const fn bits(&self) -> u8 { self.0.bits() }
/// Convert from a bits value.
///
/// This method will return `None` if any unknown bits are set.
#[inline]
pub const fn from_bits(bits: u8)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_bits(bits) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Convert from a bits value, unsetting any unknown bits.
#[inline]
pub const fn from_bits_truncate(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_truncate(bits))
}
/// Convert from a bits value exactly.
#[inline]
pub const fn from_bits_retain(bits: u8) -> Self {
Self(InternalBitFlags::from_bits_retain(bits))
}
/// Get a flags value with the bits of a flag with the given name set.
///
/// This method will return `None` if `name` is empty or doesn't
/// correspond to any named flag.
#[inline]
pub fn from_name(name: &str)
-> ::bitflags::__private::core::option::Option<Self> {
match InternalBitFlags::from_name(name) {
::bitflags::__private::core::option::Option::Some(bits) =>
::bitflags::__private::core::option::Option::Some(Self(bits)),
::bitflags::__private::core::option::Option::None =>
::bitflags::__private::core::option::Option::None,
}
}
/// Whether all bits in this flags value are unset.
#[inline]
pub const fn is_empty(&self) -> bool { self.0.is_empty() }
/// Whether all known bits in this flags value are set.
#[inline]
pub const fn is_all(&self) -> bool { self.0.is_all() }
/// Whether any set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn intersects(&self, other: Self) -> bool {
self.0.intersects(other.0)
}
/// Whether all set bits in a source flags value are also set in a target flags value.
#[inline]
pub const fn contains(&self, other: Self) -> bool {
self.0.contains(other.0)
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
pub fn insert(&mut self, other: Self) { self.0.insert(other.0) }
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `remove` won't truncate `other`, but the `!` operator will.
#[inline]
pub fn remove(&mut self, other: Self) { self.0.remove(other.0) }
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
pub fn toggle(&mut self, other: Self) { self.0.toggle(other.0) }
/// Call `insert` when `value` is `true` or `remove` when `value` is `false`.
#[inline]
pub fn set(&mut self, other: Self, value: bool) {
self.0.set(other.0, value)
}
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn intersection(self, other: Self) -> Self {
Self(self.0.intersection(other.0))
}
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn union(self, other: Self) -> Self {
Self(self.0.union(other.0))
}
/// The intersection of a source flags value with the complement of a target flags
/// value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
#[must_use]
pub const fn difference(self, other: Self) -> Self {
Self(self.0.difference(other.0))
}
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
#[must_use]
pub const fn symmetric_difference(self, other: Self) -> Self {
Self(self.0.symmetric_difference(other.0))
}
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
#[must_use]
pub const fn complement(self) -> Self {
Self(self.0.complement())
}
}
impl ::bitflags::__private::core::fmt::Binary for RootUseFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Binary::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::Octal for RootUseFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::Octal::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::LowerHex for RootUseFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::LowerHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::fmt::UpperHex for RootUseFlags {
fn fmt(&self, f: &mut ::bitflags::__private::core::fmt::Formatter)
-> ::bitflags::__private::core::fmt::Result {
let inner = self.0;
::bitflags::__private::core::fmt::UpperHex::fmt(&inner, f)
}
}
impl ::bitflags::__private::core::ops::BitOr for RootUseFlags {
type Output = Self;
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor(self, other: RootUseFlags) -> Self { self.union(other) }
}
impl ::bitflags::__private::core::ops::BitOrAssign for RootUseFlags {
/// The bitwise or (`|`) of the bits in two flags values.
#[inline]
fn bitor_assign(&mut self, other: Self) { self.insert(other); }
}
impl ::bitflags::__private::core::ops::BitXor for RootUseFlags {
type Output = Self;
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor(self, other: Self) -> Self {
self.symmetric_difference(other)
}
}
impl ::bitflags::__private::core::ops::BitXorAssign for RootUseFlags {
/// The bitwise exclusive-or (`^`) of the bits in two flags values.
#[inline]
fn bitxor_assign(&mut self, other: Self) { self.toggle(other); }
}
impl ::bitflags::__private::core::ops::BitAnd for RootUseFlags {
type Output = Self;
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand(self, other: Self) -> Self { self.intersection(other) }
}
impl ::bitflags::__private::core::ops::BitAndAssign for RootUseFlags {
/// The bitwise and (`&`) of the bits in two flags values.
#[inline]
fn bitand_assign(&mut self, other: Self) {
*self =
Self::from_bits_retain(self.bits()).intersection(other);
}
}
impl ::bitflags::__private::core::ops::Sub for RootUseFlags {
type Output = Self;
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub(self, other: Self) -> Self { self.difference(other) }
}
impl ::bitflags::__private::core::ops::SubAssign for RootUseFlags {
/// The intersection of a source flags value with the complement of a target flags value (`&!`).
///
/// This method is not equivalent to `self & !other` when `other` has unknown bits set.
/// `difference` won't truncate `other`, but the `!` operator will.
#[inline]
fn sub_assign(&mut self, other: Self) { self.remove(other); }
}
impl ::bitflags::__private::core::ops::Not for RootUseFlags {
type Output = Self;
/// The bitwise negation (`!`) of the bits in a flags value, truncating the result.
#[inline]
fn not(self) -> Self { self.complement() }
}
impl ::bitflags::__private::core::iter::Extend<RootUseFlags> for
RootUseFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn extend<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(&mut self, iterator: T) {
for item in iterator { self.insert(item) }
}
}
impl ::bitflags::__private::core::iter::FromIterator<RootUseFlags> for
RootUseFlags {
/// The bitwise or (`|`) of the bits in each flags value.
fn from_iter<T: ::bitflags::__private::core::iter::IntoIterator<Item
= Self>>(iterator: T) -> Self {
use ::bitflags::__private::core::iter::Extend;
let mut result = Self::empty();
result.extend(iterator);
result
}
}
impl RootUseFlags {
/// Yield a set of contained flags values.
///
/// Each yielded flags value will correspond to a defined named flag. Any unknown bits
/// will be yielded together as a final flags value.
#[inline]
pub const fn iter(&self) -> ::bitflags::iter::Iter<RootUseFlags> {
::bitflags::iter::Iter::__private_const_new(<RootUseFlags as
::bitflags::Flags>::FLAGS,
RootUseFlags::from_bits_retain(self.bits()),
RootUseFlags::from_bits_retain(self.bits()))
}
/// Yield a set of contained named flags values.
///
/// This method is like [`iter`](#method.iter), except only yields bits in contained named flags.
/// Any unknown bits, or bits not corresponding to a contained flag will not be yielded.
#[inline]
pub const fn iter_names(&self)
-> ::bitflags::iter::IterNames<RootUseFlags> {
::bitflags::iter::IterNames::__private_const_new(<RootUseFlags
as ::bitflags::Flags>::FLAGS,
RootUseFlags::from_bits_retain(self.bits()),
RootUseFlags::from_bits_retain(self.bits()))
}
}
impl ::bitflags::__private::core::iter::IntoIterator for RootUseFlags
{
type Item = RootUseFlags;
type IntoIter = ::bitflags::iter::Iter<RootUseFlags>;
fn into_iter(self) -> Self::IntoIter { self.iter() }
}
};bitflags! {
306/// VisitorState flags that are linked with the root type's use.
307 /// (These are the permanent part of the state, kept when visiting new Ty.)
308#[derive(Clone, Copy, Debug, PartialEq, Eq)]
309struct RootUseFlags: u8 {
310/// For use in (externally-linked) static variables.
311const STATIC = 0b000001;
312/// For use in functions in general.
313const FUNC = 0b000010;
314/// For variables in function returns (implicitly: not for static variables).
315const FN_RETURN = 0b000100;
316/// For variables in functions/variables which are defined in rust.
317const DEFINED = 0b001000;
318/// For times where we are only defining the type of something
319 /// (struct/enum/union definitions, FnPtrs).
320const THEORETICAL = 0b010000;
321 }
322}323324/// Description of the relationship between current Ty and
325/// the type (or lack thereof) immediately containing it
326#[derive(#[automatically_derived]
impl ::core::marker::Copy for OuterTyKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for OuterTyKind { }
#[automatically_derived]
impl ::core::clone::Clone for OuterTyKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for OuterTyKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
OuterTyKind::None => "None",
OuterTyKind::NoneThroughFnPtr => "NoneThroughFnPtr",
OuterTyKind::Other => "Other",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for OuterTyKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for OuterTyKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for OuterTyKind { }Eq)]
327enum OuterTyKind {
328None,
329/// A variant that should not exist,
330 /// but is needed because we don't change the lint's behavior yet
331NoneThroughFnPtr,
332/// Placeholder for properties that will be used eventually
333Other,
334}
335336impl OuterTyKind {
337/// Computes the relationship by providing the containing Ty itself
338fn from_ty<'tcx>(ty: Ty<'tcx>) -> Self {
339match ty.kind() {
340 ty::FnPtr(..) => Self::NoneThroughFnPtr,
341 ty::RawPtr(..)
342 | ty::Ref(..)
343 | ty::Adt(..)
344 | ty::Tuple(..)
345 | ty::Array(..)
346 | ty::Slice(_) => OuterTyKind::Other,
347_ => bug_impl(None, format_args!("Unexpected outer type {0:?}", ty),
Location::caller())bug!("Unexpected outer type {ty:?}"),
348 }
349 }
350}
351352#[derive(#[automatically_derived]
impl ::core::marker::Copy for VisitorState { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for VisitorState { }
#[automatically_derived]
impl ::core::clone::Clone for VisitorState {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<RootUseFlags>;
let _: ::core::clone::AssertParamIsClone<OuterTyKind>;
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for VisitorState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "VisitorState",
"root_use_flags", &self.root_use_flags, "outer_ty_kind",
&self.outer_ty_kind, "depth", &&self.depth)
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for VisitorState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for VisitorState {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.root_use_flags == other.root_use_flags &&
self.outer_ty_kind == other.outer_ty_kind &&
self.depth == other.depth
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for VisitorState {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<RootUseFlags>;
let _: ::core::cmp::AssertParamIsEq<OuterTyKind>;
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq)]
353struct VisitorState {
354/// Flags describing both the overall context in which the current Ty is,
355 /// linked to how the Visitor's original Ty was used.
356root_use_flags: RootUseFlags,
357/// Flags describing both the immediate context in which the current Ty is,
358 /// linked to how it relates to its parent Ty (or lack thereof).
359outer_ty_kind: OuterTyKind,
360/// Type recursion depth, to prevent infinite recursion
361depth: usize,
362}
363364impl RootUseFlags {
365// The values that can be set.
366const STATIC_TY: Self = Self::STATIC;
367const ARGUMENT_TY_IN_DEFINITION: Self =
368Self::from_bits(Self::FUNC.bits() | Self::DEFINED.bits()).unwrap();
369const RETURN_TY_IN_DEFINITION: Self =
370Self::from_bits(Self::FUNC.bits() | Self::FN_RETURN.bits() | Self::DEFINED.bits()).unwrap();
371const ARGUMENT_TY_IN_DECLARATION: Self = Self::FUNC;
372const RETURN_TY_IN_DECLARATION: Self =
373Self::from_bits(Self::FUNC.bits() | Self::FN_RETURN.bits()).unwrap();
374const ARGUMENT_TY_IN_FNPTR: Self =
375Self::from_bits(Self::FUNC.bits() | Self::THEORETICAL.bits()).unwrap();
376const RETURN_TY_IN_FNPTR: Self =
377Self::from_bits(Self::FUNC.bits() | Self::THEORETICAL.bits() | Self::FN_RETURN.bits())
378 .unwrap();
379}
380381impl VisitorState {
382/// From an existing state, compute the state of any subtype of the current type.
383 /// (General case. For the case where the current type is a function pointer, see `next_in_fnptr`.)
384fn next(&self, current_ty: Ty<'_>) -> Self {
385if !!#[allow(non_exhaustive_omitted_patterns)] match current_ty.kind() {
ty::FnPtr(..) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: !matches!(current_ty.kind(), ty::FnPtr(..))")
};assert!(!matches!(current_ty.kind(), ty::FnPtr(..)));
386VisitorState {
387 root_use_flags: self.root_use_flags,
388 outer_ty_kind: OuterTyKind::from_ty(current_ty),
389 depth: self.depth + 1,
390 }
391 }
392393/// From an existing state, compute the state of any subtype of the current type.
394 /// (Case where the current type is a function pointer,
395 /// meaning we need to specify if the subtype is an argument or the return.)
396fn next_in_fnptr(&self, current_ty: Ty<'_>, fn_pos: FnPos) -> Self {
397if !#[allow(non_exhaustive_omitted_patterns)] match current_ty.kind() {
ty::FnPtr(..) => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(current_ty.kind(), ty::FnPtr(..))")
};assert!(matches!(current_ty.kind(), ty::FnPtr(..)));
398VisitorState {
399 root_use_flags: match fn_pos {
400 FnPos::Ret => RootUseFlags::RETURN_TY_IN_FNPTR,
401 FnPos::Arg => RootUseFlags::ARGUMENT_TY_IN_FNPTR,
402 },
403 outer_ty_kind: OuterTyKind::from_ty(current_ty),
404 depth: self.depth + 1,
405 }
406 }
407408/// Get the proper visitor state for a given function's arguments or return type.
409fn fn_entry_point(fn_mode: CItemKind, fn_pos: FnPos) -> Self {
410let p_flags = match (fn_mode, fn_pos) {
411 (CItemKind::Definition, FnPos::Ret) => RootUseFlags::RETURN_TY_IN_DEFINITION,
412 (CItemKind::Declaration, FnPos::Ret) => RootUseFlags::RETURN_TY_IN_DECLARATION,
413 (CItemKind::Definition, FnPos::Arg) => RootUseFlags::ARGUMENT_TY_IN_DEFINITION,
414 (CItemKind::Declaration, FnPos::Arg) => RootUseFlags::ARGUMENT_TY_IN_DECLARATION,
415 };
416VisitorState { root_use_flags: p_flags, outer_ty_kind: OuterTyKind::None, depth: 0 }
417 }
418419/// Get the proper visitor state for a static variable's type
420fn static_entry_point() -> Self {
421VisitorState {
422 root_use_flags: RootUseFlags::STATIC_TY,
423 outer_ty_kind: OuterTyKind::None,
424 depth: 0,
425 }
426 }
427428/// Whether the type is used in a function.
429fn is_in_function(&self) -> bool {
430let ret = self.root_use_flags.contains(RootUseFlags::FUNC);
431if ret {
432if true {
if !!self.root_use_flags.contains(RootUseFlags::STATIC) {
::core::panicking::panic("assertion failed: !self.root_use_flags.contains(RootUseFlags::STATIC)")
};
};debug_assert!(!self.root_use_flags.contains(RootUseFlags::STATIC));
433 }
434ret435 }
436437/// Whether the type is used (directly or not) in a function, in return position.
438fn is_in_function_return(&self) -> bool {
439let ret = self.root_use_flags.contains(RootUseFlags::FN_RETURN);
440if ret {
441if true {
if !self.is_in_function() {
::core::panicking::panic("assertion failed: self.is_in_function()")
};
};debug_assert!(self.is_in_function());
442 }
443ret444 }
445446/// Whether the type is used (directly or not) in a defined function.
447 /// In other words, whether or not we allow non-FFI-safe types behind a C pointer,
448 /// to be treated as an opaque type on the other side of the FFI boundary.
449fn is_in_defined_function(&self) -> bool {
450self.root_use_flags.contains(RootUseFlags::DEFINED) && self.is_in_function()
451 }
452453/// Whether the type is used (directly or not) in a function pointer type.
454 /// Here, we also allow non-FFI-safe types behind a C pointer,
455 /// to be treated as an opaque type on the other side of the FFI boundary.
456fn is_in_fnptr(&self) -> bool {
457self.root_use_flags.contains(RootUseFlags::THEORETICAL) && self.is_in_function()
458 }
459460/// Whether we can expect type parameters and co in a given type.
461fn can_expect_ty_params(&self) -> bool {
462// rust-defined functions, as well as FnPtrs
463self.root_use_flags.contains(RootUseFlags::THEORETICAL) || self.is_in_defined_function()
464 }
465}
466467/// Visitor used to recursively traverse MIR types and evaluate FFI-safety.
468/// It uses ``check_*`` methods as entrypoints to be called elsewhere,
469/// and ``visit_*`` methods to recurse.
470struct ImproperCTypesVisitor<'a, 'tcx> {
471 cx: &'a LateContext<'tcx>,
472/// To prevent problems with recursive types,
473 /// add a types-in-check cache.
474cache: FxHashSet<Ty<'tcx>>,
475/// The original type being checked, before we recursed
476 /// to any other types it contains.
477base_ty: Ty<'tcx>,
478 base_fn_mode: CItemKind,
479}
480481impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
482fn new(
483 cx: &'a LateContext<'tcx>,
484 base_ty: Unnormalized<'tcx, Ty<'tcx>>,
485 base_fn_mode: CItemKind,
486 ) -> Self {
487// Skip normalization for opaques: even in `TypingMode::Borrowck` the body's own
488 // defining opaques still get revealed, leaving entries in `OpaqueTypeStorage` that
489 // ICE on `InferCtxt` drop (issue #156352).
490let base_ty = if base_ty.skip_norm_wip().has_opaque_types() {
491base_ty.skip_norm_wip()
492 } else {
493maybe_normalize_erasing_regions(cx, base_ty)
494 };
495ImproperCTypesVisitor { cx, base_ty, base_fn_mode, cache: FxHashSet::default() }
496 }
497498/// Checks if the given indirection (box,ref,pointer) is "ffi-safe".
499fn visit_indirection(
500&mut self,
501 state: VisitorState,
502 ty: Ty<'tcx>,
503 inner_ty: Ty<'tcx>,
504 indirection_kind: IndirectionKind,
505 ) -> FfiResult<'tcx> {
506use FfiResult::*;
507let tcx = self.cx.tcx;
508509match indirection_kind {
510 IndirectionKind::Box => {
511// FIXME(ctypes): this logic is broken, but it still fits the current tests:
512 // - for some reason `Box<_>`es in `extern "ABI" {}` blocks
513 // (including within FnPtr:s)
514 // are not treated as pointers but as FFI-unsafe structs
515 // - otherwise, treat the box itself correctly, and follow pointee safety logic
516 // as described in the other `indirection_type` match branch.
517if state.is_in_defined_function()
518 || (state.is_in_fnptr() && #[allow(non_exhaustive_omitted_patterns)] match self.base_fn_mode {
CItemKind::Definition => true,
_ => false,
}matches!(self.base_fn_mode, CItemKind::Definition))
519 {
520if inner_ty.is_sized(tcx, self.cx.typing_env()) {
521return FfiSafe;
522 } else {
523return FfiUnsafe {
524ty,
525 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("box cannot be represented as a single pointer"))msg!("box cannot be represented as a single pointer"),
526 help: None,
527 };
528 }
529 } else {
530// (mid-retcon-commit-chain comment:)
531 // this is the original fallback behavior, which is wrong
532if let ty::Adt(def, args) = ty.kind() {
533self.visit_struct_or_union(state, ty, *def, args)
534 } else if truecfg!(debug_assertions) {
535bug_impl(None,
format_args!("ImproperCTypes: this retcon commit was badly written"),
Location::caller())bug!("ImproperCTypes: this retcon commit was badly written")536 } else {
537FfiSafe538 }
539 }
540 }
541 IndirectionKind::Ref | IndirectionKind::RawPtr => {
542// Weird behaviour for pointee safety. the big question here is
543 // "if you have a FFI-unsafe pointee behind a FFI-safe pointer type, is it ok?"
544 // The answer until now is:
545 // "It's OK for rust-defined functions and callbacks, we'll assume those are
546 // meant to be opaque types on the other side of the FFI boundary".
547 //
548 // Reasoning:
549 // For extern function declarations, the actual definition of the function is
550 // written somewhere else, meaning the declaration is free to express this
551 // opaqueness with an extern type (opaque caller-side) or a std::ffi::c_void
552 // (opaque callee-side). For extern function definitions, however, in the case
553 // where the type is opaque caller-side, it is not opaque callee-side,
554 // and having the full type information is necessary to compile the function.
555 //
556 // It might be better to rething this, or even ignore pointee safety for a first
557 // batch of behaviour changes. See the discussion that ends with
558 // https://github.com/rust-lang/rust/pull/134697#issuecomment-2692610258
559if (state.is_in_defined_function() || state.is_in_fnptr())
560 && inner_ty.is_sized(self.cx.tcx, self.cx.typing_env())
561 {
562FfiSafe563 } else {
564self.visit_type(state.next(ty), inner_ty)
565 }
566 }
567 }
568 }
569570/// Checks if the given `VariantDef`'s field types are "ffi-safe".
571fn visit_variant_fields(
572&mut self,
573 state: VisitorState,
574 ty: Ty<'tcx>,
575 def: AdtDef<'tcx>,
576 variant: &ty::VariantDef,
577 args: GenericArgsRef<'tcx>,
578 ) -> FfiResult<'tcx> {
579use FfiResult::*;
580581let transparent_with_all_zst_fields = if def.repr().transparent() {
582if let Some(field) = super::transparent_newtype_field(self.cx.tcx, variant) {
583// Transparent newtypes have at most one non-ZST field which needs to be checked..
584let field_ty =
585maybe_normalize_erasing_regions(self.cx, field.ty(self.cx.tcx, args));
586match self.visit_type(state.next(ty), field_ty) {
587FfiUnsafe { ty, .. } if ty.is_unit() => (),
588 r => return r,
589 }
590591false
592} else {
593// ..or have only ZST fields, which is FFI-unsafe (unless those fields are all
594 // `PhantomData`).
595true
596}
597 } else {
598false
599};
600601// We can't completely trust `repr(C)` markings, so make sure the fields are actually safe.
602let mut all_phantom = !variant.fields.is_empty();
603for field in &variant.fields {
604let field_ty = maybe_normalize_erasing_regions(self.cx, field.ty(self.cx.tcx, args));
605 all_phantom &= match self.visit_type(state.next(ty), field_ty) {
606 FfiSafe => false,
607// `()` fields are FFI-safe!
608FfiUnsafe { ty, .. } if ty.is_unit() => false,
609 FfiPhantom(..) => true,
610 r @ FfiUnsafe { .. } => return r,
611 }
612 }
613614if all_phantom {
615FfiPhantom(ty)
616 } else if transparent_with_all_zst_fields {
617FfiUnsafe {
618ty,
619 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this struct contains only zero-sized fields"))msg!("this struct contains only zero-sized fields"),
620 help: None,
621 }
622 } else {
623FfiSafe624 }
625 }
626627fn visit_struct_or_union(
628&mut self,
629 state: VisitorState,
630 ty: Ty<'tcx>,
631 def: AdtDef<'tcx>,
632 args: GenericArgsRef<'tcx>,
633 ) -> FfiResult<'tcx> {
634if true {
if !#[allow(non_exhaustive_omitted_patterns)] match def.adt_kind() {
AdtKind::Struct | AdtKind::Union => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(def.adt_kind(), AdtKind::Struct | AdtKind::Union)")
};
};debug_assert!(matches!(def.adt_kind(), AdtKind::Struct | AdtKind::Union));
635use FfiResult::*;
636637if !def.repr().c() && !def.repr().transparent() {
638return FfiUnsafe {
639ty,
640 reason: if def.is_struct() {
641rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this struct has unspecified layout"))msg!("this struct has unspecified layout")642 } else {
643rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this union has unspecified layout"))msg!("this union has unspecified layout")644 },
645 help: if def.is_struct() {
646Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct"))msg!(
647"consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct"
648))
649 } else {
650// FIXME(#60405): confirm that this makes sense for unions once #60405 / RFC2645 stabilises
651Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this union"))msg!(
652"consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this union"
653))
654 },
655 };
656 }
657658if def.non_enum_variant().field_list_has_applicable_non_exhaustive() {
659return FfiUnsafe {
660ty,
661 reason: if def.is_struct() {
662rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this struct is non-exhaustive"))msg!("this struct is non-exhaustive")663 } else {
664rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this union is non-exhaustive"))msg!("this union is non-exhaustive")665 },
666 help: None,
667 };
668 }
669670if def.non_enum_variant().fields.is_empty() {
671FfiUnsafe {
672ty,
673 reason: if def.is_struct() {
674rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this struct has no fields"))msg!("this struct has no fields")675 } else {
676rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this union has no fields"))msg!("this union has no fields")677 },
678 help: if def.is_struct() {
679Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding a member to this struct"))msg!("consider adding a member to this struct"))
680 } else {
681Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding a member to this union"))msg!("consider adding a member to this union"))
682 },
683 }
684 } else {
685self.visit_variant_fields(state, ty, def, def.non_enum_variant(), args)
686 }
687 }
688689fn visit_enum(
690&mut self,
691 state: VisitorState,
692 ty: Ty<'tcx>,
693 def: AdtDef<'tcx>,
694 args: GenericArgsRef<'tcx>,
695 ) -> FfiResult<'tcx> {
696if true {
if !#[allow(non_exhaustive_omitted_patterns)] match def.adt_kind() {
AdtKind::Enum => true,
_ => false,
} {
::core::panicking::panic("assertion failed: matches!(def.adt_kind(), AdtKind::Enum)")
};
};debug_assert!(matches!(def.adt_kind(), AdtKind::Enum));
697use FfiResult::*;
698699if def.variants().is_empty() {
700// Empty enums are okay... although sort of useless.
701return FfiSafe;
702 }
703// Check for a repr() attribute to specify the size of the
704 // discriminant.
705if !def.repr().c() && !def.repr().transparent() && def.repr().int.is_none() {
706// Special-case types like `Option<extern fn()>` and `Result<extern fn(), ()>`
707if let Some(inner_ty) = repr_nullable_ptr(self.cx.tcx, self.cx.typing_env(), ty) {
708return self.visit_type(state.next(ty), inner_ty);
709 }
710711return FfiUnsafe {
712ty,
713 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("enum has no representation hint"))msg!("enum has no representation hint"),
714 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum"))msg!(
715"consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum"
716)),
717 };
718 }
719720let non_exhaustive = def.variant_list_has_applicable_non_exhaustive();
721// Check the contained variants.
722let ret = def.variants().iter().try_for_each(|variant| {
723 check_non_exhaustive_variant(non_exhaustive, variant)
724 .map_break(|reason| FfiUnsafe { ty, reason, help: None })?;
725726match self.visit_variant_fields(state, ty, def, variant, args) {
727FfiSafe => ControlFlow::Continue(()),
728 r => ControlFlow::Break(r),
729 }
730 });
731if let ControlFlow::Break(result) = ret {
732return result;
733 }
734735FfiSafe736 }
737738/// Checks if the given type is "ffi-safe" (has a stable, well-defined
739 /// representation which can be exported to C code).
740fn visit_type(&mut self, state: VisitorState, ty: Ty<'tcx>) -> FfiResult<'tcx> {
741use FfiResult::*;
742743let tcx = self.cx.tcx;
744745// Protect against infinite recursion, for example
746 // `struct S(*mut S);`.
747if !(self.cache.insert(ty) && self.cx.tcx.recursion_limit().value_within_limit(state.depth))
748 {
749return FfiSafe;
750 }
751752match *ty.kind() {
753 ty::Adt(def, args) => {
754if let Some(inner_ty) = ty.boxed_ty() {
755return self.visit_indirection(state, ty, inner_ty, IndirectionKind::Box);
756 }
757if def.is_phantom_data() {
758return FfiPhantom(ty);
759 }
760match def.adt_kind() {
761 AdtKind::Struct | AdtKind::Union => {
762if let Some(sym::cstring_type | sym::cstr_type) =
763tcx.get_diagnostic_name(def.did())
764 && !self.base_ty.is_mutable_ptr()
765 {
766return FfiUnsafe {
767ty,
768 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("`CStr`/`CString` do not have a guaranteed layout"))msg!("`CStr`/`CString` do not have a guaranteed layout"),
769 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider passing a `*const std::ffi::c_char` instead, and use `CStr::as_ptr()`"))msg!(
770"consider passing a `*const std::ffi::c_char` instead, and use `CStr::as_ptr()`"
771)),
772 };
773 }
774self.visit_struct_or_union(state, ty, def, args)
775 }
776 AdtKind::Enum => self.visit_enum(state, ty, def, args),
777 }
778 }
779780// Pattern types are just extra invariants on the type that you need to uphold,
781 // but only the base type is relevant for being representable in FFI.
782 // (note: this lint was written when pattern types could only be integers constrained to ranges)
783 // (also note: the lack of ".next(ty)" on the state is on purpose)
784ty::Pat(pat_ty, _) => self.visit_type(state, pat_ty),
785786// types which likely have a stable representation, if the target architecture defines those
787 // note: before rust 1.77, 128-bit ints were not FFI-safe on x86_64
788ty::Int(..) | ty::Uint(..) | ty::Float(..) => FfiResult::FfiSafe,
789790 ty::Bool => FfiResult::FfiSafe,
791792 ty::Char => FfiResult::FfiUnsafe {
793ty,
794 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `char` type has no C equivalent"))msg!("the `char` type has no C equivalent"),
795 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider using `u32` or `libc::wchar_t` instead"))msg!("consider using `u32` or `libc::wchar_t` instead")),
796 },
797798 ty::Slice(_) => FfiUnsafe {
799ty,
800 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("slices have no C equivalent"))msg!("slices have no C equivalent"),
801 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider using a raw pointer instead"))msg!("consider using a raw pointer instead")),
802 },
803804 ty::Dynamic(..) => {
805FfiUnsafe { ty, reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("trait objects have no C equivalent"))msg!("trait objects have no C equivalent"), help: None }
806 }
807808 ty::Str => FfiUnsafe {
809ty,
810 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("string slices have no C equivalent"))msg!("string slices have no C equivalent"),
811 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider using `*const u8` and a length instead"))msg!("consider using `*const u8` and a length instead")),
812 },
813814 ty::Tuple(tuple) => {
815if tuple.is_empty()
816 && state.is_in_function_return()
817 && #[allow(non_exhaustive_omitted_patterns)] match state.outer_ty_kind {
OuterTyKind::None | OuterTyKind::NoneThroughFnPtr => true,
_ => false,
}matches!(
818 state.outer_ty_kind,
819 OuterTyKind::None | OuterTyKind::NoneThroughFnPtr
820 )821 {
822// C functions can return void
823FfiSafe824 } else {
825FfiUnsafe {
826ty,
827 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("tuples have unspecified layout"))msg!("tuples have unspecified layout"),
828 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider using a struct instead"))msg!("consider using a struct instead")),
829 }
830 }
831 }
832833 ty::RawPtr(ty, _)
834if match ty.kind() {
835 ty::Tuple(tuple) => tuple.is_empty(),
836_ => false,
837 } =>
838 {
839FfiSafe840 }
841842 ty::RawPtr(inner_ty, _) => {
843return self.visit_indirection(state, ty, inner_ty, IndirectionKind::RawPtr);
844 }
845 ty::Ref(_, inner_ty, _) => {
846return self.visit_indirection(state, ty, inner_ty, IndirectionKind::Ref);
847 }
848849 ty::Array(inner_ty, _) => {
850if state.is_in_function()
851// FIXME(ctypes): VVV-this-VVV shouldn't make a difference between ::None and ::NoneThroughFnPtr
852 && #[allow(non_exhaustive_omitted_patterns)] match state.outer_ty_kind {
OuterTyKind::None => true,
_ => false,
}matches!(state.outer_ty_kind, OuterTyKind::None)853 {
854// C doesn't really support passing arrays by value - the only way to pass an array by value
855 // is through a struct.
856FfiResult::FfiUnsafe {
857ty,
858 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("passing raw arrays by value is not FFI-safe"))msg!("passing raw arrays by value is not FFI-safe"),
859 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider passing a pointer to the array"))msg!("consider passing a pointer to the array")),
860 }
861 } else {
862// let's allow phantoms to go through,
863 // since an array of 1-ZSTs is also a 1-ZST
864self.visit_type(state.next(ty), inner_ty)
865 }
866 }
867868 ty::FnPtr(sig_tys, hdr) => {
869let sig = sig_tys.with(hdr);
870if sig.abi().is_rustic_abi() {
871return FfiUnsafe {
872ty,
873 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this function pointer has Rust-specific calling convention"))msg!("this function pointer has Rust-specific calling convention"),
874 help: Some(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("consider using an `extern fn(...) -> ...` function pointer instead"))msg!(
875"consider using an `extern fn(...) -> ...` function pointer instead"
876)),
877 };
878 }
879880let sig = tcx.instantiate_bound_regions_with_erased(sig);
881for arg in sig.inputs() {
882match self.visit_type(state.next_in_fnptr(ty, FnPos::Arg), *arg) {
883 FfiSafe => {}
884 r => return r,
885 }
886 }
887888let ret_ty = sig.output();
889self.visit_type(state.next_in_fnptr(ty, FnPos::Ret), ret_ty)
890 }
891892 ty::Foreign(..) => FfiSafe,
893894 ty::Never => FfiSafe,
895896// While opaque types are checked for earlier, if a projection in a struct field
897 // normalizes to an opaque type, then it will reach this branch.
898ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
899FfiUnsafe { ty, reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("opaque types have no C equivalent"))msg!("opaque types have no C equivalent"), help: None }
900 }
901902// `extern "C" fn` functions can have type parameters, which may or may not be FFI-safe,
903 // so they are currently ignored for the purposes of this lint.
904ty::Param(..)
905 | ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. })
906if state.can_expect_ty_params() =>
907 {
908FfiSafe909 }
910911 ty::UnsafeBinder(_) => FfiUnsafe {
912ty,
913 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unsafe binders are incompatible with foreign function interfaces"))msg!("unsafe binders are incompatible with foreign function interfaces"),
914 help: None,
915 },
916917// Safety net for when normalization reveals a body's own defining opaque
918 // (e.g. `async extern fn`'s `impl Future` → `Coroutine`); the nicer
919 // "opaque types have no C equivalent" message comes from `visit_for_opaque_ty`
920 // in `check_type` before normalization (issue #156352).
921ty::Closure(..)
922 | ty::CoroutineClosure(..)
923 | ty::Coroutine(..)
924 | ty::CoroutineWitness(..) => FfiUnsafe {
925ty,
926 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("closures and coroutines are not FFI-safe"))msg!("closures and coroutines are not FFI-safe"),
927 help: None,
928 },
929930 ty::Param(..)
931 | ty::Alias(
932_,
933 ty::AliasTy {
934 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
935 ..
936 },
937 )
938 | ty::Infer(..)
939 | ty::Bound(..)
940 | ty::Error(_)
941 | ty::Placeholder(..)
942 | ty::FnDef(..) => bug_impl(None, format_args!("unexpected type in foreign function: {0:?}", ty),
Location::caller())bug!("unexpected type in foreign function: {:?}", ty),
943 }
944 }
945946fn visit_for_opaque_ty(&mut self, ty: Ty<'tcx>) -> PartialFfiResult<'tcx> {
947struct ProhibitOpaqueTypes;
948impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ProhibitOpaqueTypes {
949type Result = ControlFlow<Ty<'tcx>>;
950951fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
952if !ty.has_opaque_types() {
953return ControlFlow::Continue(());
954 }
955956if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) = ty.kind() {
957 ControlFlow::Break(ty)
958 } else {
959ty.super_visit_with(self)
960 }
961 }
962 }
963964ty.visit_with(&mut ProhibitOpaqueTypes).break_value().map(|ty| FfiResult::FfiUnsafe {
965ty,
966 reason: rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("opaque types have no C equivalent"))msg!("opaque types have no C equivalent"),
967 help: None,
968 })
969 }
970971fn check_type(
972&mut self,
973 state: VisitorState,
974 ty: Unnormalized<'tcx, Ty<'tcx>>,
975 ) -> FfiResult<'tcx> {
976// Catch opaques before normalization so the new solver doesn't reveal them
977 // (e.g. `async extern fn` return → `Coroutine`) and we get the nicer
978 // "opaque types have no C equivalent" message.
979if let Some(res) = self.visit_for_opaque_ty(ty.skip_norm_wip()) {
980return res;
981 }
982let ty = maybe_normalize_erasing_regions(self.cx, ty);
983if let Some(res) = self.visit_for_opaque_ty(ty) {
984return res;
985 }
986987self.visit_type(state, ty)
988 }
989}
990991impl<'tcx> ImproperCTypesLint {
992/// Find any fn-ptr types with external ABIs in `ty`, and FFI-checks them.
993 /// For example, `Option<extern "C" fn()>` FFI-checks `extern "C" fn()`.
994fn check_type_for_external_abi_fnptr(
995&mut self,
996 cx: &LateContext<'tcx>,
997 state: VisitorState,
998 hir_ty: &hir::Ty<'tcx>,
999 ty: Ty<'tcx>,
1000 fn_mode: CItemKind,
1001 ) {
1002struct FnPtrFinder<'tcx> {
1003 current_depth: usize,
1004 depths: Vec<usize>,
1005 spans: Vec<Span>,
1006 tys: Vec<Ty<'tcx>>,
1007 }
10081009impl<'tcx> hir::intravisit::Visitor<'_> for FnPtrFinder<'tcx> {
1010fn visit_ty(&mut self, ty: &'_ hir::Ty<'_, AmbigArg>) {
1011{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/bba531001d4de6d7f49693e0836a2668ca063282/compiler/rustc_lint/src/types/improper_ctypes.rs:1011",
"rustc_lint::types::improper_ctypes",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/bba531001d4de6d7f49693e0836a2668ca063282/compiler/rustc_lint/src/types/improper_ctypes.rs"),
::tracing_core::__macro_support::Option::Some(1011u32),
::tracing_core::__macro_support::Option::Some("rustc_lint::types::improper_ctypes"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("ty")
}> =
::tracing::__macro_support::FieldName::new("ty");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?ty);
1012self.current_depth += 1;
1013if let hir::TyKind::FnPtr(hir::FnPtrTy { abi, .. }) = ty.kind
1014 && !abi.is_rustic_abi()
1015 {
1016self.depths.push(self.current_depth);
1017self.spans.push(ty.span);
1018 }
10191020 hir::intravisit::walk_ty(self, ty);
1021self.current_depth -= 1;
1022 }
1023 }
10241025impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for FnPtrFinder<'tcx> {
1026type Result = ();
10271028fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
1029if let ty::FnPtr(_, hdr) = ty.kind()
1030 && !hdr.abi().is_rustic_abi()
1031 {
1032self.tys.push(ty);
1033 }
10341035ty.super_visit_with(self)
1036 }
1037 }
10381039let mut visitor = FnPtrFinder {
1040 spans: Vec::new(),
1041 tys: Vec::new(),
1042 depths: Vec::new(),
1043 current_depth: 0,
1044 };
1045ty.visit_with(&mut visitor);
1046visitor.visit_ty_unambig(hir_ty);
10471048let all_types = iter::zip(
1049visitor.depths.drain(..),
1050 iter::zip(visitor.tys.drain(..), visitor.spans.drain(..)),
1051 );
1052for (depth, (fn_ptr_ty, span)) in all_types {
1053let fn_ptr_ty = Unnormalized::new_wip(fn_ptr_ty);
1054let mut visitor = ImproperCTypesVisitor::new(cx, fn_ptr_ty, fn_mode);
1055let bridge_state = VisitorState { depth, ..state };
1056// FIXME(ctypes): make a check_for_fnptr
1057let ffi_res = visitor.check_type(bridge_state, fn_ptr_ty);
10581059self.process_ffi_result(cx, span, ffi_res, fn_mode);
1060 }
1061 }
10621063/// Regardless of a function's need to be "ffi-safe", look for fn-ptr argument/return types
1064 /// that need to be checked for ffi-safety.
1065fn check_fn_for_external_abi_fnptr(
1066&mut self,
1067 cx: &LateContext<'tcx>,
1068 fn_mode: CItemKind,
1069 def_id: LocalDefId,
1070 decl: &'tcx hir::FnDecl<'_>,
1071 ) {
1072let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1073let sig = cx.tcx.instantiate_bound_regions_with_erased(sig);
10741075for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) {
1076let state = VisitorState::fn_entry_point(fn_mode, FnPos::Arg);
1077self.check_type_for_external_abi_fnptr(cx, state, input_hir, *input_ty, fn_mode);
1078 }
10791080if let hir::FnRetTy::Return(ret_hir) = decl.output {
1081let state = VisitorState::fn_entry_point(fn_mode, FnPos::Ret);
1082self.check_type_for_external_abi_fnptr(cx, state, ret_hir, sig.output(), fn_mode);
1083 }
1084 }
10851086/// For a local definition of a #[repr(C)] struct/enum/union, check that it is indeed FFI-safe.
1087fn check_reprc_adt(
1088&mut self,
1089 cx: &LateContext<'tcx>,
1090 item: &'tcx hir::Item<'tcx>,
1091 adt_def: AdtDef<'tcx>,
1092 ) {
1093if true {
if !(adt_def.repr().c() && !adt_def.repr().packed() &&
adt_def.repr().align.is_none()) {
::core::panicking::panic("assertion failed: adt_def.repr().c() && !adt_def.repr().packed() &&\n adt_def.repr().align.is_none()")
};
};debug_assert!(
1094 adt_def.repr().c() && !adt_def.repr().packed() && adt_def.repr().align.is_none()
1095 );
10961097// FIXME(ctypes): this following call is awkward.
1098 // is there a way to perform its logic in MIR space rather than HIR space?
1099 // (so that its logic can be absorbed into visitor.visit_struct_or_union)
1100check_struct_for_power_alignment(cx, item, adt_def);
1101 }
11021103fn check_foreign_static(&mut self, cx: &LateContext<'tcx>, id: hir::OwnerId, span: Span) {
1104let ty = cx.tcx.type_of(id).instantiate_identity();
1105let mut visitor = ImproperCTypesVisitor::new(cx, ty, CItemKind::Declaration);
1106let ffi_res = visitor.check_type(VisitorState::static_entry_point(), ty);
1107self.process_ffi_result(cx, span, ffi_res, CItemKind::Declaration);
1108 }
11091110/// Check if a function's argument types and result type are "ffi-safe".
1111fn check_foreign_fn(
1112&mut self,
1113 cx: &LateContext<'tcx>,
1114 fn_mode: CItemKind,
1115 def_id: LocalDefId,
1116 decl: &'tcx hir::FnDecl<'_>,
1117 ) {
1118let sig = cx.tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip();
1119let sig = cx.tcx.instantiate_bound_regions_with_erased(sig);
11201121for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) {
1122let input_ty = Unnormalized::new_wip(*input_ty);
1123let state = VisitorState::fn_entry_point(fn_mode, FnPos::Arg);
1124let mut visitor = ImproperCTypesVisitor::new(cx, input_ty, fn_mode);
1125let ffi_res = visitor.check_type(state, input_ty);
1126self.process_ffi_result(cx, input_hir.span, ffi_res, fn_mode);
1127 }
11281129if let hir::FnRetTy::Return(ret_hir) = decl.output {
1130let output_ty = Unnormalized::new_wip(sig.output());
1131let state = VisitorState::fn_entry_point(fn_mode, FnPos::Ret);
1132let mut visitor = ImproperCTypesVisitor::new(cx, output_ty, fn_mode);
1133let ffi_res = visitor.check_type(state, output_ty);
1134self.process_ffi_result(cx, ret_hir.span, ffi_res, fn_mode);
1135 }
1136 }
11371138fn process_ffi_result(
1139&self,
1140 cx: &LateContext<'tcx>,
1141 sp: Span,
1142 res: FfiResult<'tcx>,
1143 fn_mode: CItemKind,
1144 ) {
1145match res {
1146 FfiResult::FfiSafe => {}
1147 FfiResult::FfiPhantom(ty) => {
1148self.emit_ffi_unsafe_type_lint(
1149cx,
1150ty,
1151sp,
1152rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("composed only of `PhantomData`"))msg!("composed only of `PhantomData`"),
1153None,
1154fn_mode,
1155 );
1156 }
1157 FfiResult::FfiUnsafe { ty, reason, help } => {
1158self.emit_ffi_unsafe_type_lint(cx, ty, sp, reason, help, fn_mode);
1159 }
1160 }
1161 }
11621163fn emit_ffi_unsafe_type_lint(
1164&self,
1165 cx: &LateContext<'tcx>,
1166 ty: Ty<'tcx>,
1167 sp: Span,
1168 note: DiagMessage,
1169 help: Option<DiagMessage>,
1170 fn_mode: CItemKind,
1171 ) {
1172let lint = match fn_mode {
1173 CItemKind::Declaration => IMPROPER_CTYPES,
1174 CItemKind::Definition => IMPROPER_CTYPES_DEFINITIONS,
1175 };
1176let desc = match fn_mode {
1177 CItemKind::Declaration => "block",
1178 CItemKind::Definition => "fn",
1179 };
1180let span_note = if let ty::Adt(def, _) = ty.kind()
1181 && let Some(sp) = cx.tcx.hir_span_if_local(def.did())
1182 {
1183Some(sp)
1184 } else {
1185None1186 };
1187cx.emit_span_lint(lint, sp, ImproperCTypes { ty, desc, label: sp, help, note, span_note });
1188 }
1189}
11901191/// `ImproperCTypesDefinitions` checks items outside of foreign items (e.g. stuff that isn't in
1192/// `extern "C" { }` blocks):
1193///
1194/// - `extern "<abi>" fn` definitions are checked in the same way as the
1195/// `ImproperCtypesDeclarations` visitor checks functions if `<abi>` is external (e.g. "C").
1196/// - All other items which contain types (e.g. other functions, struct definitions, etc) are
1197/// checked for extern fn-ptrs with external ABIs.
1198impl<'tcx> LateLintPass<'tcx> for ImproperCTypesLint {
1199fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, it: &hir::ForeignItem<'tcx>) {
1200let abi = cx.tcx.hir_get_foreign_abi(it.hir_id());
12011202match it.kind {
1203 hir::ForeignItemKind::Fn(sig, _, _) => {
1204// fnptrs are a special case, they always need to be treated as
1205 // "the element rendered unsafe" because their unsafety doesn't affect
1206 // their surroundings, and their type is often declared inline
1207if !abi.is_rustic_abi() {
1208self.check_foreign_fn(cx, CItemKind::Declaration, it.owner_id.def_id, sig.decl);
1209 } else {
1210self.check_fn_for_external_abi_fnptr(
1211cx,
1212 CItemKind::Declaration,
1213it.owner_id.def_id,
1214sig.decl,
1215 );
1216 }
1217 }
1218 hir::ForeignItemKind::Static(ty, _, _) if !abi.is_rustic_abi() => {
1219self.check_foreign_static(cx, it.owner_id, ty.span);
1220 }
1221 hir::ForeignItemKind::Static(..) | hir::ForeignItemKind::Type => (),
1222 }
1223 }
12241225fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1226match item.kind {
1227 hir::ItemKind::Static(_, _, ty, _)
1228 | hir::ItemKind::Const(_, _, ty, _)
1229 | hir::ItemKind::TyAlias(_, _, ty) => {
1230self.check_type_for_external_abi_fnptr(
1231cx,
1232VisitorState::static_entry_point(),
1233ty,
1234cx.tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip(),
1235 CItemKind::Definition,
1236 );
1237 }
1238// See `check_fn` for declarations, `check_foreign_items` for definitions in extern blocks
1239hir::ItemKind::Fn { .. } => {}
1240 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {
1241// looking for extern FnPtr:s is delegated to `check_field_def`.
1242let adt_def: AdtDef<'tcx> = cx.tcx.adt_def(item.owner_id.to_def_id());
12431244if adt_def.repr().c() && !adt_def.repr().packed() && adt_def.repr().align.is_none()
1245 {
1246self.check_reprc_adt(cx, item, adt_def);
1247 }
1248 }
12491250// Doesn't define something that can contain a external type to be checked.
1251hir::ItemKind::Impl(..)
1252 | hir::ItemKind::TraitAlias(..)
1253 | hir::ItemKind::Trait { .. }
1254 | hir::ItemKind::GlobalAsm { .. }
1255 | hir::ItemKind::ForeignMod { .. }
1256 | hir::ItemKind::Mod(..)
1257 | hir::ItemKind::Macro(..)
1258 | hir::ItemKind::Use(..)
1259 | hir::ItemKind::ExternCrate(..)
1260 | hir::ItemKind::TestBinderConstraints { .. } => {}
1261 }
1262 }
12631264fn check_field_def(&mut self, cx: &LateContext<'tcx>, field: &'tcx hir::FieldDef<'tcx>) {
1265self.check_type_for_external_abi_fnptr(
1266cx,
1267VisitorState::static_entry_point(),
1268field.ty,
1269cx.tcx.type_of(field.def_id).instantiate_identity().skip_norm_wip(),
1270 CItemKind::Definition,
1271 );
1272 }
12731274fn check_fn(
1275&mut self,
1276 cx: &LateContext<'tcx>,
1277 kind: hir::intravisit::FnKind<'tcx>,
1278 decl: &'tcx hir::FnDecl<'_>,
1279_: &'tcx hir::Body<'_>,
1280_: Span,
1281 id: LocalDefId,
1282 ) {
1283use hir::intravisit::FnKind;
12841285let abi = match kind {
1286 FnKind::ItemFn(_, _, header, ..) => header.abi,
1287 FnKind::Method(_, sig, ..) => sig.header.abi,
1288_ => return,
1289 };
12901291// fnptrs are a special case, they always need to be treated as
1292 // "the element rendered unsafe" because their unsafety doesn't affect
1293 // their surroundings, and their type is often declared inline
1294if !abi.is_rustic_abi() {
1295self.check_foreign_fn(cx, CItemKind::Definition, id, decl);
1296 } else {
1297self.check_fn_for_external_abi_fnptr(cx, CItemKind::Definition, id, decl);
1298 }
1299 }
1300}