LEVIATHAN vd52e79c4 · d52e79c486

Types

Numeric conversions and working types

Values cross between integer and float types only through a conversion call, lossless widening is implicit, and literals take the type their context asks for.

since 0.1.0-alpha.1linuxwindowswasm

Description

The numeric types form three classes:

Three rules decide how they combine.

  1. A value never crosses between the classes on its own. Turning an integer into a float, or a float into an integer, is always a call: .toFloat(), .toInt(), or a width-specific conversion such as .toFloat32(). An operator with an integer value on one side and a float value on the other is a compile error, and so is storing a value of one class into a slot of the other.
  2. Inside a class, lossless widening is implicit and narrowing is a call. An int8 flows into an int and a float32 into a float without a call. Going the other way, such as int to int8 or float to float32, needs the conversion method, which throws when the value does not fit.
  3. Literals take the type their context asks for, and so do expressions made only of literals: float f = 1 / 3; is 0.333333, because both literals become floats. With no context, integer literals are int and float literals are float, so var x = 1 / 3; is 0.

Every compile error caused by these rules names the conversion to write. decimal follows the same three rules, and since it is alone in its class nothing ever widens into or out of it: every crossing is .toDecimal() (on every integer and float type) or .toInt() / .toFloat() (on decimal).

Values, widening and literals

use io::console;

void demo() {
    int n = 10;
    float mean = n.toFloat() / 4;
    console.writeln(mean);
    int8 small = 100;
    int wide = small;
    console.writeln(wide + 1);
    float third = 1 / 3;
    console.writeln(third);
    var whole = 1 / 3;
    console.writeln(whole);
    console.writeln(2.7.toInt());
}
demo();
2.5e0
101
3.333333333333333e-1
0
2

Rules

Classes and widening.

  • These are the only conversions that happen without a call:
    • the signed chain int8 → int16 → int32 → int;
    • byte → int16, int32, uint and int, and uint → int;
    • the float chain float8 → float16 → float32 → float.
  • Each of them keeps every value exactly. Every other pair inside a class needs a conversion call, and so does every pair across the classes. This includes int8 ↔ byte, uint → int32 and every narrowing.
  • decimal widens to nothing and nothing widens to it. .toDecimal() exists on every integer and float type; decimal has .toInt() (truncating) and .toFloat().
  • The conversion methods come in two kinds. toInt() and toFloat() exist on every numeric type. The narrow-integer conversions (toByte(), toInt8(), toInt16(), toInt32(), toUint()) are methods of int, and the narrow-float ones (toFloat8(), toFloat16(), toFloat32()) are methods of float and, parsing text, of string. Other pairs go through that hub, for example f.toInt().toInt8() or n.toFloat().toFloat32(). The diagnostic spells the whole route.
  • A narrowing conversion throws a catchable RuntimeException when the value does not fit. float to an integer truncates toward zero, and throws for NaN, infinity or a value outside the range.

Operators.

  • Two integers compute in the joined integer type:
    • two signed integers, or two unsigned ones, join to the wider of the two;
    • a signed and an unsigned integer join to the smallest signed type that covers both, so int8 + byte is int16 and uint with any signed type is int.
  • Two floats compute in the wider float. An integer and a float have no join: a * 1.5 with an int8 a is a compile error that asks for a.toFloat().
  • Two decimals compute in decimal. A decimal and any other numeric type have no join: d * n with an int n is a compile error, no implicit conversion between 'decimal' and 'int'; convert the int with .toDecimal(); with a float type the hint is convert one operand with .toDecimal() or .toFloat(). % exists on decimal (the truncated remainder); the bitwise operators and shifts do not.
  • The result is reduced to the working type. Integer operators wrap at the working width, and narrow-float operators re-round in the working format. See lang.sized-integers and lang.sized-floats.
  • / is typed by its operands: integer division for integers, float division for floats.
  • Comparisons follow the same pairing rules and return bool.
  • + with a string operand is not numeric. Either order converts the other operand to text and concatenates: "n=" + 5 and 5 + "n" are strings.

Typed boundaries.

  • Each of these is a boundary, where the incoming value must already have the slot's type or widen to it:
    • an explicitly typed declaration, field, parameter, return value or assignment;
    • a collection element or a for-in variable;
    • a lambda's written return type;
    • a generic parameter after substitution;
    • the store of a compound assignment.
  • The value is computed in its own working type and then widened once. int x = a * 100; with an int8 a of 5 computes the int8 product, which wraps to -12, and only then widens it.
  • A compound assignment stores its working type back into the variable. total += a; with an int total and an int8 a is fine. x += n; with an int8 x and an int n is a compile error that asks for n.toInt8().
  • With a typed target, each arm of a conditional (c ? a : b), of a match and of ?? meets the target on its own.
  • A numeric optional such as float? keeps None and checks a present value like any other.
  • A boundary never converts into or out of decimal. Another numeric type into a decimal slot is cannot convert 'int' to 'decimal' implicitly; use .toDecimal(); a decimal into another numeric slot is cannot convert 'decimal' to 'int' implicitly; use .toInt() (use .toFloat() for a float slot, use .toInt() and a width conversion for a sized integer). For compound assignment, d += n with an int n is the operator error and n += d the store error.

Literals.

  • A literal-only expression is numeric literals combined with unary - and ~, the arithmetic operators and the bitwise operators. It adopts the type of its context. The contexts are:
    • every typed boundary above;
    • a typed operand beside it, so b * 2 with a byte b computes at 8 bits;
    • attribute arguments.
  • An integer literal can become a float (float f = 5;). A float literal never becomes an integer.
  • Integer and float literals both become decimal, built exactly from their digits: decimal r = 5 / 100; is 0.05, computed in decimal at compile time. A literal that decimal cannot hold exactly is a compile error, and a literal written with the m suffix (1.5m) is a decimal that adopts no other type (lang.numeric-literals).
  • A literal-only expression with a float literal in it and no context is a float, so var y = 1 / 2 + 0.5; is 1.0.
  • A named constant (const, static const) is a value, not a literal. float g = N / 3; with const int N needs N.toFloat().
  • A literal-only expression is evaluated at compile time exactly as the run time would evaluate it in its type, operator by operator.
    • A step whose result does not fit is a compile error that names the value and the range. int16 h = 300 * 300; reports literal expression 90000 out of range for 'int16'.
    • Integer division or remainder by zero, and a shift count outside the width, are compile errors too.
    • Float division by zero keeps its IEEE answer, so 1.0 / 0.0 is infinity.
  • A range with literal bounds adopts the element type: Array<float> ys = [1..3]; holds floats. A range with a variable bound has that bound's type.
  • A wide integer literal adopting a float converts from its own digits, never through a signed 64-bit overflow: float f = 18446744073709551615; stores 18446744073709551616.0.

Overload selection.

  • A value argument chooses among overloads only through exact matches and lossless widenings, and an exact match wins.
  • A literal argument prefers the overload of its own default type, so f(1 / 3) with f(int) and f(float) calls f(int). Otherwise the literal goes to the parameter that holds it best.
  • Two overloads that tie on different numeric targets make the call ambiguous. The result never depends on declaration order. Convert the argument explicitly to choose.
  • f(1.5) with f(float) and f(decimal) calls f(float); f(1.5m) calls f(decimal). An int or float value never selects a decimal parameter.

Examples

Boundaries, compound assignment and ranges:

Typed boundaries

use io::console;

float half(int n) => n.toFloat() / 2;
int whole(float f) => f.toInt();

void demo() {
    int8 a = 5;
    int x = a * 100;
    console.writeln(x);
    int total = 0;
    total += a;
    console.writeln(total);
    console.writeln(half(5));
    console.writeln(whole(3.99));
    Array<float> fs = [1, 2];
    Array<float> ys = [1..3];
    console.writeln(fs);
    console.writeln(ys);
    float? opt = 4;
    console.writeln(opt);
}
demo();
-12
5
2.5e0
3
[1.0e0, 2.0e0]
[1.0e0, 2.0e0, 3.0e0]
4.0e0

Overload selection, and string concatenation:

Overloads and string +

use io::console;

string pick(int x) => "int";
string pick(float x) => "float";
string size(int16 x) => "int16";
string size(float x) => "float";

console.writeln(pick(1));
console.writeln(pick(1 / 3));
console.writeln(pick(1.5));
byte b = 3;
console.writeln(size(b));
console.writeln("n=" + 5);
console.writeln(5 + "n");
console.writeln("x" + 1.5);
int
int
float
int16
n=5
5n
x1.5e0

Crossing into and out of decimal:

Explicit decimal conversions

use io::console;

string pick(float x) => "float";
string pick(decimal x) => "decimal";

void demo() {
    int qty = 3;
    decimal price = 19.99;
    decimal total = price * qty.toDecimal();
    console.writeln(total);
    console.writeln(total.toInt());
    console.writeln(total.toFloat());
    float f = 0.1;
    console.writeln(f.toDecimal() + 0.2);
    console.writeln(pick(1.5));
    console.writeln(pick(1.5m));
}
demo();
59.97
59
5.997e1
0.3
float
decimal

Notes

In the last example size(b) selects size(int16), because a byte widens to an int16 and does not cross into the floats.

See also

  • Sized integers: byte, int8, int16, int32, uint — The fixed-width integer types, how arithmetic wraps, how mixed widths combine, and when conversions throw.
  • Sized floats: float8, float16, float32 — The narrow floating-point formats, how every operation re-rounds, and where they overflow or throw.
  • decimal — The exact base-10 number for money and other decimal quantities — 34 significant digits, a kept scale, value equality and half-even rounding.
  • Numeric literals — Decimal, hexadecimal and binary integers, floats, the m suffix of a decimal literal, and the _ digit separator.
  • int — The signed 64-bit integer type, the default type of whole numbers.
  • float — A 64-bit IEEE 754 floating-point number (binary64).
  • decimal — An exact base-10 number: up to 34 significant digits and up to 34 digits after the point.