royale-compiler: Assign to int or uint variable does not convert Number from floating point to integer

A developer using int or uint will never want floating point values. Otherwise, they’d be using Number instead. We need to ensure that int and uint behave correctly in our generated JavaScript.

Current behavior:

var integer:int = -10.25;
trace("init with literal:", integer); //-10.25
integer = -10.25;
trace("assign with literal:", integer); //-10.25
integer = -10.25 + -5;
trace("add with literals:", integer); //-15.25

var number:Number = -10.25;
var number2:Number = -5;

var integer2:int = number;
trace("init with Number:", integer2); //-10.25
integer2 = number;
trace("assign with Number:", integer2); //-10.25
integer2 = number + number2;
trace("add with Number:", integer2); //-15.25

Expected behavior:

var integer:int = -10.25;
trace("init with literal:", integer); //-10
integer = -10.25;
trace("assign with literal:", integer); //-10
integer = -10.25 + -5;
trace("add with literals:", integer); //-15

var number:Number = -10.25;
var number2:Number = -5;

var integer2:int = number;
trace("init with Number:", integer2); //-10
integer2 = number;
trace("assign with Number:", integer2); //-10
integer2 = number + number2;
trace("add with Number:", integer2); //-15

To fix, the emitter could output Language._int(). However, we probably want to avoid a function call, so maybe just inline the same operation:

var integer = (-10.25) >> 0;

(The parentheses will be needed for complex expressions, but we might be able to remove them sometimes… or maybe Closure compiler will do it for us?)

Some alternate syntax options that should work too (however, we should probably be consistent with Language._int():

var integer = (-10.25) | 0;
var integer = ~~(-10.25);

Math.floor() should definitely be avoided. It does not simply drop the decimal part. It rounds down, which would give an incorrect value for negative floating point numbers. -10.25 would become -11 with Math.floor()

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Comments: 54 (54 by maintainers)

Commits related to this issue

Most upvoted comments

All numeric literals resolve to Number, even if they’re an integer. I added a special case for assigning a simple numeric literal integer, but expressions are treated as Number.

I should be able to manually crawl a more complex expression to check that all of these are true:

  1. numeric literals are all integers
  2. variables are all integers
  3. functions only return integers
  4. only the allowed operators are used
  5. any other sub-expressions resolve to int (this may have some more edge cases, but we can address them as they’re found)

Example of a complex expression that should be allowed without needing coercion, similar to a simple integer literal or variable:

(((1 + myInt) * 4) - 2 + getInt()) * 9