Debian Codegraph @

src/codegen/sys/ffi_type.rs

raw
1 use log::{info, trace, warn};
2
3 use crate::{
4 analysis::{
5 c_type::{implements_c_type, rustify_pointers},
6 namespaces,
7 rust_type::{Result, TypeError},
8 },
9 env::Env,
10 library::{self, *},
11 traits::*,
12 };
13
14 // FIXME: This module needs redundant allocations audit
15 // TODO: ffi_type computations should be cached
16
17 pub fn ffi_type(env: &Env, tid: library::TypeId, c_type: &str) -> Result {
18 let (ptr, inner) = rustify_pointers(c_type);
19 let res = if ptr.is_empty() {
20 if let Some(c_tid) = env.library.find_type(0, c_type) {
21 // Fast track plain basic types avoiding some checks
22 if env.library.type_(c_tid).maybe_ref_as::<Basic>().is_some() {
23 match *env.library.type_(tid) {
24 Type::FixedArray(inner_tid, size, ref inner_c_type) => {
25 let inner_c_type = inner_c_type.as_ref().map_or(c_type, String::as_str);
26 ffi_type(env, inner_tid, inner_c_type).map_any(|rust_type| {
27 rust_type.alter_type(|typ_| format!("[{typ_}; {size}]"))
28 })
29 }
30 Type::Class(Class {
31 c_type: ref expected,
32 ..
33 })
34 | Type::Interface(Interface {
35 c_type: ref expected,
36 ..
37 }) if c_type == "gpointer" => {
38 info!("[c:type `gpointer` instead of `*mut {expected}`, fixing]");
39 ffi_inner(env, tid, expected.clone()).map_any(|rust_type| {
40 rust_type.alter_type(|typ_| format!("*mut {typ_}"))
41 })
42 }
43 _ => ffi_inner(env, c_tid, c_type.into()),
44 }
45 } else {
46 // c_type isn't Basic
47 ffi_inner(env, tid, inner)
48 }
49 } else {
50 // c_type doesn't match any type in the library by name
51 ffi_inner(env, tid, inner)
52 }
53 } else {
54 // ptr not empty
55 ffi_inner(env, tid, inner)
56 .map_any(|rust_type| rust_type.alter_type(|typ_| format!("{ptr} {typ_}")))
57 };
58 trace!("ffi_type({tid:?}, {c_type}) -> {res:?}");
59 res
60 }
61
62 fn ffi_basic(fund: &crate::library::Basic) -> Option<&'static str> {
63 use crate::library::Basic::*;
64
65 let res = match fund {
66 None => "c_void",
67 Boolean => "gboolean",
68 Int8 => "i8",
69 UInt8 => "u8",
70 Int16 => "i16",
71 UInt16 => "u16",
72 Int32 => "i32",
73 UInt32 => "u32",
74 Int64 => "i64",
75 UInt64 => "u64",
76 Char => "c_char",
77 UChar => "c_uchar",
78 Short => "c_short",
79 UShort => "c_ushort",
80 Int => "c_int",
81 UInt => "c_uint",
82 Long => "c_long",
83 ULong => "c_ulong",
84 Size => "size_t",
85 SSize => "ssize_t",
86 TimeT => "time_t",
87 OffT => "off_t",
88 DevT => "dev_t",
89 GidT => "gid_t",
90 PidT => "pid_t",
91 SockLenT => "socklen_t",
92 UidT => "uid_t",
93 Float => "c_float",
94 Double => "c_double",
95 UniChar => "u32",
96 Utf8 => "c_char",
97 Filename => "c_char",
98 OsString => "c_char",
99 Type => "GType",
100 IntPtr => "intptr_t",
101 UIntPtr => "uintptr_t",
102 Bool => "bool",
103 Pointer => "gpointer",
104 Unsupported => return Option::None,
105 VarArgs => panic!("Should not reach here"),
106 };
107
108 Some(res)
109 }
110
111 fn ffi_inner(env: &Env, tid: library::TypeId, mut inner: String) -> Result {
112 let mut volatile = false;
113 if let Some(non_volatile) = inner.strip_prefix("volatile ") {
114 volatile = true;
115 inner = non_volatile.into();
116 }
117
118 let typ = env.library.type_(tid);
119 let res = match *typ {
120 Type::Basic(fund) => {
121 use crate::library::Basic::*;
122 let inner = match fund {
123 Pointer => {
124 match inner.as_str() {
125 "void" => "c_void",
126 "gconstpointer" => "gconstpointer",
127 "gpointer" => "gpointer",
128 // TODO: try use time:Tm
129 "tm" => return Err(TypeError::Unimplemented(inner)),
130 _ => {
131 if let Some(c_tid) = env.library.find_type(0, &inner) {
132 if let Some(fund) = env
133 .library
134 .type_(c_tid)
135 .maybe_ref_as::<Basic>()
136 .and_then(ffi_basic)
137 {
138 fund
139 } else {
140 &*inner
141 }
142 } else {
143 &*inner
144 }
145 }
146 }
147 }
148 _ => ffi_basic(&fund).ok_or(TypeError::Unimplemented(inner))?,
149 };
150 Ok(inner.into())
151 }
152 Type::Record(..) | Type::Alias(..) | Type::Function(..) => {
153 if let Some(declared_c_type) = typ.get_glib_name() {
154 if declared_c_type != inner {
155 let msg = format!(
156 "[c:type mismatch `{}` != `{}` of `{}`]",
157 inner,
158 declared_c_type,
159 typ.get_name()
160 );
161 warn!("{msg}");
162 return Err(TypeError::Mismatch(msg));
163 }
164 } else {
165 warn!("Type `{}` missing c_type", typ.get_name());
166 }
167 fix_name(env, tid, &inner)
168 }
169 Type::CArray(inner_tid) => ffi_inner(env, inner_tid, inner),
170 Type::FixedArray(inner_tid, size, ref inner_c_type) => {
171 let inner_c_type = inner_c_type
172 .as_ref()
173 .map_or_else(|| inner.as_str(), String::as_str);
174 ffi_type(env, inner_tid, inner_c_type)
175 .map_any(|rust_type| rust_type.alter_type(|typ_| format!("[{typ_}; {size}]")))
176 }
177 Type::Array(..)
178 | Type::PtrArray(..)
179 | Type::List(..)
180 | Type::SList(..)
181 | Type::HashTable(..) => fix_name(env, tid, &inner),
182 _ => {
183 if let Some(glib_name) = env.library.type_(tid).get_glib_name() {
184 if inner != glib_name {
185 if inner == "gpointer" {
186 fix_name(env, tid, glib_name).map_any(|rust_type| {
187 rust_type.alter_type(|typ_| format!("*mut {typ_}"))
188 })
189 } else if implements_c_type(env, tid, &inner) {
190 info!(
191 "[c:type {} of {} <: {}, fixing]",
192 glib_name,
193 env.library.type_(tid).get_name(),
194 inner
195 );
196 fix_name(env, tid, glib_name)
197 } else {
198 let msg = format!(
199 "[c:type mismatch {} != {} of {}]",
200 inner,
201 glib_name,
202 env.library.type_(tid).get_name()
203 );
204 warn!("{msg}");
205 Err(TypeError::Mismatch(msg))
206 }
207 } else {
208 fix_name(env, tid, &inner)
209 }
210 } else {
211 let msg = format!(
212 "[Missing glib_name of {}, can't match != {}]",
213 env.library.type_(tid).get_name(),
214 inner
215 );
216 warn!("{msg}");
217 Err(TypeError::Mismatch(msg))
218 }
219 }
220 };
221
222 if volatile {
223 res.map(|rust_type| rust_type.alter_type(|typ_| format!("/*volatile*/{typ_}")))
224 } else {
225 res
226 }
227 }
228
229 fn fix_name(env: &Env, type_id: library::TypeId, name: &str) -> Result {
230 if type_id.ns_id == library::INTERNAL_NAMESPACE {
231 match env.library.type_(type_id) {
232 Type::Array(..)
233 | Type::PtrArray(..)
234 | Type::List(..)
235 | Type::SList(..)
236 | Type::HashTable(..) => {
237 if env.namespaces.glib_ns_id == namespaces::MAIN {
238 Ok(name.into())
239 } else {
240 Ok(format!(
241 "{}::{}",
242 env.namespaces[env.namespaces.glib_ns_id].crate_name, name
243 )
244 .into())
245 }
246 }
247 _ => Ok(name.into()),
248 }
249 } else {
250 let name_with_prefix = if type_id.ns_id == namespaces::MAIN {
251 name.into()
252 } else {
253 format!("{}::{}", env.namespaces[type_id.ns_id].crate_name, name)
254 };
255 if env
256 .type_status_sys(&type_id.full_name(&env.library))
257 .ignored()
258 {
259 Err(TypeError::Ignored(name_with_prefix))
260 } else {
261 Ok(name_with_prefix.into())
262 }
263 }
264 }