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

Minimum signed integer literal #779

Closed
Coder-256 opened this issue Mar 11, 2020 · 5 comments
Closed

Minimum signed integer literal #779

Coder-256 opened this issue Mar 11, 2020 · 5 comments

Comments

@Coder-256
Copy link

Coder-256 commented Mar 11, 2020

In the section about integer literals, the Reference says:

Note that the Rust syntax considers -1i8 as an application of the unary minus operator to an integer literal 1i8, rather than a single integer literal.

However, this is a bit misleading due to the way Rust handles literals that are "out of range": values like -128i8 actually work (due to const eval?). AFAIK you can use any integer literal in the range [0, 2^128) as long as it evaluates to something in range, but either way things get a bit weird. For example:

Playground

fn main() {
    println!("{}", -128i8); // prints -128
    println!("{}", -(128i8)); // prints -128
    // println!("{}", -(126i8 + 2)); // error: attempt to add with overflow
    // let x = 128i8; // error: literal out of range for `i8`
}
@ehuss
Copy link
Contributor

ehuss commented Mar 12, 2020

Yea, I see how that could be confusing. I think the key point is that it is treated that way at the syntactic level (here is the parser where it is immediately interpreted as unary operator). At the semantic level it has a particular meaning which is AFAIK undocumented.

One situation where it really matters is for a macro consuming tokens. -128i8 is two tokens. I can't think of any other way it matters, but there's probably something.

I'm not sure where/how this should be described. Maybe something in Negation operators? I don't really know how constants work internally.

@Centril
Copy link
Contributor

Centril commented Apr 8, 2020

cc @oli-obk

@oli-obk
Copy link
Contributor

oli-obk commented Apr 9, 2020

While the parser and the AST consider -128i8 to be Neg(Lit(128, i8)), there is a specific conversion for exactly the pattern Neg(Lit(...)) to a constant, that's why you get the diagnostics you've posted.

@mattheww
Copy link
Contributor

I think this issue is resolved by #1177 and #1188

@ehuss
Copy link
Contributor

ehuss commented Apr 18, 2022

Thanks! Yea, I think those should cover the negation behavior.

@ehuss ehuss closed this as completed Apr 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants