Skip to content

Instantly share code, notes, and snippets.

@klutzy
Last active Dec 23, 2015
Embed
What would you like to do?
for extern "C++"
extern mod syntax;
extern mod rustc;
pub use syntax::ast;
pub use rustc::middle::ty;
pub use rustc::middle::ty::t;
fn cpp_arg_mangle(arg: t) -> ~str {
let arg = ty::get(arg);
match arg.sty {
ty::ty_nil => ~"v",
ty::ty_bool => ~"b",
ty::ty_char => ~"c",
ty::ty_int(ast::ty_i) => ~"i",
ty::ty_uint(ast::ty_u) => ~"j",
ty::ty_ptr(tm) => {
let pref = if tm.mutbl == ast::MutImmutable {
~"PK"
} else {
~"P"
};
pref + cpp_arg_mangle(tm.ty)
},
_ => fail!("not implemented"),
}
}
pub fn cpp_mangle(name: &str, inputs: &[t], _output: t) -> ~str {
let prefix = "_Z";
let fn_name = name.len().to_str() + name; //source-name
let mut bare_fn_ty = ~"";
for i in inputs.iter() {
bare_fn_ty = bare_fn_ty + cpp_arg_mangle(*i);
}
let encoding = fn_name + bare_fn_ty;
prefix + encoding
}
fn main() {
}
#[cfg(test)]
mod test {
use super::*;
struct Ctxt {
ts: ~[@ty::t_box_],
}
impl Ctxt {
fn new() -> Ctxt {
Ctxt { ts: ~[] }
}
}
fn mk_ptr(c: &mut Ctxt, t: ty::t, is_mut: bool) -> t {
let is_mut = if is_mut {
ast::MutMutable
} else {
ast::MutImmutable
};
let p = @ty::t_box_ {
sty: ty::ty_ptr(ty::mt {
ty: t,
mutbl: is_mut,
}),
id: 0,
flags: 0,
};
c.ts.push(p);
let p = unsafe { std::cast::transmute(&*p) };
p
}
fn test_func(inputs: &[t], output: t, expected: ~str) {
let name = cpp_mangle("func", inputs, output);
assert_eq!(name, expected);
}
#[test]
fn test_int_int() {
// int func(int, int)
let output = ty::mk_int();
let inputs = ~[ty::mk_int(), ty::mk_int()];
let expected = ~"_Z4funcii";
test_func(inputs, output, expected);
}
#[test]
fn test_intp() {
// int func(int*, const int*)
let mut ctx = ~Ctxt::new();
let output = ty::mk_int();
let intp = mk_ptr(ctx, ty::mk_int(), true);
let intpk = mk_ptr(ctx, ty::mk_int(), false);
let inputs = ~[intp, intpk];
let expected = ~"_Z4funcPiPKi";
test_func(inputs, output, expected);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment