[go: up one dir, main page]

cpp 0.0.3

Write C++ code inline in your rust code!
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::collections::HashSet;
use std::mem;

use syntax::ast::{self, Expr, DefId, NodeId, MetaNameValue, LitStr};
use syntax::ast::IntTy::*;
use syntax::ast::UintTy::*;
use syntax::ast::FloatTy::*;
use syntax::attr::*;
use syntax::codemap::Span;

use rustc::middle::ty::*;
use rustc::lint::{Context, Level};

declare_lint!(pub BAD_CXX_TYPE, Warn, "Unable to translate type to C++");

struct DeferredStruct {
    defid: DefId,
    nid: (NodeId, Span),
}

impl DeferredStruct {
    fn run(self, td: &mut TypeData, tcx: &ctxt) -> TypeName {
        let struct_def = tcx.lookup_adt_def(self.defid);

        let (ns_before, ns_after, name, path) = explode_path(tcx, self.defid);
        let mut tn = TypeName::new(path);

        let mut defn = format!("struct {} {{\n", &name);
        for fdd in struct_def.all_fields() {
            let ty = cpp_type_of_internal(td, tcx, self.nid, fdd.unsubst_ty(), false);

            // Add the field, merging any errors into our TypeName
            defn.push_str(&format!("    {} {};\n", &tn.merge(ty), &fdd.name));
        }
        defn.push_str("};");

        // If we have any errors, we shouldn't write out our declaration,
        // as it won't be valid.
        if tn.err.len() == 0 {
            td.decls.push_str(&format!("{}\n{}\n{}", ns_before, defn, ns_after));
        }

        tn
    }
}

pub struct TypeData {
    decls: String,
    queue: Vec<DeferredStruct>,
    declared: HashSet<String>,
}

impl TypeData {
    pub fn new() -> TypeData {
        TypeData {
            decls: String::new(),
            queue: Vec::new(),
            declared: HashSet::new(),
        }
    }

    pub fn to_cpp(&mut self, cx: &Context) -> String {
        while self.queue.len() != 0 {
            let mut todo = Vec::new();
            mem::swap(&mut todo, &mut self.queue);

            // Run each of the callbacks, and report any errors
            for cb in todo {
                let mut tn = cb.run(self, cx.tcx);
                tn.recover();
                tn.into_name(cx);
            }
        }
        // XXX Process queue here
        self.decls.clone()
    }
}

#[derive(Debug, Clone)]
struct TypeNameNote {
    msg: String,
    span: Option<Span>,
}

#[derive(Debug, Clone)]
struct TypeNameProblem {
    msg: String,
    span: Option<Span>,
    notes: Vec<TypeNameNote>,
}

#[derive(Debug, Clone)]
pub struct TypeName {
    name: String,
    warn: Vec<TypeNameProblem>,
    err: Vec<TypeNameProblem>,
}

impl TypeName {
    fn new(s: String) -> TypeName {
        TypeName {
            name: s,
            warn: Vec::new(),
            err: Vec::new(),
        }
    }

    fn from_str(s: &str) -> TypeName {
        TypeName::new(format!("{}", s))
    }

    fn error(err: String, span: Option<Span>) -> TypeName {
        TypeName {
            name: format!("rs::__Dummy"),
            warn: Vec::new(),
            err: vec![TypeNameProblem {
                msg: err,
                span: span,
                notes: Vec::new(),
            }],
        }
    }

    pub fn into_name(self, cx: &Context) -> String {
        if self.err.len() == 0 {
            for warn in &self.warn {
                if cx.current_level(BAD_CXX_TYPE) != Level::Allow {
                    if let Some(span) = warn.span {
                        cx.span_lint(BAD_CXX_TYPE, span, &warn.msg);
                    } else {
                        cx.lint(BAD_CXX_TYPE, &warn.msg);
                    }

                    cx.sess().note("C++ code will recieve an opaque reference");

                    for note in &warn.notes {
                        if let Some(span) = note.span {
                            cx.sess().span_note(span, &note.msg);
                        } else {
                            cx.sess().note(&note.msg);
                        }
                    }
                }
            }
        } else {
            for err in &self.err {
                if let Some(span) = err.span {
                    cx.sess().span_err(span, &err.msg);
                } else {
                    cx.sess().err(&err.msg);
                }

                cx.sess().note("This type can't be passed by value, and thus \
                                is an invalid return type");

                for note in &err.notes {
                    if let Some(span) = note.span {
                        cx.sess().span_note(span, &note.msg);
                    } else {
                        cx.sess().note(&note.msg);
                    }
                }
            }

            // Don't bother reporting warnings if we are going to fail
            // Just report the errors
        }

        self.name
    }

