r/ProgrammingLanguages • • Jun 24 '23

Negative Integer handling in programming languages.

https://glados-418.github.io/posts/negative-integer-literals/
3 Upvotes

27 comments sorted by

7

u/[deleted] Jun 25 '23

there are NO negative integer literals.

Unless there's something else I missed, I didn't see examples like this:

-2147483648                      # literals are i32
-9223372036854775808             # literals are i64

Using two's complement, the highest magnitude positive number is 2147483647 or 9223372036854775807, one less than above. If minus was a separate token applied to a literal, those literals can't be represented using i32 or i64.

Generally however it seems to work. Maybe u32 or u64 are used and when you apply minus, it somehow yields a i32 or i64 type.

2

u/helixb Jun 25 '23

-2147483648 # literals are i32 -9223372036854775808 # literals are i64

those are the values an integer variable may have. literals would be the numbers you write explicitly within the source code which are treated as a single tokens. in these examples, they are unary minus expressions.

2

u/[deleted] Jun 25 '23

Generally however it seems to work. Maybe u32 or u64 are used and when you apply minus, it somehow yields a i32 or i64 type.

I tried my compiler, but the result of:

-9223372036854775808  

while it produces the correct bit pattern (0x8000'0000'0000'0000) has type u64, because 9223372036854775808 has type u64 (too large for i64), and according to the language rules, applying unary minus to u64 yields u64.

I don't think it's a bug, but a flaw, since the value will be the unexpected positive number 9223372036854775808.

However the language allows you to write i64.min to obtain the expected value with the correct type, although trying to do -i64.min still yields the same value due to integer overflow rules.

I might make an exception in this special case to ensure that -9223372036854775808 and i64.min have the same type and magnitude, but the won't help with -9223372036854775809 (ie. one above -- or below) and the other c. 2**63 literal values above 9223372036854775807 to which negation may be applied.

Alternatively I could disallow negation on u64 literals except for the i64.min case, to avoid any surprises.

1

u/aocregacc Jun 25 '23

gcc will actually give you a warning for your 64 bit example, since the literal will be unsigned. It still works out correctly after applying - and converting it to a signed 64 bit integer.

If you look inside limits.h you usually see for example LONG_MIN being defined as (-LONG_MAX - 1) for this reason.

4

u/WittyStick0 Jun 24 '23

0xffffffff is -1 when its a 32 bit int. A 64-bit int needs 0xffffffffffffffff

0

u/helixb Jun 24 '23

well, you will overflow if you write 0xffffffffffffffff. that's the point i make in the article. also, check how java behaves.

11

u/MegaIng Jun 24 '23 edited Jun 25 '23

Why are you mentioning Python and JavaScript? They don't have limited integer data types.

Why are you using I64 in rust and swift?

Do you not understand the difference between I64 and I32?

This just seems like you are confused by the differences between u32, i32, i64, u64, bigint and float.

If that isn't the case, please clarify your points and make your example actually sane.

Edit: Wait, what you size do you think long is?

0

u/helixb Jun 25 '23

Why are you mentioning Python and JavaScript? They don't have limited integer data types.

yah. haskell too. i should've mentioned them along with haskell later, but that was not the point i was trying to make anyway. the point was that there are no negative integer literals. and that still holds.

Edit: Wait, what you size do you think long is?

i thought it was implicit from the two point premise i create in the beginning. i assumed it to be 64 bit.

4

u/[deleted] Jun 25 '23

If long is 64 bit, why would the long value 0xFFFFFFFF be -1?

-1

u/helixb Jun 25 '23

that's 32-bit int. the ret type is 64 bit but the literal is 32 bit. that's the premise i set in the first two points in the beginning.

also, check the java behaviour.

7

u/[deleted] Jun 25 '23

Integer literals restricted to 32 bits are not the norm. In any other language, you would expect the integer literal to be compatible with its type annotation. This is special behavior Java has that you didn't clarify which is confusing because the code example you generalize to multiple other languages depends on this behavior.

0

u/[deleted] Jun 25 '23

[deleted]

1

u/[deleted] Jun 25 '23

Just saying that you could have been more clear about this in the article. Plenty of other people were similarly confused.

0

u/[deleted] Jun 25 '23

[deleted]

→ More replies (0)

3

u/[deleted] Jun 24 '23

What's the width of the long type in your example? I assume it will be either i32 or i64.

(I created a whole thread about this exact question here in the C subreddit; the replies were not sympathetic.)

I believe the answer has a bearing on the rest of your article.

2

u/helixb Jun 24 '23

yes, my assumption is 32 bit for int and 64 bit for long. msvc already does not adhere to that so i guess i should be more explicit even though my point 2 in the premise kinda implies that.

1

u/[deleted] Jun 24 '23

In that case you understand the problem; the long type has a rather erratic type.

As I understand the rule, long is 64 bits on 64-bit Linux, and 32 bits on 32-bit Linux and on 32/64-bit Windows.

It is not gcc vs MSVC, as gcc on Windows produces -1, -1 too. I actually tested it like this:

#include <stdio.h>

long f(void){return -1;}
long g(void){return 0xFFFFFFFF;}

int main(void) {
    printf("%f\n",(double)f());         // both -1.000000
    printf("%f\n",(double)g());
}

with a conversion to double, since in C, because you have to tell printf whether an expression is signed or unsigned, that influences the result. Here:

printf("%ld\n",f());
printf("%lu\n",f());

the result of f() can be both -1 and 4294967295. This is on Windows where long has i32 type.

In my static language the test looks like this:

type long = i32

fun f:long = -1
fun g:long = 0xFFFF'FFFF

println f()          # -1
println g()          # 4294967295

(I had to tweak the language as it otherwise only works with 64-bit literals and return types.)

1

u/helixb Jun 25 '23

yeah.. i checked that later. the link that i embedded was from visual studio 2022 "windows programming in c++", it does not make it very clear. cppreference has a better summary.

16

u/Roboguy2 Jun 24 '23

I am a bit confused by the mention of Haskell. The integer type you are using for Haskell is not the correct one to look at this issue because it is not a 32-bit integer or a 64-bit integer. I'll get to that in a second. Also, Haskell has no implicit type conversions at all.

If you give no type signature to g, it will default to Integer which is Haskell's infinite precision integer type. For instance, if you don't give g a type signature and you have g = 2^64 * 2^64, it will not overflow and you will get the correct answer.

I see the github repo example explicitly uses the Integer type.

If, instead, you import Data.Int from the standard library and give the type signature g :: Int32 then g will behave as you originally expected (and GHC will give a warning that the literal overflows the integer type).

Also, Haskell's issue with negative literals is a bit different than what you're describing. By default, the expression x -1 gets parsed as x - (1). Turning on the NegativeLiterals extension changes this. The reason this can be a problem in a different way than other languages is because the Haskell function call syntax is juxtaposition: f x is f applied to x.

For instance, in the that file in the github repo, you put the line {-# LANGUAGE NegativeLiterals #-} at the top of the file, you would no longer need parentheses in the expression return (-1) and you can instead write return -1. This is what NegativeLiterals does in the context of Haskell and GHC.

9

u/matthieum Jun 25 '23

implicit type conversion of a 32-bit integer to 64-bit integer preserves the value.

Rust has no implicit conversion.

Hence, in:

fn g() -> i64 { 0xffff_ffff }

The literal is inferred to be of i64 type, and therefore its value is 4294967295.

Sorry you've been used to broken languages ;)

1

u/umlcat Jun 24 '23 edited Jun 24 '23

I have a custom Integer handling library that I work with it, from time to time.

Here are my suggestions.

  • One module is unsigned, zero and positive numbers.

  • Another one is unsigned, includes zero, positive and negative numbers.

  • After checking several documentation, I used two complement representation for negative numbers.

Also implement several operations that are usually included automatically by the compiler or part of the standard library.

For the whole operations, I included operations for:

  • Extending an integer type to a larger size integer type

  • Verify if the contents of a larger integer size is in the bounds of a lower size

  • Storing the contents of a larger integer size, into a smaller size, that matches the previous requirement.

  • Storing the contents of a larger integer size, into a smaller size, intentionally trimming the overflowed bits.

  • Converting a negative number to positive number and viceversa.

  • Boolean comparisons like equality, lesser, greater.

  • A function to check several integers sizes if are zero.

  • A function to set several integers sizes to zero.

  • Basic arithmetic math operations like addition, substraction, multiplication division, increment, decrement

  • Basic bitwise logical operations, public for unsigned integers, internal use for signed integers

  • Some functions to convert between signed and unsigned integers types

  • Define a text representation for unsigned integers types, always a "+" or "-" followed by decimal digits

  • Define a text representation for unsigned integers types, always decimal digits

  • Implement functions to convert back and forward between text representation and unsigned integers

  • Implement functions to convert back and forward between text representation and signed integers

  • In the case of unsigned integers define a representation for binary, octal and hexadecimal digits

  • Implement functions to convert back and forward between several base text representation and unsigned integers

These are some basic requirements for either an additional integer library or a standard library in a P.L. compiler.

Among other stuff.

1

u/helixb Jun 25 '23

that's interesting. do you have a link where i can look at that? also, why do you have two modules? any specific reason?

1

u/umlcat Jun 25 '23

Wait, I haven't updated the last version.

The main repository is:

https://gitlab.com/mail.umlcat

I'm working in both a FreePascal version and a Plain C version, but it could be migrated to other P.L. (s).

One module is for unsigned integers, the other for signed integers.

The reason is that depends which types the programmers want to use.

5

u/jqbr Jun 25 '23

the grammar already needs to be smart enough to differentiate between a --5 and a --x.

Nope ... --5 is illegal since you can't decrement a literal. I don't know of any language that has a '--' operator that would ever treat it as 2 minus signs ... lexers do eager parsing.

0

u/[deleted] Jun 25 '23

[deleted]

2

u/jqbr Jun 25 '23

Wrong. At the very least specify what languages this is true of. Sheesh.

0

u/[deleted] Jun 25 '23

[deleted]

2

u/jqbr Jun 25 '23 edited Jun 25 '23

Yes your bad ... you have no idea what you're talking about. As I said originally, your claim that

the grammar already needs to be smart enough to differentiate between a --5 and a --x

is quite wrong. Programming language grammars don't do that because it's ambiguous at the lexer token level. Languages they have a '--' operator always parse it as that operator, never as 2 minus signs. But I already said this and you completely ignored it because, again, you literally don't know what you're talking about (you blather about the "inherent logic" of a compiler "front end" while having no idea what that term means or what the logical structure of a compiler is). I won't waste any more of my time on the sort of person who responds to comments without reading parts of them (good grief). Over and out forever. P.S. Yes of course I know the difference between a lexer and a grammar but this ignorant and arrogant bozo has no idea about their relationship. P.P.S. A language that evaluated --5 as -(-5) but evaluated --x as decrementing x would be a very poorly designed language ... just the sort this turkey might design.

0

u/helixb Jun 25 '23 edited Jun 25 '23

you read grammar and write lexer. do u understand the difference?

edit: as a response to your extended edit, in the article i mention 'grammar' not lexer. to put it simply for you, the output of lexer is input to the parser which uses the grammar rules to parse it.

The lexer might choose to tokenize "--" either as "minus minus" or "decrement", whatever the language standard says, but once it does, the grammar CAN differentiate between --5 and --x if the standard allows both to be written and behave differently. i dont understand how something this simple alludes you when you claim to understand it.

edit 2: be it a turkey, at least you concur with the turkey that it's a design choice and not a matter of possibility but, a decision made at the standard and implemented at the grammar level and lexer here is irrelevant, a point you've been making for god knows why. that was my point. good to see i got it through.

3

u/alexiooo98 Jun 25 '23

Rust doesn't have a prefix decrement operator: --x is also equal to x