Casting
Casting is the explicit side of value conversion.
The language direction is:
- coercion stays implicit and narrow
- casting stays explicit and source-visible
FOL has no general cast operator. The explicit conversions that exist are named
intrinsics with checked semantics: .widen(...) and .narrow(...) for integer
widths below, and the text and number conversions in the library chapters.
A general cast would need a legality contract answering questions such as:
- which scalar casts are allowed beyond the width conversions below
- whether lossy casts are permitted
- whether container casts exist
- how aliases interact with explicit conversion
- how foreign/ABI types participate in conversion
Until that contract exists, conversions are added one named intrinsic at a time, each with its own checks, rather than through an operator whose meaning would have to be guessed.
Integer widths
Integer widths never mix implicitly. i32 and int are different types, and
adding them is a type error rather than a silent promotion:
var small: i32 = 1;
var big: int = 2;
var sum: int = small + big; // rejected: 'i32' and 'int'
.widen(...) converts a value to a wider type. It takes its result width from
the context, so the binding or parameter it fills decides the target:
var small: i32 = 2000000000;
var wide: i64 = .widen(small);
var byte: u8 = 200;
var signed: i16 = .widen(byte); // every u8 fits an i16
Widening is checked in both directions rather than assumed. The compiler refuses a conversion that could lose value, one where nothing could be lost, and one with no target to read:
'i32' does not hold every 'int', so this is not a widening
the value is already 'i32', so it needs no conversion
'.widen(...)' takes its result width from the context
“Wider” means the target holds every value of the source, not that it has more
bits. u8 widens to i16 because every byte is a valid i16; i32 does not
widen to u32, and u32 does not widen to i32, because each holds values the
other cannot.
.narrow(...) converts the other way. It can lose the value, so it reports
through the ordinary error channel and the failure has to be handled:
var wide: i64 = 5000000000;
var fitted: i32 = .narrow(wide) || 0; // 5000000000 does not fit, so 0
The direction is checked here too. Narrowing to a type that holds every value of the source is refused, because nothing could be lost:
'int' holds every 'i32', so nothing can be lost; use '.widen(...)'