    pub fn with_note(mut self, msg: String, span: Option<Span>) -> TypeName {
        for warn in &mut self.warn {
            warn.notes.push(TypeNameNote {
                msg: msg.clone(),
                span: span,
            });
        }
        for err in &mut self.err {
            err.notes.push(TypeNameNote {
                msg: msg.clone(),
                span: span,
            });
        }
        self
    }

    pub fn with_warn(mut self, msg: String, span: Option<Span>) -> TypeName {
        self.warn.push(TypeNameProblem {
            msg: msg,
            span: span,
            notes: Vec::new(),
        });
        self
    }

    pub fn with_name(mut self, name: String) -> TypeName {
        self.name = name;
        self
    }

    pub fn map_name<F>(self, f: F) -> TypeName where F: FnOnce(String) -> String {
        let TypeName{ name, warn, err } = self;
        let name = f(name);
        TypeName{ name: name, warn: warn, err: err }
    }

    pub fn merge(&mut self, other: TypeName) -> String {
        let TypeName{ name, warn, err } = other;

        for it in warn { self.warn.push(it) }
        for it in err { self.err.push(it) }
        name
    }

    /// This method is called when it is possible to require from
    /// typename generation problems. If there are any errors,
    /// they are converted into warnings, and true is returned.
    /// otherwise, false is returned.
    pub fn recover(&mut self) -> bool {
        if self.err.len() == 0 { return false }

        let mut err = Vec::new();
        mem::swap(&mut self.err, &mut err);
        for e in err {
            self.warn.push(e);
        }

        true
    }
}

/// Takes the defid of a struct or enum, and produces useful strings for generating the C++ code
/// the results are as follows:
/// ns_before: The `namespace foo {` declarations which should be placed before the declaration
/// ns_after: The `}` declarations which should be placed after the declaration
/// name: The name of the struct or enum itself
/// path: The fully qualified path in C++ which the struct/enum should exist at
fn explode_path(tcx: &ctxt, defid: DefId) -> (String, String, String, String) {
    let mut ns_before = String::new();
    let mut ns_after = String::new();
    let mut name = String::new();
    let mut path = format!("::rs::");

    tcx.with_path(defid, |segs| {
        let mut segs_vec: Vec<_> = segs.map(|x| x.name()).collect();

        name = format!("{}", segs_vec.pop().unwrap().as_str());
        for seg in segs_vec {
            ns_before.push_str(&format!("namespace {} {{", seg.as_str()));
            ns_after.push_str("}\n");
            path.push_str(&format!("{}::", seg.as_str()));
        }
        path.push_str(&name);
    });

    (ns_before, ns_after, name, path)
}


fn cpp_type_attr_check(tcx: &ctxt, defid: DefId, rs_ty: Ty) -> Option<TypeName> {
    let attrs = tcx.get_attrs(defid);
    for attr in &*attrs {
        let metaitem = &attr.node.value.node;
        if let MetaNameValue(ref name, ref value) = *metaitem {
            if *name == "cpp_type" {
                return if let LitStr(ref s, _) = value.node {
                    Some(TypeName::from_str(s))
                } else {
                    // Error
                    Some(TypeName::error(format!("Struct type {} has a #[cpp_type] \
                                                  annotation, but it's value isn't \
                                                  a string", rs_ty), None))
                }
            }
        }
    }
    None
}

