Debian Codegraph @

.cargo/vendor/cbindgen/src/bindgen/ir/repr.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use syn::ext::IdentExt;
6
7 use crate::bindgen::ir::ty::{IntKind, PrimitiveType};
8
9 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
10 pub enum ReprStyle {
11 Rust,
12 C,
13 Transparent,
14 }
15
16 impl Default for ReprStyle {
17 fn default() -> Self {
18 ReprStyle::Rust
19 }
20 }
21
22 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
23 pub struct ReprType {
24 kind: IntKind,
25 signed: bool,
26 }
27
28 impl ReprType {
29 pub(crate) fn to_primitive(self) -> PrimitiveType {
30 PrimitiveType::Integer {
31 kind: self.kind,
32 signed: self.signed,
33 zeroable: true,
34 }
35 }
36 }
37
38 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
39 pub enum ReprAlign {
40 Packed,
41 Align(u64),
42 }
43
44 #[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
45 pub struct Repr {
46 pub style: ReprStyle,
47 pub ty: Option<ReprType>,
48 pub align: Option<ReprAlign>,
49 }
50
51 impl Repr {
52 pub fn load(attrs: &[syn::Attribute]) -> Result<Repr, String> {
53 let ids = attrs
54 .iter()
55 .filter_map(|attr| {
56 if let syn::Meta::List(syn::MetaList { path, nested, .. }) =
57 attr.parse_meta().ok()?
58 {
59 if path.is_ident("repr") {
60 return Some(nested.into_iter().collect::<Vec<_>>());
61 }
62 }
63 None
64 })
65 .flatten()
66 .filter_map(|meta| match meta {
67 syn::NestedMeta::Meta(syn::Meta::Path(path)) => Some((
68 path.segments.first().unwrap().ident.unraw().to_string(),
69 None,
70 )),
71 syn::NestedMeta::Meta(syn::Meta::List(syn::MetaList { path, nested, .. })) => {
72 Some((
73 path.segments.first().unwrap().ident.unraw().to_string(),
74 Some(
75 nested
76 .iter()
77 .filter_map(|meta| match meta {
78 // Only used for #[repr(align(...))].
79 syn::NestedMeta::Lit(syn::Lit::Int(literal)) => {
80 Some(literal.base10_digits().to_string())
81 }
82 // Only single levels of nesting supported at the moment.
83 _ => None,
84 })
85 .collect::<Vec<_>>(),
86 ),
87 ))
88 }
89 _ => None,
90 });
91
92 let mut repr = Repr::default();
93 for id in ids {
94 let (int_kind, signed) = match (id.0.as_ref(), id.1) {
95 ("u8", None) => (IntKind::B8, false),
96 ("u16", None) => (IntKind::B16, false),
97 ("u32", None) => (IntKind::B32, false),
98 ("u64", None) => (IntKind::B64, false),
99 ("usize", None) => (IntKind::Size, false),
100 ("i8", None) => (IntKind::B8, true),
101 ("i16", None) => (IntKind::B16, true),
102 ("i32", None) => (IntKind::B32, true),
103 ("i64", None) => (IntKind::B64, true),
104 ("isize", None) => (IntKind::Size, true),
105 ("C", None) => {
106 repr.style = ReprStyle::C;
107 continue;
108 }
109 ("transparent", None) => {
110 repr.style = ReprStyle::Transparent;
111 continue;
112 }
113 ("packed", args) => {
114 // #[repr(packed(n))] not supported because of some open questions about how
115 // to calculate the native alignment of types. See eqrion/cbindgen#433.
116 if args.is_some() {
117 return Err(
118 "Not-yet-implemented #[repr(packed(...))] encountered.".to_string()
119 );
120 }
121 let align = ReprAlign::Packed;
122 // Only permit a single alignment-setting repr.
123 if let Some(old_align) = repr.align {
124 return Err(format!(
125 "Conflicting #[repr(align(...))] type hints {:?} and {:?}.",
126 old_align, align
127 ));
128 }
129 repr.align = Some(align);
130 continue;
131 }
132 ("align", Some(args)) => {
133 // #[repr(align(...))] only allows a single argument.
134 if args.len() != 1 {
135 return Err(format!(
136 "Unsupported #[repr(align({}))], align must have exactly one argument.",
137 args.join(", ")
138 ));
139 }
140 // Must be a positive integer.
141 let align = match args.first().unwrap().parse::<u64>() {
142 Ok(align) => align,
143 Err(_) => {
144 return Err(format!("Non-numeric #[repr(align({}))].", args.join(", ")))
145 }
146 };
147 // Must be a power of 2.
148 if !align.is_power_of_two() || align == 0 {
149 return Err(format!("Invalid alignment to #[repr(align({}))].", align));
150 }
151 // Only permit a single alignment-setting repr.
152 if let Some(old_align) = repr.align {
153 return Err(format!(
154 "Conflicting #[repr(align(...))] type hints {:?} and {:?}.",
155 old_align,
156 ReprAlign::Align(align)
157 ));
158 }
159 repr.align = Some(ReprAlign::Align(align));
160 continue;
161 }
162 (path, args) => match args {
163 None => return Err(format!("Unsupported #[repr({})].", path)),
164 Some(args) => {
165 return Err(format!(
166 "Unsupported #[repr({}({}))].",
167 path,
168 args.join(", ")
169 ));
170 }
171 },
172 };
173 let ty = ReprType {
174 kind: int_kind,
175 signed,
176 };
177 if let Some(old_ty) = repr.ty {
178 return Err(format!(
179 "Conflicting #[repr(...)] type hints {:?} and {:?}.",
180 old_ty, ty
181 ));
182 }
183 repr.ty = Some(ty);
184 }
185 Ok(repr)
186 }
187 }