summaryrefslogtreecommitdiffstats
path: root/src/bindgen/ir/repr.rs
blob: c40cd7fc19103f1d6c93a52304f986a6db1d6951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use syn::ext::IdentExt;

use crate::bindgen::ir::ty::{IntKind, PrimitiveType};

#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub enum ReprStyle {
    #[default]
    Rust,
    C,
    Transparent,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ReprType {
    kind: IntKind,
    signed: bool,
}

impl ReprType {
    pub(crate) fn to_primitive(self) -> PrimitiveType {
        PrimitiveType::Integer {
            kind: self.kind,
            signed: self.signed,
            zeroable: true,
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ReprAlign {
    Packed,
    Align(u64),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
pub struct Repr {
    pub style: ReprStyle,
    pub ty: Option<ReprType>,
    pub align: Option<ReprAlign>,
}

impl Repr {
    pub fn load(attrs: &[syn::Attribute]) -> Result<Repr, String> {
        let ids = attrs
            .iter()
            .filter_map(|attr| {
                if let syn::Meta::List(syn::MetaList { path, nested, .. }) =
                    attr.parse_meta().ok()?
                {
                    if path.is_ident("repr") {
                        return Some(nested.into_iter().collect::<Vec<_>>());
                    }
                }
                None
            })
            .flatten()
            .filter_map(|meta| match meta {
                syn::NestedMeta::Meta(syn::Meta::Path(path)) => Some((
                    path.segments.first().unwrap().ident.unraw().to_string(),
                    None,
                )),
                syn::NestedMeta::Meta(syn::Meta::List(syn::MetaList { path, nested, .. })) => {
                    Some((
                        path.segments.first().unwrap().ident.unraw().to_string(),
                        Some(
                            nested
                                .iter()
                                .filter_map(|meta| match meta {
                                    // Only used for #[repr(align(...))].
                                    syn::NestedMeta::Lit(syn::Lit::Int(literal)) => {
                                        Some(literal.base10_digits().to_string())
                                    }
                                    // Only single levels of nesting supported at the moment.
                                    _ => None,
                                })
                                .collect::<Vec<_>>(),
                        ),
                    ))
                }
                _ => None,
            });

        let mut repr = Repr::default();
        for id in ids {
            let (int_kind, signed) = match (id.0.as_ref(), id.1) {
                ("u8", None) => (IntKind::B8, false),
                ("u16", None) => (IntKind::B16, false),
                ("u32", None) => (IntKind::B32, false),
                ("u64", None) => (IntKind::B64, false),
                ("usize", None) => (IntKind::Size, false),
                ("i8", None) => (IntKind::B8, true),
                ("i16", None) => (IntKind::B16, true),
                ("i32", None) => (IntKind::B32, true),
                ("i64", None) => (IntKind::B64, true),
                ("isize", None) => (IntKind::Size, true),
                ("C", None) => {
                    repr.style = ReprStyle::C;
                    continue;
                }
                ("transparent", None) => {
                    repr.style = ReprStyle::Transparent;
                    continue;
                }
                ("packed", args) => {
                    // #[repr(packed(n))] not supported because of some open questions about how
                    // to calculate the native alignment of types. See mozilla/cbindgen#433.
                    if args.is_some() {
                        return Err(
                            "Not-yet-implemented #[repr(packed(...))] encountered.".to_string()
                        );
                    }
                    let align = ReprAlign::Packed;
                    // Only permit a single alignment-setting repr.
                    if let Some(old_align) = repr.align {
                        return Err(format!(
                            "Conflicting #[repr(align(...))] type hints {:?} and {:?}.",
                            old_align, align
                        ));
                    }
                    repr.align = Some(align);
                    continue;
                }
                ("align", Some(args)) => {
                    // #[repr(align(...))] only allows a single argument.
                    if args.len() != 1 {
                        return Err(format!(
                            "Unsupported #[repr(align({}))], align must have exactly one argument.",
                            args.join(", ")
                        ));
                    }
                    // Must be a positive integer.
                    let align = match args.first().unwrap().parse::<u64>() {
                        Ok(align) => align,
                        Err(_) => {
                            return Err(format!("Non-numeric #[repr(align({}))].", args.join(", ")))
                        }
                    };
                    // Must be a power of 2.
                    if !align.is_power_of_two() || align == 0 {
                        return Err(format!("Invalid alignment to #[repr(align({}))].", align));
                    }
                    // Only permit a single alignment-setting repr.
                    if let Some(old_align) = repr.align {
                        return Err(format!(
                            "Conflicting #[repr(align(...))] type hints {:?} and {:?}.",
                            old_align,
                            ReprAlign::Align(align)
                        ));
                    }
                    repr.align = Some(ReprAlign::Align(align));
                    continue;
                }
                (path, args) => match args {
                    None => return Err(format!("Unsupported #[repr({})].", path)),
                    Some(args) => {
                        return Err(format!(
                            "Unsupported #[repr({}({}))].",
                            path,
                            args.join(", ")
                        ));
                    }
                },
            };
            let ty = ReprType {
                kind: int_kind,
                signed,
            };
            if let Some(old_ty) = repr.ty {
                return Err(format!(
                    "Conflicting #[repr(...)] type hints {:?} and {:?}.",
                    old_ty, ty
                ));
            }
            repr.ty = Some(ty);
        }
        Ok(repr)
    }
}