/// Determine the c++ type for a given expression
/// This is the entry point for the types module, and is the intended mechanism for
/// invoking the type translation infrastructure.
pub fn cpp_type_of<'tcx>(td: &mut TypeData,
                         tcx: &ctxt<'tcx>,
                         expr: &Expr,
                         is_arg: bool) -> TypeName {
    // Get the type object
    let rs_ty = tcx.expr_ty(expr);

    if !is_arg {
        // Special case for void return value
        if let TyTuple(ref it) = rs_ty.sty {
            if it.len() == 0 {
                return TypeName::from_str("void");
            }
        }
    }

    cpp_type_of_internal(td, tcx, (expr.id, expr.span), rs_ty, is_arg)
}

fn cpp_type_of_internal<'tcx>(td: &mut TypeData,
                              tcx: &ctxt<'tcx>,
                              nid: (NodeId, Span),
                              rs_ty: Ty<'tcx>,
                              in_ptr: bool) -> TypeName {
    match rs_ty.sty {
        TyBool => TypeName::from_str("::rs::bool_"),

        TyInt(TyIs) => TypeName::from_str("::rs::isize"),
        TyInt(TyI8) => TypeName::from_str("::rs::i8"),
        TyInt(TyI16) => TypeName::from_str("::rs::i16"),
        TyInt(TyI32) => TypeName::from_str("::rs::i32"),
        TyInt(TyI64) => TypeName::from_str("::rs::i64"),

        TyUint(TyUs) => TypeName::from_str("::rs::usize"),
        TyUint(TyU8) => TypeName::from_str("::rs::u8"),
        TyUint(TyU16) => TypeName::from_str("::rs::u16"),
        TyUint(TyU32) => TypeName::from_str("::rs::u32"),
        TyUint(TyU64) => TypeName::from_str("::rs::u64"),

        TyFloat(TyF32) => TypeName::from_str("::rs::f32"),
        TyFloat(TyF64) => TypeName::from_str("::rs::f64"),

        TyRawPtr(TypeAndMut { ref ty, .. }) |
        TyRef(_, TypeAndMut { ref ty, .. }) |
        TyBox(ref ty) => {
            // We need to know if the type is Sized.
            // !Sized pointers are twice as wide as Sized pointers.
            if ty.is_sized(&ParameterEnvironment::for_item(tcx, nid.0), nid.1) {
                // We try to get the internal type - if that doesn't work out it's OK
                let mut cpp_ty = cpp_type_of_internal(td, tcx, nid, ty, true);

                // If we had a problem generating the type, make the errors warnings,
                // and emit the type void*
                if cpp_ty.recover() {
                    cpp_ty.with_name(format!("void*"))
                } else {
                    cpp_ty.map_name(|name| format!("{}*", &name))
                }
            } else {
                // It's a trait object or slice!
                match ty.sty {
                    TyStr => TypeName::from_str("::rs::StrSlice"),
                    TySlice(ref it_ty) => {
                        let mut cpp_ty = cpp_type_of_internal(td, tcx, nid, it_ty, true);

                        if cpp_ty.recover() {
                            cpp_ty.with_name(format!("::rs::Slice<void>"))
                        } else {
                            cpp_ty.map_name(|name| format!("::rs::Slice< {} >", &name))
                        }
                    }

                    // Unsized types which aren't slices are trait objects of some type.
                    // We don't want to go out of our way to support them,
                    // but we return the correct width of pointer to keep layout correct.
                    _ => {
                        TypeName::from_str("::rs::TraitObject")
                            .with_warn(format!("Type {} is an unsized type which cannot \
                                                currently be translated to C++", ty),
                                       None)
                    },
                }
            }
        }

        TyEnum(edef, _) => {
            let defid = edef.did;
            if let Some(tn) = cpp_type_attr_check(tcx, defid, rs_ty) {
                return tn;
            }

            if edef.is_payloadfree() {
                let repr_hints = tcx.lookup_repr_hints(defid);

                // Ensure that there is exactly 1 item in repr_hints
                if repr_hints.len() == 0 {
                    return TypeName::error(format!("Enum type {} does not have a #[repr(_)] annotation.",
                                                   rs_ty), None)
                        .with_note(format!("Consider annotating it with #[repr(C)]"), None);
                } else if repr_hints.len() > 1 {
                    return TypeName::error(format!("Enum type {} has multiple #[repr(_)] annotations",
                                                   rs_ty), None);
                }

                let (ns_before, ns_after, name, path) = explode_path(tcx, defid);
                let tn = TypeName::new(path);
                if td.declared.contains(&name) { return tn; }

                let mut defn = format!("enum class {}", &name);

                // Determine the representation of the enum class
                match repr_hints[0] {
                    ReprExtern => {
                        // #[repr(C)] => representation is the default!
                    }
                    ReprInt(_, ity) => {
                        // #[repr(int_type)] => representation is the int_type!
                        let repr = match ity {
                            SignedInt(ast::TyI8) => "::rs::i8",
                            UnsignedInt(ast::TyU8) => "::rs::u8",
                            SignedInt(ast::TyI16) => "::rs::i16",
                            UnsignedInt(ast::TyU16) => "::rs::u16",
                            SignedInt(ast::TyI32) => "::rs::i32",
                            UnsignedInt(ast::TyU32) => "::rs::u32",
                            SignedInt(ast::TyI64) => "::rs::i64",
                            UnsignedInt(ast::TyU64) => "::rs::u64",
                            SignedInt(ast::TyIs) => "::rs::isize",
                            UnsignedInt(ast::TyUs) => "::rs::usize",
                        };

                        defn.push_str(&format!(" : {}", repr));
                    }
                    _ => {
                        return TypeName::error(format!("Enum type {} has unsupported #[repr(_)] annotation",
                                                       rs_ty), None);
                    }
                }

                defn.push_str(" {\n");
                for variant in &edef.variants {
                    defn.push_str(&format!("    {} = {},\n",
                                           variant.name.as_str(), variant.disr_val));
                }
                defn.push_str("};");

                // Record the declaration, and define the type
                td.decls.push_str(&format!("{}\n{}\n{}", ns_before, defn, ns_after));
                td.declared.insert(name);
                tn
            } else {
                TypeName::error(format!("Enum type {} is not a C-like enum", rs_ty), None)
            }
        }

        TyStruct(sdef, substs) => {
            let defid = sdef.did;
            if let Some(tn) = cpp_type_attr_check(tcx, defid, rs_ty) {
                return tn;
            }

            let repr_hints = tcx.lookup_repr_hints(defid);

            // Ensure that there is exactly 1 item in repr_hints, and that it is #[repr(C)]
            if repr_hints.len() == 0 {
                return TypeName::error(format!("Struct type {} does not have a #[repr(_)] annotation",
                                               rs_ty), None)
                    .with_note(format!("Consider annotating it with #[repr(C)]"), None);
            } else if repr_hints.len() > 1 {
                return TypeName::error(format!("Struct type {} has multiple #[repr(_)] annotations",
                                               rs_ty), None);
            } else if repr_hints[0] != ReprExtern {
                return TypeName::error(format!("Struct type {} has an unsupported #[repr(_)] annotation",
                                               rs_ty), None);
            }

            // We don't support structs with substitutions (generic type parameters)
            if !substs.types.is_empty() {
                return TypeName::error(format!("Struct type {} has generic type parameters, \
                                                which are not supported",
                                               rs_ty), None);
            }

            let (ns_before, ns_after, name, path) = explode_path(tcx, defid);
            let tn = TypeName::new(path);
            if td.declared.contains(&name) { return tn; }

            let deferred = DeferredStruct {
                defid: defid,
                nid: nid,
            };

            if in_ptr {
                td.decls.push_str(&format!("{}\nstruct {};\n{}",
                                           ns_before, &name, ns_after));
                td.queue.push(deferred);
            } else {
                deferred.run(td, tcx);
            }

            td.declared.insert(name);
            tn
        }

        // Unsupported types
        _ => {
            TypeName::error(format!("The type {} cannot be passed between C++ and rust",
                                    rs_ty), None)
        }
    }
}