Skip to content

Commit 080766e

Browse files
committed
Implement remaining wrapping operations
cc rust-lang/rust#24420
1 parent 17d69e8 commit 080766e

File tree

3 files changed

+13
-14
lines changed

3 files changed

+13
-14
lines changed

Diff for: README.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@ A macro for wrapping arithmetic.
44

55
Any code within a `wrapping! { .. }` block will be transformed as follows:
66

7-
* `a + b` becomes `a.wrapping_add(b)`. Similarly for `-` and `*`.
8-
* `a += b` becomes `a = a.wrapping_add(b)`. Similarly for `-=` and `*=`.
9-
* `-a` becomes `a.wrapping_mul(!0)`.
7+
* `a + b` becomes `a.wrapping_add(b)`. Similarly for `-`, `*`, `/`, `%`, `<<`, `>>`.
8+
* `a += b` becomes `a = a.wrapping_add(b)`. Similarly for `-=`, `*=`, `/=`, `%=`, `<<=`, `>>=`.
9+
* `-a` becomes `a.wrapping_neg()`.
1010

1111
See [this Internals thread][1] for the motivation behind this crate.
1212

Diff for: src/lib.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@ extern crate rustc;
77
use std::borrow::ToOwned;
88
use std::rc::Rc;
99
use syntax::ast::{
10-
BinOp_, BiAdd, BiSub, BiMul, Delimited,
11-
Expr, ExprAssign, ExprAssignOp, ExprBinary, ExprUnary,
12-
LitInt, UnsuffixedIntLit, Sign, UnNeg, UnNot,
10+
BinOp_, BiAdd, BiSub, BiMul, BiDiv, BiRem, BiShl, BiShr, UnNeg,
11+
Delimited, Expr, ExprAssign, ExprAssignOp, ExprBinary, ExprUnary,
1312
Ident, Mac, TokenTree, TtDelimited
1413
};
1514
use syntax::codemap::{DUMMY_SP, Span};
@@ -35,14 +34,9 @@ impl<'cx> Folder for WrappingFolder<'cx> {
3534
ExprUnary(UnNeg, inner) => {
3635
// Recurse in sub-expressions
3736
let inner = self.fold_expr(inner);
38-
// Rewrite `-a` to `a.wrapping_mul(!0)`
39-
// This is equivalent to `a.wrapping_mul(-1)`, except it
40-
// works on unsigned types as well
41-
let method = token::str_to_ident("wrapping_mul");
42-
let zero = self.cx.expr_lit(
43-
DUMMY_SP, LitInt(0, UnsuffixedIntLit(Sign::Plus)));
44-
let neg_one = self.cx.expr_unary(DUMMY_SP, UnNot, zero);
45-
self.cx.expr_method_call(expr.span, inner, method, vec![neg_one])
37+
// Rewrite `-a` to `a.wrapping_neg()`
38+
let method = token::str_to_ident("wrapping_neg");
39+
self.cx.expr_method_call(expr.span, inner, method, vec![])
4640
.and_then(|e| e)
4741
}
4842
ExprBinary(op, left, right) => {
@@ -87,6 +81,10 @@ fn wrapping_method(op: BinOp_) -> Option<Ident> {
8781
BiAdd => "wrapping_add",
8882
BiSub => "wrapping_sub",
8983
BiMul => "wrapping_mul",
84+
BiDiv => "wrapping_div",
85+
BiRem => "wrapping_rem",
86+
BiShl => "wrapping_shl",
87+
BiShr => "wrapping_shr",
9088
_ => return None,
9189
}))
9290
}

Diff for: tests/tests.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#![feature(core)]
12
#![feature(plugin)]
23
#![plugin(wrapping_macros)]
34

0 commit comments

Comments
 (0)