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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use c2rust_ast_builder::mk;
use c_ast::CDeclId;
use c_ast::*;
use renamer::*;
use std::collections::{HashMap, HashSet};
use std::ops::Index;
use syntax::ast::*;
use syntax::ptr::P;
use translator::TranslationError;

pub struct TypeConverter {
    pub translate_valist: bool,
    renamer: Renamer<CDeclId>,
    fields: HashMap<CDeclId, Renamer<CFieldId>>,
    features: HashSet<&'static str>,
    emit_no_std: bool,
}

static RESERVED_NAMES: [&str; 101] = [
    // Keywords currently in use
    "as",
    "break",
    "const",
    "continue",
    "crate",
    "else",
    "enum",
    "extern",
    "false",
    "fn",
    "for",
    "if",
    "impl",
    "in",
    "let",
    "loop",
    "match",
    "mod",
    "move",
    "mut",
    "pub",
    "ref",
    "return",
    "Self",
    "self",
    "static",
    "struct",
    "super",
    "trait",
    "true",
    "type",
    "unsafe",
    "use",
    "where",
    "while",
    "dyn",
    // Keywords reserved for future use
    "abstract",
    "alignof",
    "become",
    "box",
    "do",
    "final",
    "macro",
    "offsetof",
    "override",
    "priv",
    "proc",
    "pure",
    "sizeof",
    "typeof",
    "unsized",
    "virtual",
    "yield",
    // Types exported in prelude
    "Copy",
    "Send",
    "Sized",
    "Sync",
    "Drop",
    "Fn",
    "FnMut",
    "FnOnce",
    "Box",
    "ToOwned",
    "Clone",
    "PartialEq",
    "PartialOrd",
    "Eq",
    "Ord",
    "AsRef",
    "AsMut",
    "Into",
    "From",
    "Default",
    "Iterator",
    "Extend",
    "IntoIterator",
    "DoubleEndedIterator",
    "ExactSizeIterator",
    "Option",
    "Result",
    "SliceConcatExt",
    "String",
    "ToString",
    "Vec",
    "bool",
    "char",
    "f32",
    "f64",
    "i8",
    "i16",
    "i32",
    "i64",
    "i128",
    "isize",
    "u8",
    "u16",
    "u32",
    "u64",
    "u128",
    "usize",
    "str",
];

impl TypeConverter {
    pub fn new(emit_no_std: bool) -> TypeConverter {
        TypeConverter {
            translate_valist: false,
            renamer: Renamer::new(&RESERVED_NAMES),
            fields: HashMap::new(),
            features: HashSet::new(),
            emit_no_std,
        }
    }

    pub fn features_used(&self) -> &HashSet<&'static str> {
        &self.features
    }

    pub fn declare_decl_name(&mut self, decl_id: CDeclId, name: &str) -> String {
        self.renamer
            .insert(decl_id, name)
            .expect("Name already assigned")
    }

    pub fn alias_decl_name(&mut self, new_decl_id: CDeclId, old_decl_id: CDeclId) {
        self.renamer.alias(new_decl_id, &old_decl_id)
    }

    pub fn resolve_decl_name(&self, decl_id: CDeclId) -> Option<String> {
        self.renamer.get(&decl_id)
    }

    pub fn declare_field_name(
        &mut self,
        record_id: CRecordId,
        field_id: CFieldId,
        name: &str,
    ) -> String {
        let name = if name.is_empty() { "unnamed" } else { name };

        if !self.fields.contains_key(&record_id) {
            self.fields.insert(record_id, Renamer::new(&RESERVED_NAMES));
        }

        self.fields
            .get_mut(&record_id)
            .unwrap()
            .insert(field_id, name)
            .expect("Field already declared")
    }

    /** Resolve the Rust name associated with a field declaration. The optional record_id
    is used as a hint to speed up the process of finding the field's name.
    */
    pub fn resolve_field_name(
        &self,
        record_id: Option<CRecordId>,
        field_id: CFieldId,
    ) -> Option<String> {
        match record_id {
            Some(record_id) => self.fields.get(&record_id).and_then(|x| x.get(&field_id)),
            None => self.fields.values().flat_map(|x| x.get(&field_id)).next(),
        }
    }

    /// Helper function handling conversion of function types in `convert`.
    /// Optional return type excludes a ty when a function doesn't return.
    fn convert_function(
        &mut self,
        ctxt: &TypedAstContext,
        ret: Option<CQualTypeId>,
        params: &Vec<CQualTypeId>,
        is_variadic: bool,
    ) -> Result<P<Ty>, TranslationError> {
        let mut inputs = params
            .iter()
            .map(|x| mk().arg(self.convert(ctxt, x.ctype).unwrap(), mk().wild_pat()))
            .collect::<Vec<_>>();

        let output = match ret {
            None => mk().never_ty(),
            Some(ret) => self.convert(ctxt, ret.ctype)?,
        };

        if is_variadic {
            // For variadic functions, we need to add `_: ...` as an explicit argument
            inputs.push(mk().arg(mk().cvar_args_ty(), mk().wild_pat()))
        };

        let fn_ty = mk().fn_decl(inputs, FunctionRetTy::Ty(output), is_variadic);
        return Ok(mk().unsafe_().abi("C").barefn_ty(fn_ty));
    }

    pub fn convert_pointer(
        &mut self,
        ctxt: &TypedAstContext,
        qtype: CQualTypeId,
    ) -> Result<P<Ty>, TranslationError> {
        match ctxt.resolve_type(qtype.ctype).kind {
            // While void converts to () in function returns, it converts to c_void
            // in the case of pointers.
            CTypeKind::Void => {
                let mutbl = if qtype.qualifiers.is_const {
                    Mutability::Immutable
                } else {
                    Mutability::Mutable
                };
                return Ok(mk()
                    .set_mutbl(mutbl)
                    .ptr_ty(mk().path_ty(vec!["libc", "c_void"])));
            }

            CTypeKind::VariableArray(mut elt, _len) => {
                while let CTypeKind::VariableArray(elt_, _) = ctxt.resolve_type(elt).kind {
                    elt = elt_
                }
                let child_ty = self.convert(ctxt, elt)?;
                let mutbl = if qtype.qualifiers.is_const {
                    Mutability::Immutable
                } else {
                    Mutability::Mutable
                };
                return Ok(mk().set_mutbl(mutbl).ptr_ty(child_ty));
            }

            // Function pointers are translated to Option applied to the function type
            // in order to support NULL function pointers natively
            CTypeKind::Function(ret, ref params, is_var, is_noreturn, has_proto) => {
                if !has_proto {
                    return Err(TranslationError::generic(
                        "Unable to convert function pointer type without prototype",
                    ));
                }

                let opt_ret = if is_noreturn { None } else { Some(ret) };
                let fn_ty = self.convert_function(ctxt, opt_ret, params, is_var)?;
                let param = mk().angle_bracketed_args(vec![fn_ty]);
                let optn_ty = mk().path_ty(vec![mk().path_segment_with_args("Option", param)]);
                return Ok(optn_ty);
            }

            CTypeKind::Struct(struct_id) => {
                if self.translate_valist {
                    if let CDeclKind::Struct {
                        name: Some(ref struct_name),
                        ..
                    } = ctxt[struct_id].kind
                    {
                        if struct_name == "__va_list_tag" {
                            self.features.insert("c_variadic");

                            let std_or_core = if self.emit_no_std { "core" } else { "std" };
                            let path = vec!["", std_or_core, "ffi", "VaList"];
                            let ty = mk().path_ty(path);
                            return Ok(ty);
                        }
                    }
                }
            }

            _ => {}
        }

        let child_ty = self.convert(ctxt, qtype.ctype)?;
        let mutbl = if qtype.qualifiers.is_const {
            Mutability::Immutable
        } else {
            Mutability::Mutable
        };
        Ok(mk().set_mutbl(mutbl).ptr_ty(child_ty))
    }

    pub fn is_inner_type_valist(ctxt: &TypedAstContext, qtype: CQualTypeId) -> bool {
        match ctxt.resolve_type(qtype.ctype).kind {
            CTypeKind::Struct(struct_id) => {
                if let CDeclKind::Struct {
                    name: Some(ref struct_name),
                    ..
                } = ctxt[struct_id].kind
                {
                    if struct_name == "__va_list_tag" {
                        return true;
                    }
                }
                false
            }
            CTypeKind::Pointer(pointer_id) => Self::is_inner_type_valist(ctxt, pointer_id),
            _ => false,
        }
    }

    /// Convert a `C` type to a `Rust` one. For the moment, these are expected to have compatible
    /// memory layouts.
    pub fn convert(
        &mut self,
        ctxt: &TypedAstContext,
        ctype: CTypeId,
    ) -> Result<P<Ty>, TranslationError> {
        match ctxt.index(ctype).kind {
            CTypeKind::Void => Ok(mk().tuple_ty(vec![] as Vec<P<Ty>>)),
            CTypeKind::Bool => Ok(mk().path_ty(mk().path(vec!["bool"]))),
            CTypeKind::Short => Ok(mk().path_ty(mk().path(vec!["libc", "c_short"]))),
            CTypeKind::Int => Ok(mk().path_ty(mk().path(vec!["libc", "c_int"]))),
            CTypeKind::Long => Ok(mk().path_ty(mk().path(vec!["libc", "c_long"]))),
            CTypeKind::LongLong => Ok(mk().path_ty(mk().path(vec!["libc", "c_longlong"]))),
            CTypeKind::UShort => Ok(mk().path_ty(mk().path(vec!["libc", "c_ushort"]))),
            CTypeKind::UInt => Ok(mk().path_ty(mk().path(vec!["libc", "c_uint"]))),
            CTypeKind::ULong => Ok(mk().path_ty(mk().path(vec!["libc", "c_ulong"]))),
            CTypeKind::ULongLong => Ok(mk().path_ty(mk().path(vec!["libc", "c_ulonglong"]))),
            CTypeKind::SChar => Ok(mk().path_ty(mk().path(vec!["libc", "c_schar"]))),
            CTypeKind::UChar => Ok(mk().path_ty(mk().path(vec!["libc", "c_uchar"]))),
            CTypeKind::Char => Ok(mk().path_ty(mk().path(vec!["libc", "c_char"]))),
            CTypeKind::Double => Ok(mk().path_ty(mk().path(vec!["libc", "c_double"]))),
            CTypeKind::LongDouble => Ok(mk().path_ty(mk().path(vec!["f128", "f128"]))),
            CTypeKind::Float => Ok(mk().path_ty(mk().path(vec!["libc", "c_float"]))),
            CTypeKind::Int128 => Ok(mk().path_ty(mk().path(vec!["i128"]))),
            CTypeKind::UInt128 => Ok(mk().path_ty(mk().path(vec!["u128"]))),

            CTypeKind::Pointer(qtype) => self.convert_pointer(ctxt, qtype),

            CTypeKind::Elaborated(ref ctype) => self.convert(ctxt, *ctype),
            CTypeKind::Decayed(ref ctype) => self.convert(ctxt, *ctype),
            CTypeKind::Paren(ref ctype) => self.convert(ctxt, *ctype),

            CTypeKind::Struct(decl_id) => {
                let new_name = self
                    .resolve_decl_name(decl_id)
                    .ok_or_else(|| format_err!("Unknown decl id {:?}", decl_id))?;
                Ok(mk().path_ty(mk().path(vec![new_name])))
            }

            CTypeKind::Union(decl_id) => {
                let new_name = self.resolve_decl_name(decl_id).unwrap();
                Ok(mk().path_ty(mk().path(vec![new_name])))
            }

            CTypeKind::Enum(decl_id) => {
                let new_name = self.resolve_decl_name(decl_id).unwrap();
                Ok(mk().path_ty(mk().path(vec![new_name])))
            }

            CTypeKind::Typedef(decl_id) => {
                let new_name = self.resolve_decl_name(decl_id).unwrap();
                Ok(mk().path_ty(mk().path(vec![new_name])))
            }

            CTypeKind::ConstantArray(element, count) => {
                let ty = self.convert(ctxt, element)?;
                Ok(mk().array_ty(
                    ty,
                    mk().lit_expr(mk().int_lit(count as u128, LitIntType::Unsuffixed)),
                ))
            }

            CTypeKind::IncompleteArray(element) => {
                let ty = self.convert(ctxt, element)?;
                let zero_lit = mk().int_lit(0, LitIntType::Unsuffixed);
                let zero = mk().lit_expr(zero_lit);
                Ok(mk().array_ty(ty, zero))
            }

            CTypeKind::VariableArray(mut elt, _) => {
                while let CTypeKind::VariableArray(elt_, _) = ctxt.resolve_type(elt).kind {
                    elt = elt_
                }
                let child_ty = self.convert(ctxt, elt)?;
                Ok(mk().mutbl().ptr_ty(child_ty))
            }

            CTypeKind::Attributed(ty, _) => self.convert(ctxt, ty.ctype),

            CTypeKind::Function(ret, ref params, is_var, is_noreturn, true) => {
                let opt_ret = if is_noreturn { None } else { Some(ret) };
                let fn_ty = self.convert_function(ctxt, opt_ret, params, is_var)?;
                Ok(fn_ty)
            }

            CTypeKind::TypeOf(ty) => self.convert(ctxt, ty),

            ref t => Err(format_err!("Unsupported type {:?}", t).into()),
        }
    }
}