forked from rust-lang/libc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffi_items.rs
More file actions
243 lines (211 loc) · 7.3 KB
/
ffi_items.rs
File metadata and controls
243 lines (211 loc) · 7.3 KB
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
use std::ops::Deref;
use syn::punctuated::Punctuated;
use syn::visit::Visit;
use crate::{Abi, Const, Field, Fn, Parameter, Static, Struct, Type, Union};
/// Represents a collected set of top-level Rust items relevant to FFI generation or analysis.
///
/// Includes foreign functions/statics, type aliases, structs, unions, and constants.
#[derive(Default, Clone, Debug)]
pub(crate) struct FfiItems {
pub(crate) aliases: Vec<Type>,
pub(crate) structs: Vec<Struct>,
pub(crate) unions: Vec<Union>,
pub(crate) constants: Vec<Const>,
pub(crate) foreign_functions: Vec<Fn>,
pub(crate) foreign_statics: Vec<Static>,
}
impl FfiItems {
/// Creates a new blank FfiItems.
pub(crate) fn new() -> Self {
Self::default()
}
/// Return whether the type has parsed a struct with the given identifier.
pub(crate) fn contains_struct(&self, ident: &str) -> bool {
self.structs()
.iter()
.any(|structure| structure.ident() == ident)
}
/// Return whether the type has parsed a union with the given identifier.
pub(crate) fn contains_union(&self, ident: &str) -> bool {
self.unions().iter().any(|union| union.ident() == ident)
}
/// Return a list of all type aliases found.
pub(crate) fn aliases(&self) -> &Vec<Type> {
&self.aliases
}
/// Return a list of all structs found.
pub(crate) fn structs(&self) -> &Vec<Struct> {
&self.structs
}
/// Return a list of all unions found.
pub(crate) fn unions(&self) -> &Vec<Union> {
&self.unions
}
/// Return a list of all constants found.
pub(crate) fn constants(&self) -> &Vec<Const> {
&self.constants
}
/// Return a list of all foreign functions found mapped by their ABI.
#[cfg_attr(not(test), expect(unused))]
pub(crate) fn foreign_functions(&self) -> &Vec<Fn> {
&self.foreign_functions
}
/// Return a list of all foreign statics found mapped by their ABI.
#[cfg_attr(not(test), expect(unused))]
pub(crate) fn foreign_statics(&self) -> &Vec<Static> {
&self.foreign_statics
}
}
/// Determine whether an item is visible to other crates.
///
/// This function assumes that if the visibility is restricted then it is not
/// meant to be accessed.
fn is_visible(vis: &syn::Visibility) -> bool {
match vis {
syn::Visibility::Public(_) => true,
syn::Visibility::Inherited | syn::Visibility::Restricted(_) => false,
}
}
/// Collect fields in a syn grammar into ctest's equivalent structure.
fn collect_fields(fields: &Punctuated<syn::Field, syn::Token![,]>) -> Vec<Field> {
fields
.iter()
.filter_map(|field| {
field.ident.as_ref().map(|ident| Field {
public: is_visible(&field.vis),
ident: ident.to_string().into_boxed_str(),
ty: field.ty.clone(),
})
})
.collect()
}
fn visit_foreign_item_fn(table: &mut FfiItems, i: &syn::ForeignItemFn, abi: &Abi) {
let public = is_visible(&i.vis);
let abi = abi.clone();
let ident = i.sig.ident.to_string().into_boxed_str();
let parameters = i
.sig
.inputs
.iter()
.map(|arg| match arg {
syn::FnArg::Typed(arg) => Parameter {
ident: match arg.pat.deref() {
syn::Pat::Ident(i) => i.ident.to_string().into_boxed_str(),
_ => {
unimplemented!("Foreign functions are unlikely to have any other pattern.")
}
},
ty: arg.ty.deref().clone(),
},
syn::FnArg::Receiver(_) => {
unreachable!("Foreign functions can't have self/receiver parameters.")
}
})
.collect::<Vec<_>>();
let return_type = match &i.sig.output {
syn::ReturnType::Default => None,
syn::ReturnType::Type(_, ty) => Some(ty.deref().clone()),
};
let mut link_name_iter = i
.attrs
.iter()
.filter(|attr| attr.path().is_ident("link_name"));
let link_name = link_name_iter.next().and_then(|attr| match &attr.meta {
syn::Meta::NameValue(nv) => {
if let syn::Expr::Lit(expr_lit) = &nv.value {
if let syn::Lit::Str(lit_str) = &expr_lit.lit {
return Some(lit_str.value().into_boxed_str());
}
}
None
}
_ => None,
});
if let Some(attr) = link_name_iter.next() {
panic!("multiple `#[link_name = ...]` attributes found: {attr:?}");
}
table.foreign_functions.push(Fn {
public,
abi,
ident,
link_name,
parameters,
return_type,
});
}
fn visit_foreign_item_static(table: &mut FfiItems, i: &syn::ForeignItemStatic, abi: &Abi) {
let public = is_visible(&i.vis);
let abi = abi.clone();
let ident = i.ident.to_string().into_boxed_str();
let ty = i.ty.deref().clone();
table.foreign_statics.push(Static {
public,
abi,
ident,
ty,
});
}
impl<'ast> Visit<'ast> for FfiItems {
fn visit_item_type(&mut self, i: &'ast syn::ItemType) {
let public = is_visible(&i.vis);
let ty = i.ty.deref().clone();
let ident = i.ident.to_string().into_boxed_str();
self.aliases.push(Type { public, ident, ty });
}
fn visit_item_struct(&mut self, i: &'ast syn::ItemStruct) {
let public = is_visible(&i.vis);
let ident = i.ident.to_string().into_boxed_str();
let fields = match &i.fields {
syn::Fields::Named(fields) => collect_fields(&fields.named),
syn::Fields::Unnamed(fields) => collect_fields(&fields.unnamed),
syn::Fields::Unit => Vec::new(),
};
self.structs.push(Struct {
public,
ident,
fields,
});
}
fn visit_item_union(&mut self, i: &'ast syn::ItemUnion) {
let public = is_visible(&i.vis);
let ident = i.ident.to_string().into_boxed_str();
let fields = collect_fields(&i.fields.named);
self.unions.push(Union {
public,
ident,
fields,
});
}
fn visit_item_const(&mut self, i: &'ast syn::ItemConst) {
let public = is_visible(&i.vis);
let ident = i.ident.to_string().into_boxed_str();
let ty = i.ty.deref().clone();
let expr = i.expr.deref().clone();
self.constants.push(Const {
public,
ident,
ty,
expr,
});
}
fn visit_item_foreign_mod(&mut self, i: &'ast syn::ItemForeignMod) {
// Because we need to store the ABI we can't directly visit the foreign
// functions/statics.
// Since this is an extern block, assume extern "C" by default.
let abi = i
.abi
.name
.clone()
.map(|s| Abi::from(s.value().as_str()))
.unwrap_or_else(|| Abi::C);
for item in &i.items {
match item {
syn::ForeignItem::Fn(function) => visit_foreign_item_fn(self, function, &abi),
syn::ForeignItem::Static(static_variable) => {
visit_foreign_item_static(self, static_variable, &abi)
}
_ => (),
}
}
}
}