Skip to content

Commit 6a902de

Browse files
committed
transpile: Split convert_pointer into two functions for easier reuse
1 parent ec1a29e commit 6a902de

File tree

1 file changed

+27
-22
lines changed

1 file changed

+27
-22
lines changed

c2rust-transpile/src/convert_type.rs

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -268,44 +268,49 @@ impl TypeConverter {
268268
Ok(mk().unsafe_().extern_("C").barefn_ty(fn_ty))
269269
}
270270

271+
/// Converts the qualified type of a pointer.
271272
pub fn convert_pointer(
272273
&mut self,
273274
ctxt: &TypedAstContext,
274275
qtype: CQualTypeId,
275276
) -> TranslationResult<Box<Type>> {
276-
let mutbl = if qtype.qualifiers.is_const {
277-
Mutability::Immutable
277+
let pointee_ty = self.convert_pointee(ctxt, qtype.ctype)?;
278+
279+
if let CTypeKind::Function(..) = ctxt.resolve_type(qtype.ctype).kind {
280+
// Function pointers are translated to Option applied to the function type
281+
// in order to support NULL function pointers natively
282+
let param = mk().angle_bracketed_args(vec![pointee_ty]);
283+
Ok(mk().path_ty(vec![mk().path_segment_with_args("Option", param)]))
278284
} else {
279-
Mutability::Mutable
280-
};
285+
let mutbl = if qtype.qualifiers.is_const {
286+
Mutability::Immutable
287+
} else {
288+
Mutability::Mutable
289+
};
281290

282-
match ctxt.resolve_type(qtype.ctype).kind {
291+
Ok(mk().set_mutbl(mutbl).ptr_ty(pointee_ty))
292+
}
293+
}
294+
295+
/// Converts the pointee type of a pointer.
296+
pub fn convert_pointee(
297+
&mut self,
298+
ctxt: &TypedAstContext,
299+
ctype: CTypeId,
300+
) -> TranslationResult<Box<Type>> {
301+
match ctxt.resolve_type(ctype).kind {
283302
// While void converts to () in function returns, it converts to c_void
284303
// in the case of pointers.
285-
CTypeKind::Void => Ok(mk()
286-
.set_mutbl(mutbl)
287-
.ptr_ty(mk().abs_path_ty(vec!["core", "ffi", "c_void"]))),
304+
CTypeKind::Void => Ok(mk().abs_path_ty(vec!["core", "ffi", "c_void"])),
288305

289306
CTypeKind::VariableArray(mut elt, _len) => {
290307
while let CTypeKind::VariableArray(elt_, _) = ctxt.resolve_type(elt).kind {
291308
elt = elt_
292309
}
293-
let child_ty = self.convert(ctxt, elt)?;
294-
Ok(mk().set_mutbl(mutbl).ptr_ty(child_ty))
295-
}
296-
297-
// Function pointers are translated to Option applied to the function type
298-
// in order to support NULL function pointers natively
299-
CTypeKind::Function(..) => {
300-
let fn_ty = self.convert(ctxt, qtype.ctype)?;
301-
let param = mk().angle_bracketed_args(vec![fn_ty]);
302-
Ok(mk().path_ty(vec![mk().path_segment_with_args("Option", param)]))
310+
self.convert(ctxt, elt)
303311
}
304312

305-
_ => {
306-
let child_ty = self.convert(ctxt, qtype.ctype)?;
307-
Ok(mk().set_mutbl(mutbl).ptr_ty(child_ty))
308-
}
313+
_ => self.convert(ctxt, ctype),
309314
}
310315
}
311316

0 commit comments

Comments
 (0)