Skip to content

Commit eebd633

Browse files
committed
[gen.rs] Improve const_to_rs.
1 parent 05a46b5 commit eebd633

File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed

src/gen.rs

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ fn extract_definitions(ctx: &mut GenCtx,
144144
GVar(ref vi) => {
145145
let v = vi.borrow();
146146
let ty = cty_to_rs(ctx, &v.ty);
147-
defs.push(const_to_rs(ctx, v.name.clone(), v.val.unwrap(), ty));
147+
defs.push(const_to_rs(ctx, &v.name, v.val.unwrap(), ty));
148148
},
149149
_ => { }
150150
}
@@ -675,25 +675,31 @@ fn cunion_to_rs(ctx: &mut GenCtx, name: String, derive_debug: bool, layout: Layo
675675
items
676676
}
677677

678-
fn const_to_rs(ctx: &mut GenCtx, name: String, val: i64, val_ty: ast::Ty) -> P<ast::Item> {
679-
let int_lit = ast::LitKind::Int(
680-
val.abs() as u64,
681-
ast::LitIntType::Unsuffixed
682-
);
683-
let mut value = ctx.ext_cx.expr_lit(ctx.span, int_lit);
684-
if val < 0 {
685-
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, value);
686-
value = ctx.ext_cx.expr(ctx.span, negated);
678+
/// Converts a signed number to AST Expression.
679+
fn i64_to_int_lit(ctx: &mut GenCtx, value: i64) -> P<ast::Expr> {
680+
let int_lit = ast::LitKind::Int(value.abs() as u64,
681+
ast::LitIntType::Unsuffixed);
682+
let expr = ctx.ext_cx.expr_lit(ctx.span, int_lit);
683+
if value < 0 {
684+
let negated = ast::ExprKind::Unary(ast::UnOp::Neg, expr);
685+
ctx.ext_cx.expr(ctx.span, negated)
686+
} else {
687+
expr
687688
}
689+
}
688690

689-
let cst = ast::ItemKind::Const(
690-
P(val_ty),
691-
value
692-
);
691+
/// Converts a C const to Rust AST.
692+
fn const_to_rs(ctx: &mut GenCtx,
693+
name: &str,
694+
val: i64,
695+
val_ty: ast::Ty) -> P<ast::Item> {
696+
let int_lit = i64_to_int_lit(ctx, val);
693697

694-
let id = rust_id(ctx, &name).0;
698+
let cst = ast::ItemKind::Const(P(val_ty), int_lit);
699+
700+
let id = rust_id(ctx, name).0;
695701
P(ast::Item {
696-
ident: ctx.ext_cx.ident_of(&id[..]),
702+
ident: ctx.ext_cx.ident_of(&id),
697703
attrs: Vec::new(),
698704
id: ast::DUMMY_NODE_ID,
699705
node: cst,

0 commit comments

Comments
 (0)