Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle negative literals a bit better #65

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 48 additions & 1 deletion src/to_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use super::Tokens;
use std::borrow::Cow;

use proc_macro2::{Literal, Span, Term, TokenNode, TokenTree, TokenStream};
use proc_macro2::{Spacing, Delimiter};

fn tt(kind: TokenNode) -> TokenTree {
TokenTree {
Expand Down Expand Up @@ -126,8 +127,54 @@ macro_rules! primitive {
}

primitive! {
i8 i16 i32 i64 isize
u8 u16 u32 u64 usize
}

macro_rules! signed_primitive {
($($t:ident)*) => ($(
impl ToTokens for $t {
fn to_tokens(&self, tokens: &mut Tokens) {
let val = if *self == <$t>::min_value() {
let mut sub_tokens = Tokens::new();
(*self as u64).to_tokens(&mut sub_tokens);
sub_tokens.append(tt(TokenNode::Term(Term::intern("as"))));
sub_tokens.append(tt(TokenNode::Term(Term::intern(stringify!($t)))));
let sub_tokens = sub_tokens.into();
tokens.append(tt(TokenNode::Group(Delimiter::Parenthesis, sub_tokens)));
return
} else if *self < 0 {
tokens.append(tt(TokenNode::Op('-', Spacing::Alone)));
self.abs()
} else {
*self
};
tokens.append(tt(TokenNode::Literal(Literal::$t(val))));
}
}
)*)
}

signed_primitive! {
i8 i16 i32 i64 isize
}

macro_rules! float_primitive {
($($t:ident)*) => ($(
impl ToTokens for $t {
fn to_tokens(&self, tokens: &mut Tokens) {
let val = if *self < 0.0 {
tokens.append(tt(TokenNode::Op('-', Spacing::Alone)));
-*self
} else {
*self
};
tokens.append(tt(TokenNode::Literal(Literal::$t(val))));
}
}
)*)
}

float_primitive! {
f32 f64
}

Expand Down
16 changes: 15 additions & 1 deletion tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ fn test_integer() {
#ii8 #ii16 #ii32 #ii64 #iisize
#uu8 #uu16 #uu32 #uu64 #uusize
};
let expected = "-1i8 -1i16 -1i32 -1i64 -1isize 1u8 1u16 1u32 1u64 1usize";
let expected = "- 1i8 - 1i16 - 1i32 - 1i64 - 1isize 1u8 1u16 1u32 1u64 1usize";
assert_eq!(expected, tokens.to_string());
}

Expand Down Expand Up @@ -290,3 +290,17 @@ fn test_append_tokens() {
a.append_all(b);
assert_eq!("a b", a.to_string());
}

#[test]
fn negative_integers() {
let a = -1i32;
let a = quote!(#a);
assert_eq!("- 1i32", a.to_string());
}

#[test]
fn negative_min() {
let a = -128i8;
let a = quote!(#a);
assert_eq!("( 18446744073709551488u64 as i8 )", a.to_string());
}