Fly Language Reference
Version: 0.14.9
Project: Fly Programming Language
License: Apache License v2.0
Table of Contents
- Introduction
- Lexical Elements
- Types
- Variables
- Functions
- Classes and Structures
- Enumerations
- Expressions
- Statements
- Namespaces and Imports
- Modifiers
- Comments
- Grammar Summary
1. Introduction
Fly is a compiled, high-level, general-purpose programming language with particular attention to simplicity, readability, and multi-paradigm support. Fly is built on LLVM infrastructure. It has no garbage collector: structs live on the stack, strings are released automatically, and class instances are released explicitly (see 6.6).
This reference describes the language as designed. Where the released compiler does not yet enforce a rule stated here, the difference is recorded in Conformance, which is the page to consult when a guarantee matters.
Design Principles:
- Simple - Easy to read and write
- Fast - Compiled with LLVM for optimal performance
- Powerful - Multi-paradigm with modern features
2. Lexical Elements
2.1 Keywords
Fly reserves the following keywords:
abstract as bool break byte
case class complex const continue
default delete double else elsif
enum error fail false final
float for handle if import
in int interface long namespace
new null pointer private protected
public return short static string
struct suite switch test true
uint ulong ushort void while
complex is reserved but has no meaning yet: it cannot be used as a name, and the
compiler accepts it nowhere else. unset, reserved up to v0.15.2, is not a keyword
from 0.16.0: a variable without an initializer holds the zero value of its type (see
Section 4.2), an enum its first constant, a struct the
initializers of its fields (Section 6.2).
returncarries the value a function hands back (return expr, orreturn a, bwhen several return types are declared). The value travels through a hidden output parameter the compiler adds to the signature, never through a copy out of the callee's frame. See Section 5.4.
thisis not a reserved keyword either — it is a special identifier available inside instance methods that refers to the current object (e.g.this.value). See Section 6.4.
deleteis a keyword from 0.15.0: the statementdelete xreleases an object created withnew(see Section 6.6). From 0.15.0 no reserved word can be used as a declared name (variable, parameter, field, method, function, class; an enum and its constants from 0.16.0):int delete = 3andint while = 3are errors.fs.deleteandenv.deletebecamefs.delandenv.del. Up to 0.14.xdeletewas an ordinary identifier.
2.2 Identifiers
Identifiers must start with a letter or underscore, followed by any combination of letters, digits, or underscores.
Syntax:
Identifier ::= [a-zA-Z_][a-zA-Z0-9_]*
Examples:
myVariable
_privateVar
counter123
MyClass
getValue2.3 Literals
2.3.1 Numeric Literals
42 // integer literal
0 // zero
3.14 // floating-point literal
0.0 // floating-point zero
1.5e-3 // exponent: 'e' or 'E', an optional sign, digits
2. // a fraction may have no digits after the '.'
A number literal is decimal: digits, an optional fraction (. and digits) and
an optional exponent. A literal with a . or an exponent is a double; an
integer literal is an int, or a long when its value does not fit an int. A
number starts with a digit (.5 is not a number: write 0.5).
There are no hexadecimal, binary or suffixed literals. From 0.16.0 a number
followed by letters or by a second . is a compile-time error that names the
literal, and so is a value the literal cannot hold: an integer above the largest
ulong (18446744073709551615) or a floating-point number beyond the range of a
double (about 1.8e308). A floating-point number too small for a double reads
as 0.0.
int a = 0x10 // error: invalid number literal '0x10'
long b = 7L // error: invalid number literal '7L': write (long)7
double c = 2.5.3 // error: invalid number literal '2.5.3'
ulong d = 18446744073709551616 // error: number literal '18446744073709551616' does not fit 'ulong'
double e = 1e400 // error: number literal '1e400' does not fit 'double'
Up to 0.15.x (the v0.15.2 seed included) these compiled to another value:
0x10 to 10, 12abc to 12, 2.5.3 to 0.0, an integer that does not fit a
ulong wrapped around, and 1e400 was infinity (fly-lang/fly#332).
2.3.2 Boolean Literals
true // boolean true
false // boolean false2.3.3 Characters
Fly has no character type and no character literal (from 0.15.0 char is not
even a keyword): a character is a string of one character, written "a".
The functions of fly.str that work on characters count Unicode code points,
not bytes: charAt, charCount, chars, charCode and fromCharCode.
string first = str.charAt("héllo", 1) // "é" (2 bytes, 1 character)
int n = str.charCount("héllo") // 5
int code = str.charCode("é", 0) // 233
string e = str.fromCharCode(233) // "é"2.3.4 String Literals
"Hello, World!"
"" // empty string
"tab\there\n" // escape sequences (from 0.15.0)
"caf\u{E9} \x41" // a code point as UTF-8, a byte
"""C:\Users\fly""" // raw: backslashes stay as written
"""first line
second line""" // raw literals may span lines
From 0.15.0 a backslash in an ordinary string literal starts an escape sequence:
| Escape | Byte(s) |
|---|---|
\n \t \r \0 | newline (10), tab (9), carriage return (13), NUL (0) |
\ \" \' | backslash, double quote, apostrophe |
\xHH | the byte with hex value HH (exactly two hex digits) |
\u{H…} | the code point H… (1 to 6 hex digits, up to 10FFFF, not a surrogate), written as UTF-8 |
Any other sequence (\q, \x4, \u41) is a compile-time error. A raw
literal between three double quotes, """…""", has no escapes: everything up
to the closing """ is its text, backslashes, quotes and newlines included.
fly fmt leaves the lines of a raw literal untouched.
Strings are sequences of bytes (str.len, str.byteAt, str.substring
count bytes); text is UTF-8, read by character (code point) with str.charAt,
str.charCount, str.chars, str.charCode and str.fromCharCode (see §2.3.3
and the API reference).
Up to 0.14.x every literal was raw:
"\n"was the two characters\andn, and a line break had to be written withio.printLnor a byte.
2.3.5 Null Literal
null // null value for reference types2.4 Operators and Punctuators
Arithmetic Operators
+ // addition
- // subtraction
* // multiplication
/ // division
% // modulo
++ // increment
-- // decrementCompound Assignment Operators
+= // add and assign
-= // subtract and assign
*= // multiply and assign
/= // divide and assign
%= // modulo and assignComparison Operators
== // equal to
!= // not equal to
< // less than
> // greater than
<= // less than or equal
>= // greater than or equalLogical Operators
&& // logical AND
|| // logical OR
! // logical NOTBitwise Operators
& // bitwise AND
| // bitwise OR
^ // bitwise XOR
<< // left shift
>> // right shift
&= // bitwise AND and assign
|= // bitwise OR and assign
^= // bitwise XOR and assign
<<= // left shift and assign
>>= // right shift and assignOther Operators and Punctuators
= // assignment
?: // ternary conditional
. // member access
[] // array subscript (bounds-checked — see 8.1.3)
() // function call / grouping
{} // block delimiters
, // separator
; // statement separator (used between the clauses of a for loop)
: // label / case / base-type / type-bound separator
3. Types
3.1 Built-in Types
3.1.1 Integer Types
| Type | Size | Range | Description |
|---|---|---|---|
byte | 8-bit | 0 to 255 | Unsigned byte |
short | 16-bit | -32,768 to 32,767 | Signed short integer |
ushort | 16-bit | 0 to 65,535 | Unsigned short integer |
int | 32-bit | -2,147,483,648 to 2,147,483,647 | Signed integer |
uint | 32-bit | 0 to 4,294,967,295 | Unsigned integer |
long | 64-bit | -9,223,372,036,854,775,808 to ... | Signed long integer |
ulong | 64-bit | 0 to 18,446,744,073,709,551,615 | Unsigned long integer |
Examples:
byte age = 25
short temperature = -10
ushort port = 8080
int count = 1000
uint id = 12345
long bigNum = 9999999999
ulong hugeNum = 184467440737095516153.1.2 Floating-Point Types
| Type | Size | Description |
|---|---|---|
float | 32-bit | Single-precision float |
double | 64-bit | Double-precision float |
A float holds 24 bits of mantissa: (float)16777217.0 is 16777216.0, and it is
32 bits wide in a struct, an array and a call to C. Up to 0.15.x the compiler kept every
float as a 64-bit double.
Examples:
float pi = 3.14
double precise = 3.141592653593.1.3 Other Built-in Types
| Type | Description |
|---|---|
bool | Boolean type (true or false) |
string | String type (heap-managed, see §6.6) |
error | Error type for error handling |
void | Absence of a value — used only as a function return type |
Examples:
bool isActive = true
string name = "Fly"
voidis written as the return type of functions that do not produce a value:void main() { … }. A return type is mandatory on every function and method (see Section 5.1).voidis never the type of a value: a variable, a parameter, a field, an array element, a generic argument or one value of a multi-return declaredvoidis a compile error (from 0.16.0).
3.1.4 Numeric Conversions
A number converts implicitly only where no value can be lost: into a type
that holds every value of the source type. Everything else needs an explicit
cast, (T)expr, which truncates (integers) or rounds toward zero (float to int).
A cast from float or double to an integer type fails (from 0.16.0) when the
value has no integer of that type to round to: out of its range, or NaN.
(int)1.0e20 fails with the code 2991 and conversion out of range at main.fly:4:12, like an index out of range (a handle catches it). (int)2.9 is
2, (int)-2147483648.5 is the minimum int, (uint)-0.5 is 0. Up to
0.15.x the result was undefined: the minimum int at -O0, whatever the
optimizer derived above it.
| Conversion | Implicit? |
|---|---|
widening: int → long, int → double, float → double, byte → int | yes |
unsigned into a wider signed type: uint → long, byte → short | yes |
narrowing: long → int, int → byte, double → float, double → int | no — cast |
signed into unsigned, any width: int → uint, int → ulong, long → ulong (a negative value has no unsigned counterpart) | no — cast (from 0.15.0) |
any integer into pointer (address arithmetic: a negative offset wraps) | yes |
any number into bool, a pointer included: 0 is false, anything else true (a float: 0.0 and -0.0 are false, NaN is true) | yes (from 0.16.0) |
bool into a number | no — cast: (int)b is 0 or 1, in every numeric type ((double)true is 1.0; up to 0.15.x true became -1) |
A number is a truth value (from 0.16.0, fly-lang/fly#199). Wherever a bool is
expected — a declaration, an assignment, a field, an argument, a return, a
condition (if, elsif, while, for, the ?: ternary) and the operands of
!, && and || — a number is false when it is 0 and true otherwise, as
n != 0 would say; (bool)n means the same. It costs the one compare you would
write by hand. A string, an array or an object is not a truth value: bool b = "x"
and if s { } are errors. An overload taking a number wins over one taking a
bool: f(3) calls f(long) before f(bool).
bool on = 4 // true
bool off = 0 // false
if count { } // count != 0
while p { } // p != 0 (a pointer)
bool any = !items // items == 0
! gives a bool whatever its operand: !n on an int is a bool, not an int
(up to 0.15.x !n on an integer stopped the compiler with an internal error).
Up to 0.15.x a number stored into a bool kept its lowest bit only — bool b = 4,
(bool)4 and a bool function returning 256 were all false — and a number as a
condition was an error (a condition must be 'bool').
The rule is the same wherever a value is stored: a declaration, an assignment,
a field, a return, and — from 0.15.0 — every argument of a call, which is
stored into its parameter. A variable passed to a non-const (out) parameter is
checked the other way round, since the callee writes the parameter back into it.
A literal needs no cast when its value fits the target: byte b = 200,
uint u = 5, take(4096) for a ulong parameter. uint u = -1 is an error.
Comparing signed with unsigned. int and uint are compared in uint,
where -1 reads as 4294967295; from 0.15.0 such a comparison is an error
that asks for a cast. It stays legal when the signed type holds every value of
the unsigned one (aLong < aUint, anInt > aByte), or when the signed side is
a non-negative literal (u > 0).
Arithmetic on signed and unsigned. The same rule holds for +, -, *,
/, %, &, | and ^ (from 0.16.0): aUint + anInt has no type that holds
both, and is an error that asks for a cast (a signed 'int' and an unsigned 'uint' cannot be mixed in arithmetic). aUint + 1, aLong + aUint and
anInt + aUshort stay legal; so does a shift, whose count is not mixed into the
value. Up to 0.15.x (the v0.15.2 seed included) uint u = 10; int i = -1; long r = u + i compiled, then stopped with integer overflow in '+'.
long big = 5000000000
int n = big // error: may not fit
int m = (int)big // explicit
int k = -1
ulong size = k // error: a negative int has no ulong value
ulong ok = (ulong)len // explicit, once len is known to be >= 0
if k < aUint { } // error: compared in uint
if k < (int)aUint { } // explicit3.2 Array Types
Arrays can be declared with or without explicit size.
Syntax:
ArrayType ::= Type '[' [ Expression ] ']'
Examples:
// Dynamic array: the initializer gives the size
byte[] dynamicArray = {}
int[] numbers = {1, 2, 3}
// Fixed-size array
byte[10] fixedBuffer
int[5] coordinates
// Multi-dimensional arrays
int[][] matrix = {}
byte[][][] cube = {}
int[2][3] grid // 2 rows of 3: grid[i][j] with i < 2 and j < 3
A declaration must give either a size or an initializer — int[] xs alone is an error, because there is nothing to say how large the array is.
More than one dimension. The dimensions read in the order of the subscripts: int[2][3] grid is 2 rows of 3 elements, so the first subscript goes up to 2 and the second up to 3 (grid[1][2] is the last element; grid[2][0] and grid[0][3] fail with index out of range). From 0.16.0 a sized declaration builds every dimension: each row is built as a sized array of one dimension is — numbers at zero, struct elements with their field initializers, class elements with their no-argument constructor — and every size is evaluated once, before anything is allocated. A dimension without a size ends the building: int[2][] rows is two rows, each an empty array until one is assigned. Up to 0.15.x (the v0.15.2 seed included) only the outer array was built, with its sizes read in the opposite order: the rows stayed empty and every subscript failed.
The size is checked (from 0.16.0, fly-lang/fly#320). A size can be any integer expression, read from the input as well:
- a negative size fails with the code
2992,negative array size at main.fly:7:5, before anything is allocated; ahandlecatches it; - a size whose bytes do not fit the address space (
long[n]withnnear 2^61), or memory the system cannot give, stops the program witherror 134: out of memory at main.fly:7:5.
Up to 0.15.x (the v0.15.2 seed included) a negative size stopped the program on an invalid memory access, -1 made an array of length -1, and a size whose byte count overflowed wrapped to a small buffer that the elements up to the size then reached past.
Elements are read and written with the subscript operator, which is bounds-checked (see 8.1.3 Array Subscript), and iterated with for in (see 9.5.3).
Arrays are heap-backed, reference counted, and have reference semantics — assigning one array to another shares the buffer instead of copying it. Their lifetime, and what an array does and does not own, is specified in 6.6 Allocation and Lifetime.
3.3 Named Types
User-defined types include classes, structures, and enumerations.
Examples:
MyClass obj
Point location
Status currentStatus3.4 Qualified Type Names
Types can be qualified with namespace prefixes.
Examples:
// Using dotted notation
utils.Helper helper
mylib.DataType data
4. Variables
4.1 Local Variables
Local variables are declared within functions or blocks.
Syntax:
LocalVar ::= [ Modifiers ] Type Identifier [ '=' Expression ]
Examples:
void func() {
// Simple declaration
int x = 10
// Without initialization
bool flag
// Constant local variable
const int limit = 100
}4.2 Variable Initialization
4.2.1 Basic Types
bool flag = true
int count = 42
float value = 3.14
string message = "Hello"4.2.2 Null Initialization
MyClass obj = null
Type instance = null4.2.3 Array Initialization
// Empty array
byte[] empty = {}
// Array with values
byte[] values = {1, 2, 3, 4, 5}
int[] numbers = {10, 20, 30}
// Fixed-size array
byte[3] buffer = {1, 2, 3}4.2.4 Struct Literal Initialization
A brace literal that contains field = value pairs builds a struct value. Plain comma-separated values (without =) build an array value (see above); the two forms are distinguished by the presence of field =.
A field the literal does not give takes its initializer (int x = 4 in the struct, see Section 6.2), or its zero value.
// Struct value — field = value pairs
Point p = {x = 10, y = 20}
// Array value — bare values
int[] xs = {10, 20, 30}
5. Functions
5.1 Function Declaration
Every function and method must declare a return type before the function name — this is mandatory. A function that produces no value declares void. When a non-void return type is present, the body must hand a value back with return expr on every path; the compiler adds a hidden output parameter to the signature and the return writes through it.
Important: A missing return type is a compile error (
err_parser_missing_return_type). Writevoid doSomething() { … }, notdoSomething() { … }. The only exceptions are constructors (a method named exactly like its class — see §6.4) and interface method declarations, which omit the return type.
Syntax:
Function ::= [ Modifiers ] ReturnType Identifier
[ '<' TypeParam ( ',' TypeParam )* '>' ]
'(' [ Parameters ] ')' ( Block | ';' )
ReturnType ::= Type ( ',' Type )*
Examples:
// Void function — declares 'void' explicitly
void doSomething() {
// function body
}
// Function with a return type — `return` carries the value
int add(const int a, const int b) {
return a + b
}
// Multiple return types — one return, values in declaration order
int,int minMax(const int a, const int b) {
if a < b {
return a, b
} else {
return b, a
}
}5.2 Function Parameters
The const modifier on a parameter is optional. A const parameter is read-only inside the body (an input); a non-const parameter may be written and is the mechanism used for output parameters (including the hidden parameter generated for return values). A parameter may also declare a default value with = <literal>.
A parameter without const that the body never writes is reported by the missing-const warning (from 0.16.0; see CLI — Warnings): the callee could write the caller's variable, so a parameter it only reads belongs as const. const protects the parameter itself, so writing a field or an element through it (p.x = 1) is allowed and does not count as a write.
Syntax:
Parameters ::= Parameter ( ',' Parameter )*
Parameter ::= [ Modifiers ] Type Identifier [ '=' Value ]
Examples:
// const inputs (read-only)
void process(const int x, const float y, const bool flag) {
// implementation
}
// Parameters without const are writable (e.g. output parameters)
void clamp(const int value, const int lo, const int hi, int result) {
if value < lo { result = lo }
elsif value > hi { result = hi }
else { result = value }
}
// Default parameter value
void retry(const string url, const int attempts = 3) {
// attempts defaults to 3 when the caller omits it
}
// Generic parameter without const (see §6.7)
T identity<T>(T v) {
return v
}5.3 Visibility Modifiers
Functions can have different visibility levels:
// No modifier: visible in its namespace only
void defaultFunction() {}
// Private function: visible in this file only
private void privateHelper() {}
// Public function (exported)
public void publicAPI() {}
A private function belongs to its file: no other file can call it, not even
one of the same namespace, and each file of a namespace may have its own
private helper of a given name (see 11.1).
protected is not a visibility for functions: it applies only to the methods
and attributes of a class (see 11.1), and on a
function it is an error.
5.4 Return Values
A function hands a value back with return expr. The caller receives it as if the function returned by value — but the compiler generates a hidden by-reference output parameter, writes the value into it and then returns, so the result is never copied out of the callee's frame.
That is a statement about the calling convention, not a promise that returning is free. return expr is lowered to an ordinary assignment into that hidden slot and obeys the ownership rules of 6.6: returning a borrowed string — a parameter or a field — clones its buffer, which is exactly what makes every call result independently owned; returning an array transfers ownership without copying a single element.
// Looks like return-by-value to the caller…
int square(const int n) {
return n * n
}
void main() {
int x = square(5) // x = 25
}
This resolves the classic C++ ergonomics/performance tension: in C++ you must choose between File f = open(path) (readable, but implies a copy) or open(path, &f) (efficient, but noisy). Fly does both with the same syntax — the source reads as a plain return, and the compiler silently passes x by reference to square.
Every path must return. In a function that declares a return type, reaching the closing brace without a return is a compile error rather than a silent zero. An if counts only when it has an else and every branch returns, a switch only when it has a default and no case falls out of it; fail also ends the function, and so does while true with no break. A handle never counts, even when its body ends in return: a failure in the body skips the rest of it, return included, and goes on after the handle (from 0.16).
// error: 'classify' must return a value on every path
int classify(const int n) {
if n > 0 {
return 1
}
}
// error: 'parse' must return a value on every path —
// when check() fails, the return is skipped
int parse(const string s) {
handle {
check(s)
return 1
}
}
// fine: the value after a failure is written out
int parseOr(const string s) {
handle {
check(s)
return 1
}
return 0
}
Building a struct in place. When every return in a body hands back the same struct local, that local is the caller's slot: its fields are written straight into the returned object and the return copies nothing. This is what makes the idiomatic shape below cost exactly what filling an output parameter by hand used to cost:
Stat statOf(const string path) {
Stat s
s.size = sizeOf(path)
s.mode = modeOf(path)
return s // no copy: `s` was the caller's Stat all along
}
Writing into a value you are about to return. An intrinsic that fills an output parameter needs a local to fill, which the return then hands back (this is standard-library code: from 0.15.0 fly.llvm can only be called from a fly.* namespace, see Section 10.4):
public int size() {
int n = 0
fly.llvm.ptrReadInt(this.ptr, 8, n)
return n
}
Multiple return types are returned in one statement, in declaration order:
int,int divmod(const int a, const int b) {
return a / b, a % b // quotient, remainder
}
void main() {
int q = divmod(17, 5) // q = 3 — a plain assignment binds the first value
}
At the call site, a multi-assignment consumes every slot: list the
receiving variables (comma-separated) before = — they bind to the return
slots in order. Every receiver must be an already-declared variable
(a multi-assignment never declares), the right side must be a call, and the
receiver count must match the callee's return count exactly. The call writes
every receiver, so a const receiver is an error, the same as k = …
(a const field follows the rule of §6.4). The receivers
take their values after the call returns, all together: an argument that
names a receiver reads its old value, so p, q = swap(p, q) swaps two structs
as it swaps two numbers (from 0.16.0; up to 0.15.x the first result was written
into a receiver while the callee could still read it through a struct argument,
and p, q = swap(p, q) gave two copies of q). If the call fails, the receivers
keep their values. For example:
void main() {
int q = 0
int r = 0
q, r = divmod(17, 5) // q ← 3, r ← 2
}
A return with the wrong number of values is a compile error, as is a value in a function declared void.
A method declares several return types the same way (from 0.16.0; up to
0.15.x it was a parse error, expected an identifier here): an instance or a
static method, an interface method, an override. An override returns the same
types as the method it overrides (§6.3), and the
call through a base class or an interface runs the override. The header of a
--lib library lists every return type, so a program reaches such a method
through -L too.
interface Pair {
int, int split(const int v)
}
class Digits : Pair {
public int, int split(const int v) {
return v / 10, v % 10
}
}
void main() {
Pair p = new Digits()
int q = 0
int r = 0
q, r = p.split(47) // q ← 4, r ← 7
delete p
}
Early exit in a void function is a bare return:
void process(const int x) {
if x < 0 {
return // exit early — no value
}
// continue processing
}5.5 The Main Function
The main() function is the entry point of a Fly application.
Syntax:
void main() {
// Application code
}
Key Characteristics:
- Function signature: Must be declared as
void main() {}with no parameters and void return type - Entry point: The application starts execution from
main() - Automatic error handling: The main function has special error handling behavior
The signature is enforced, not merely conventional. Declaring a return type
on main — single (int main()) or multiple (int, int main()) — is a compile
error in both compilers:
error: 'main()' must be declared 'void': the exit code comes from an unhandled 'fail', not from a returned value
main takes no parameters either (from 0.16.0): void main(const int x) is the
compile error 'main' takes no parameters: the command line is read with fly.os.env,
and the arguments are read with fly.os.env. Up to 0.15.x it stopped the compiler
with an internal error (backend module verification failed).
It follows that main cannot return a value: a void function has no output
parameter, so a value there is the ordinary "'return' cannot carry a value in a
function declared 'void'" error (a bare return still exits early). The process
exit code is not something main returns — it is derived from the error state
described next, so the only things a program can act on are fail (to set an
error) and handle (to stop one from propagating).
Error Handling and Return Codes:
When the application runs, main() automatically returns an exit code to the operating system:
- Return 0: If no unhandled errors occur (success)
- Return
code: If an unhandled error occurs, the exit code is the error's integer code (fail 404, "…"→ exit 404; a barefailor afailwith only a string/object → exit 1)
Before exiting with a non-zero code, main() also prints the unhandled error to
stderr in the form:
error <code>: <message>
(or just error <code> when the error carries no message). This behavior is
automatic—you don't explicitly return an integer from main(), and only the
unhandled error that is still recorded when main() ends is printed; handled
errors are never printed.
Example 1: Successful Execution
void main() {
// Code executes successfully
int x = 10
int y = 20
// Automatically returns 0 (success)
}
Example 2: Unhandled Error
void err0() {
fail "Something went wrong"
}
void main() {
err0() // Error is not handled
// Automatically returns 1 (failure)
}
Example 3: Handled Error
void err0() {
fail "Something went wrong"
}
void main() {
handle err0() // Error is caught and handled
// Continues execution
// Automatically returns 0 (success)
}
Example 4: Captured Error with Graceful Handling
void riskyOperation() {
fail "Operation failed"
}
void main() {
handle {
riskyOperation()
}
if error {
// Error was caught and handled
// Continue with fallback logic
}
// Automatically returns 0 (success)
}
Best Practices:
- Always handle errors in main: Unhandled errors will cause the application to exit with code 1
- Use handle blocks: Wrap risky operations in
handleblocks to ensure graceful error handling - Check error variables: Use
if (error)to detect and respond to errors appropriately - Provide fallback logic: When errors occur, provide alternative execution paths
Summary:
main()is required (void return type, no parameters)- Exit code 0 = success (no unhandled errors)
- Exit code 1 = failure (unhandled error occurred)
- Use
handleto catch errors and ensure successful exit
6. Classes and Structures
6.1 Class Declaration
A class declares its base types after a colon. The grammar accepts a comma-separated list of base types: a class extends at most one class or struct and implements any number of interfaces.
Syntax:
Class ::= [ Modifiers ] 'class' Identifier
[ '<' TypeParam ( ',' TypeParam )* '>' ]
[ ':' BaseType ( ',' BaseType )* ] '{' ClassMember* '}'
BaseType ::= NamedType
Examples:
// Simple class
class MyClass {
}
// Public class
public class Application {
}
// Class extending a struct
class Derived : BaseStruct {
}
// Class implementing an interface
class MyImpl : Drawable {
}
// Class with a base struct and one or more interfaces
class Widget : BaseStruct, Drawable, Resizable {
}
abstractandfinalmay be applied as class modifiers (see Section 11).
What a base can be (checked from 0.16.0). A class extends a class or a struct and implements interfaces; a struct extends only a struct (6.2); an interface extends only interfaces (6.3). Nothing extends an enum, a builtin type (int, string), an array or its own type parameter (class Box<T> : T), and a base is listed once. Each of these is a compile error at the base, for example 'Point': a struct extends only a struct, not the class 'Box' or 'Square': 'Shape' is listed twice among the bases. Up to 0.15.x (the v0.15.2 seed included) such a base was accepted: a struct extending a class read its members as garbage, and a builtin or enum base was silently dropped.
6.2 Structure Declaration
Structures are value types similar to classes. A struct can only extend another struct.
Syntax:
Struct ::= [ Modifiers ] 'struct' Identifier [ ':' Identifier ] '{' StructMember* '}'
Examples:
// Simple structure
struct Point {
int x
int y
}
// Public structure
public struct Vector {
float x
float y
float z
}
// Struct extending another struct
struct Point3D : Point {
int z
}
A struct field may have an initializer (int x = 4). From 0.16.0 every value of the struct starts from it, after the zero value: new Point(), a declaration Point p, a brace literal that does not give the field, a struct field inside an object or another struct, the base struct of a struct, the base struct of a class (see Section 6.4), and each element of a sized struct array (Point[3] ps), in index order; a struct constructor does not run for them, as for Point p. Up to 0.15.x the initializer was ignored.
struct Pen {
int width = 2
string color = "black"
}
Pen a // width 2, color "black"
Pen b = {color = "red"} // width 2, color "red"
A struct has no ==. Two structs are compared field by field, by the
program: p == q and p != q (and < and the others) on two structs are an
error from 0.16.0, two structs ('Point') cannot be compared with this operator: compare their fields. Up to 0.15.x (the v0.15.2 seed included) they compiled to
a comparison of the two structs' addresses, so two equal structs were never
equal.
No cycles (from 0.16.0). A type cannot be its own base, directly or through others, and a struct cannot hold itself by value: a struct holds its struct fields, the elements of its sized array fields and its base struct inline, so one that holds itself has no finite size. Each is a compile error that shows the cycle:
class A : B { // error: class 'A' inherits from itself: A -> B -> A
}
class B : A {
}
struct S { // error: struct 'S' contains itself by value: S -> P -> S
P p
}
struct P {
S s
}
A class field is a reference, so a struct may hold an object of a class that holds
the struct (struct Pair { Node node } with class Node { Pair pair }). Up to
0.15.x (the v0.15.2 seed included) both cycles stopped the compiler with
fatal error: stack overflow.
An unsized array is a reference too, empty when the struct is created, so a struct
may reach itself through one, directly or through other structs, at any array
depth (P[][]). Its strings and arrays are released as deep as the data goes:
struct P {
P[] more // a tree of P: fine
int v
}
void main() {
P leaf = new P()
P root = new P()
root.more = {leaf, leaf}
}
Up to 0.15.x (the v0.15.2 seed included) such a struct stopped the compiler with
fatal error: stack overflow (fly-lang/fly#351).
6.3 Interface Declaration
Interfaces define contracts for classes. An interface extends only interfaces, one or more.
Syntax:
Interface ::= [ Modifiers ] 'interface' Identifier [ ':' Identifier ( ',' Identifier )* ] '{' InterfaceMember* '}'
InterfaceMember ::= ReturnType Identifier '(' [ ParamList ] ')'
An interface method declares its return type like any function (void included)
and has no body; a class that implements the interface defines every method with
the same signature.
From 0.16.0 the compiler checks all of it: a method of an interface with a body ('sides': a method of an interface has no body: an interface declares only signatures) and a field in an interface ('count': an interface declares only methods, not fields) are errors. So is a method that implements an interface method, or overrides a method of a base class, with another return type: 'name' returns another type than the method it overrides in 'Named': an override has the same signature, return types included, with a note at the method it overrides. Up to 0.15.x the call through the interface read the result as the interface's type (an invalid memory access for string against int), the call through a base class ran the base's method, and an interface method with a body was taken as a default the class inherited.
Examples:
// Simple interface
interface Drawable {
void draw()
}
// Public interface
public interface Serializable {
void serialize(const string path)
bool deserialize(const string data)
}
// Interface extending another interface
interface Resizable : Drawable {
void resize(const int width, const int height)
}
// Interface extending two interfaces
interface Widget : Resizable, Serializable {
string name()
}
An interface with several bases has the methods of each base and its own: a
class that implements Widget implements draw, resize, serialize,
deserialize and name, and a Widget variable calls any of them. A Widget
is accepted where a Resizable, a Drawable or a Serializable is expected. A
method that two bases declare with the same signature (both extending one
interface, for example) is one method. Up to 0.15.x (the v0.15.2 seed included)
only the first base counted: a call through Widget to a method of
Serializable ran another method.
6.4 Class Members
Classes can contain fields (attributes) and methods.
Each member is declared once (from 0.16.0). Two fields with one name, two methods (or two constructors) with the same parameter types, two parameters with one name, are errors at the second, with a note at the first: field 'f' is already declared in 'Box', method 'k' with the same parameter types is already declared in 'Box', parameter 'a' is declared twice. Two methods that differ only in the return type are the same method declared twice. The same holds in a struct and an interface. A field and a method may share a name (int size and int size()), and overloads differ in their parameter types. Up to 0.15.x the second declaration was dropped or won the call, silently.
A method without a body is abstract, and only an abstract class (or an interface) declares one: in any other class it is an error (declare 'Shape' abstract or give the method a body); an abstract method has no body (11.5).
Constructors are methods whose name is exactly the class name and which declare no return type. They are the one exception to the mandatory-return-type rule and run when the object is created with new (see §6.5).
Destructors (from 0.16.0) are written delete(): the reserved word delete, no parameters, no return type and no modifier. A class has at most one, and only a class has one (not a struct, an interface or an enum). delete x runs it, never a call: it holds the logic that deletes the objects the class owns (see Destructors).
public class Tree {
Node root
public Tree() {
this.root = new Node()
}
delete() {
delete this.root
}
}
this is available inside any instance method and refers to the current object. Use this.field to access members.
In a constructor this is only a receiver (from 0.16.0). In a constructor, and in an instance field initializer, this may be used to read or set a field and to call a method — this.x, this.x = v, this.m() — and nothing else. The object is not complete yet, and a constructor that fails releases it (see A new that fails), so a copy of this kept elsewhere would point at released memory. Any other use is a compile error, 'this' can only be a receiver (this.x, this.m()) in a constructor or a field initializer: assigned (Reg.last = this, Node self = this), passed as an argument (list.add(this), f(this)), placed in an array value ({this}), compared. As the object of a fail it has an error of its own (see Fail Statement). In every other method this is an ordinary value. A program that registers a new object does it after the new, where the object is complete:
Node n = new Node()
Reg.last = n
Not covered: a method called from the constructor (this.m()) can still store this somewhere, and the constructor can fail after it. Like using an object after delete, that is the program's responsibility. Up to 0.15.x this was an ordinary value in a constructor too.
All other methods require a return type (void for methods that return nothing).
const fields are read-only. A static const field takes its value from its initializer and is never assigned. An instance const field without an initializer is set once, by a constructor of the class that declares it, on its own object (this.v = …, v = …, or as a receiver of a multi-assignment, a, v = f()). Every other write is an error: another method, another object (o.v = …), a subclass constructor (super.v = …), a field that has an initializer, +=, ++/-- and delete. The error is the same as for a const local: cannot assign to 'v': it is declared 'const'.
Field initializers. A field may be declared with an initializer (int count = 4). An instance field's initializer runs when the object is created: after the object is zeroed and before any constructor, for every field that has one, inherited fields first and then the class's own, in declaration order, whether or not the constructor calls super(...). So a constructor already sees the initialized values. An initializer may read the fields declared before it, with this as a receiver only (see above). If it fails (a call that fails), the new fails and releases the object (see A new that fails). A static field's initializer that is a constant — a literal, an enum entry, a static const field, or the operators and casts over them (static const int B = A * 2 + 1, static const byte W = (byte)300) — is the field's initial value, and no code runs for it. Any other one (static List<int> xs = new List<int>(), static int n = compute()) runs on the first use, as described below. An initializer may call a method declared after it, and initializers are checked like a declaration's (int f = "abc" is an error). All of this is from 0.16.0. Up to 0.15.x an initializer was ignored and the field started at its zero value.
Sized array fields. A field declared with a size and no initializer (int[2] a, Cell[3] cells, int[2][3] grid) is built when the object is created, like a sized local (see Arrays): numbers at zero, struct elements with their field initializers, class elements with their no-argument constructor, every dimension. It is built with the field initializers, in declaration order, for a class (new) and for a struct (P p, new P(), a brace literal that does not give the field, a nested struct field, each element of a sized struct array). An element that fails to build fails the creation. A brace literal or an initializer that gives the field replaces the building. The array is an array like any other: a copy of the struct shares it (one more reference), and it goes with the last reference. From 0.16.0; up to 0.15.x the size was ignored and the field was an empty array (every subscript failed with index out of range).
Static initializers that are not constants. They run on first use: the first read or write of such a field of a class runs every such initializer of that class, once, in declaration order. Nothing runs before main, and a class nobody uses runs nothing. Reading a static field with a constant initializer, or with none, starts nothing; a write is a use like a read (the initializers run, then the value is stored).
class Registry {
static int version = 3 // a constant: the initial value
static List<string> names = new List<string>() // runs on first use
static int loaded = load() // runs right after `names`
static int load() {
names.add("default") // `names` is declared before `loaded`: already set
return 1
}
}
void main() {
int v = Registry.version // nothing runs
int n = Registry.loaded // `names`, then `loaded`
}
- Order among classes and modules is the order of use: an initializer that reads a static field of another class, in the same file or in another module, has that class initialized first. The initializers of a library class run in the library, also for a program that uses it through
-L(a static or a dynamic library). - A failing initializer makes the access that started it fail, like a call:
handlecatches it, and unhandled it reachesmain(error <code>: <message>and the exit code). The fields initialized before it keep their values; the next access to such a field of the class runs the failed initializer again, then the ones after it. - Cycles. A field is never read before its initializer ran. An initializer that reaches a field of its class whose own initializer has not run yet — through a method it calls, or through another class whose initializer reads it back — fails with code
2990,static initialization cycle: <Class>, a failure like any other. Reading a field declared before it is always fine. - Threads. One thread runs the initializers of a class; a thread that uses the class meanwhile waits for it.
- At the end of the program the object a static field refers to is released with everything else and is not reported as not deleted (see §6.6).
Examples:
public class Person {
// Private fields
private string name
private int age
// Public field
public bool isActive
// Static field
static int instanceCount = 0
// Constructor — same name as the class, no return type
public Person(const string personName, const int personAge) {
this.name = personName
this.age = personAge
this.isActive = true
instanceCount++
}
// Public method with return type
public string getName() {
return this.name
}
// Private void method
private void validate() {
// validation logic
}
// Static method with return type
public static int getCount() {
return instanceCount
}
}6.5 Object Creation
Objects are created with new, which invokes a constructor. There is no delete operator in the language; how the memory is reclaimed depends on whether the type is a struct or a class (see §6.6).
Examples:
// Create a class instance (heap-allocated)
MyClass obj = new MyClass()
// Construct with arguments and call a return-type method
Person person = new Person("John", 30)
string name = person.getName() // name = "John"
int count = Person.getCount() // count = 1
6.6 Allocation and Lifetime
The new keyword allocates a new instance. Where the memory comes from — and how it is reclaimed — depends on whether the type is a struct or a class. A class instance is released with delete (from 0.15.0).
Struct: stack-allocated, freed automatically
A new on a struct allocates the data on the stack (via LLVM alloca). It is freed automatically when the enclosing scope exits — nothing to release manually.
struct Point {
int x
int y
}
void process() {
Point p = new Point() // ← stack alloca
p.x = 10
p.y = 20
} // ← p released automatically when the scope exitsClass: heap-allocated, released with delete
A new on a class allocates on the heap — from 0.16.0 the runtime's own object heap, which knows every live object (see Objects never deleted below); up to 0.15.x the system malloc. The object belongs to the program until delete x releases it, which:
- does nothing when
xisnull; - runs the destructor of the object's class, then those of its base classes (from 0.16.0, see Destructors) — that is where a class releases what it owns: the objects in its fields, a buffer. A class with no destructor in its hierarchy has its
free()method called instead, when it declares one with no parameters (its own or inherited), as up to 0.15.x; - releases the object itself. Steps 2 and 3 follow the class the object was created with, not the type of
x(from 0.16.0); - sets
xtonull, so a seconddelete xis harmless and a later use ofxstops on the null-reference trap instead of reading freed memory.
After the destructor, delete releases the values the object's fields hold (from 0.16.0): the buffer of each string field, one reference to each array field, and the strings and arrays of each struct field — the base classes' fields included. It never deletes the objects its fields refer to: the class's destructor (or free()) deletes them, or the caller does before the delete (from 0.16.0; up to 0.15.x the fields filled with new unique, new shared or weak went with the object, and the string and array fields were never released: every delete of an object with a string field leaked it).
Another reference to a deleted object (Node b = a, delete a, then b) is not null, and using it is an error the program must not make. From 0.16.0 the object heap limits what it can do (fly-lang/fly#314):
- A method call through it stops the program:
deletegives the object its class's dead method table, and every entry stops witherror 134: use of a deleted 'Node'(exit code 134), also through an interface. Up to 0.15.x the call followed freed memory as the method table. - A field read or written through it is not checked: it reads what the object held, or writes into the freed slot. A freed slot is only ever reused by an object of the same class, so it can reach an object of its own class, never one of another: no
Accountis reached through a deletedBox. Up to 0.15.x a slot went to the next object of the same size, of any class. The heap keeps none of its own data in a freed slot either. - These cost nothing on a call or a field access: one store at each
delete, and the memory of keeping each class's spans apart (about 1% for the compiler compiling itself).
Deleting through another reference an object that is already gone — Node b = a, delete a, delete b — stops the program (from 0.16.0): error 134: double delete of a 'Node' at main.fly:4:5, exit code 134. The object heap no longer counts the object as live, so the second delete is caught before it runs anything.
The check holds until the freed slot is reused. A reference is an address, nothing more: once a new of the same class takes the slot (the next one usually does), the old reference points at the new object, and a second delete through it deletes that object, with no error. A freed slot goes to the same class only, so such a delete never reaches an object of another class, and the next method call on the object it deleted stops with use of a deleted …:
R x = new R()
R y = x
delete x
R z = new R() // takes x's slot
delete y // deletes z: no error
int n = z.get() // error 134: use of a deleted 'R'
A delete that reaches the object from its own destructor — a node whose next is itself, two nodes that delete each other — is a double delete too (from 0.16.0, fly-lang/fly#334): delete marks the object as dying before its destructors run, so the inner delete stops with error 134: double delete of a 'Node' at its own position instead of running the destructors again until the stack overflows.
The target must be a variable, a parameter or a field holding a class or interface reference; it cannot be this, a struct or a const variable.
A new that fails. When a field initializer, a constructor argument or the constructor itself fails, the object is only half built. From 0.16.0 the new gives its memory back before the failure goes on. Its destructor (or free()) does not run: the object was never built. The values its fields took before the failure (strings, arrays, struct members) go with it; an object a field refers to does not: a constructor that fails after it set one deletes it itself, before the fail. Up to 0.15.x the object was left behind. A constructor cannot hand this to the error (fail 1, this is a compile error, see Fail Statement); when a method it calls does, the object travels in the error instead, and the handle that consumes the failure deletes it. An element of a sized array that fails stops the declaration the same way (see Arrays); with more than one dimension the rows already built go too, the last one first, each from its last element.
public class Box {
Res inner
public Box(const bool bad) {
this.inner = new Res()
if bad {
delete this.inner // nothing else releases it
fail 1, "bad box"
}
}
delete() {
delete this.inner
}
}
A destructor or free() that fails. A destructor or free() may fail like any method (a fail, a failing call, an index out of range), and from 0.16.0 that is an ordinary failure, checked and propagated: a handle catches it, or main reports it and exits with its code. Up to 0.15.x it was not checked after delete, and it was dropped during a cleanup.
delete x: the base destructors still run, the object is still released andxset tonull; then the failure goes on from thedelete, as from a failing call. The statement after it does not run. When a base destructor fails too, the first failure is thedelete's and the later one is attached to it.- The release at the end of
mainof the objects never deleted (see below): whenmainended cleanly, the firstfree()that fails is reported like an unhandled failure and sets the exit code; the other objects are still released. - Two failures at once. A
free()that fails while another failure is already in flight — the deletion of the elements already built of a sized array that failed, the release at the end of amainthat failed — does not replace it. The first failure stays the failure (its code, its message, its object, the exit code); each later one is attached to it, like Java's suppressed exceptions. Nothing is dropped and nothing is overwritten. Unhandled,mainreports the first failure and then each attached one, in order (also: error 43: free); ahandlethat consumes the failure consumes the attached ones too (their messages freed, their objects deleted). - The error's object: when a
handle(ormain) deletes the object of afail …, objand itsfree()fails, that is a new failure, starting after thehandleas if a statement there had failed.
A destructor or free() that fails does not stop the release of its object, nor that of the other objects released with it.
import fly.data.List
void main() {
List<int> l = new List<int>() // ← heap allocation
l.add(1)
l.add(2)
// … use l …
delete l // ← l.free(), then the object, then l = null
}Releasing is written by the program
From 0.16.0 every object is created with new and released by an explicit delete, and nothing else releases it: not the end of a scope, not a return, break or continue, not a failure. What costs nothing at run time is what the program writes (fly-lang/fly#321).
-
Locals. A function deletes its objects before it leaves, on every path that must release them. A failure that propagates out of a function does not delete its locals: a function that must release them catches the failure with
handle, deletes, and fails again.int compute() { Res r = new Res() int v = 0 handle { v = step(r) // may fail } bool failed = error delete r if failed { fail 50, "compute" } return v } -
Fields. An object's fields are the class's to release: its destructor deletes them (the base classes' destructors run after it by themselves), or the caller deletes them before the
delete. A class may hold a field of its own type, so a linked list is released node by node by its destructor. For a long chain, walk it with a loop rather thandelete this.next(see Destructors): each nesteddeletetakes a level of the stack.public class Box { Res inner public Box() { this.inner = new Res() } delete() { delete this.inner } } void main() { Box b = new Box() delete b // ← Box's delete() deletes b.inner, then the Box goes } -
Returned objects. A function that returns an object hands it to the caller, which deletes it; a function that returns a value computed from its objects computes it first, then deletes them, then returns the value.
Destruction follows the real class. An object is destroyed as the class it was created with, whatever the type of the reference that lets it go: delete through a base class or an interface runs the destructor of the object's own class, then those of its bases.
public class Shape {
}
public class Poly : Shape {
Res points
public Poly() {
this.points = new Res() // a field only Poly declares
}
delete() {
delete this.points
}
}
void main() {
Shape s = new Poly()
delete s // ← Poly's delete() deletes s.points, then the Poly goes
}Destructors: delete()
From 0.16.0 a class releases what it owns in its destructor, delete() (fly-lang/fly#322): a member written like a constructor, named by the reserved word delete — the statement that runs it.
-
Shape.
deleteand empty parentheses, no parameters, no return type, no modifier (public,privateorprotectedon it is an error: everydeletecan run it). A class has at most one. A struct, an interface or an enum has none. Each of these is a compile-time error:destructor 'delete()': a destructor takes no parameters.deleteis a reserved word, so no method can have that name:void delete()is a destructor written with a return type (an error), never a method. -
Only
deleteruns it. It is never called (x.delete()does not exist).delete xruns the destructor of the object's dynamic class through the release entry of its method table, then frees the object: no cost beyond the call. -
The base classes. After its own body, a destructor runs its base class's destructor, and so on up the hierarchy: derived first, base last. A class without a destructor whose base has one runs the base's. A base destructor is never called by hand.
-
A destructor that fails is a failure of the
delete(see A destructor orfree()that fails): the base destructors still run and the object is still freed. -
A
newthat fails runs no destructor: the object was never complete. -
The object being deleted is dying while its destructors run: a
deletethat reaches it again from them (a cycle, a field that refers back to it) stops the program witherror 134: double delete of a '…'(fly-lang/fly#334). -
Long chains. A destructor that deletes the next node (
delete this.next) runs one destructor inside the other, one stack level per node: a list of a few tens of thousands of nodes overflows the 8 MB stack (fatal error: stack overflow). For a chain that can be long, detach each node before deleting it, so its own destructor finds nothing to follow:public class Node { Node next delete() { Node n = this.next this.next = null while n != null { Node m = n.next n.next = null // n's destructor sees no next delete n n = m } } } -
Objects left at the end of
mainrun no destructor: the release at the end ofmainfrees their memory only (see below). -
Libraries. A library's header declares the destructor (
delete()), so a program deletes the library's objects with the library's logic, and a subclass it declares runs its own destructor, then the library's. -
free(). Up to 0.15.xdeletecalled the class'sfree()method. In 0.16.x it still does, for a class with no destructor in its hierarchy: the toolchain itself is still built by the v0.15.2 seed, which knowsfree()and not destructors. A class that has a destructor has itsfree()ignored bydelete;freebecomes an ordinary method name once the toolchain moves to destructors.
public class Base {
Res a
public Base() {
this.a = new Res()
}
delete() {
delete this.a // runs second
}
}
public class Leaf : Base {
Res b
public Leaf() {
super()
this.b = new Res()
}
delete() {
delete this.b // runs first; Base's delete() follows by itself
}
}
new unique, new shared and weak were removed in 0.16.0 (fly-lang/fly#321). From 0.15.0 to 0.15.x new unique gave an object one owner, released at the end of its scope, new shared counted its holders, and weak h observed a shared object; they could not be made correct without a cost at run time in every program (an ownership check across returns, a reference count on every copy). Each is now a compile-time error that names the replacement:
main.fly:8:13: error: 'new unique' was removed from the language: create the object with 'new' and release it with an explicit 'delete'
A
newrequiresdelete. From 0.16.0 an object belongs to the program until adeletereleases it: leaving the scope of the variable that holds it releases nothing, and an object that is never deleted is reported at the end ofmain(see below). In 0.15.x a local initialized directly withnewthat had not escaped (passed to a call or assigned elsewhere) was still released at the end of its scope — only the object, not what itsfree()would release. Up to 0.14.x there was nodelete: classes exposedfree()and the caller invoked it.
Strings: managed automatically
string values are heap-backed but managed for you. A non-const string variable with an initializer owns its buffer: the compiler frees it at scope exit, and reassigning the variable frees the previous buffer before storing the new one. const strings and uninitialized strings point at static/null data and are never freed.
void demo() {
string s = str.toUpper("hello") // owns a heap buffer
s = str.toLower("WORLD") // old buffer freed automatically before reassignment
} // ← final buffer freed automatically at scope exit
Every slot that holds a string owns it (from 0.16.0): a local, a field, an element of an array, a member of a struct. A store copies the string into the slot, an assignment frees the buffer it replaces, and the container frees what it holds when it goes — an object at its delete, an array with its last reference, a struct at the end of its scope. Up to 0.15.x only locals did: a field or an element was never freed (a string field leaked at every delete) and an element kept the very buffer it was given.
The rule that makes this work. Everything above follows from one invariant: every owned string slot holds a buffer that nothing else owns. That is what lets the compiler free at scope exit unconditionally, with no escape analysis and no reference counting. Storing into an owned slot therefore takes one of three forms, chosen by what the right-hand side is:
| Right-hand side | What is stored | Why |
|---|---|---|
| a string literal | a fresh heap copy of the constant | the constant lives in static memory and must never be freed |
| a string lvalue — variable, parameter, field, member, array element | a deep clone of its buffer | the original still owns its buffer; sharing it would free it twice |
| a fresh producer — a call result, a concatenation | the buffer as-is, moved | it is already unique and unowned, so copying it would be waste |
void demo(const string param) {
string a = "hello" // copy of the constant
string b = a // deep clone — a and b own different buffers
string c = param // deep clone — the caller still owns param's buffer
string d = a + b // moved — the concatenation's buffer was already fresh
} // ← a, b, c and d each free their own buffer
The empty string is the one case that goes the other way: it owns no heap at all, so cloning it allocates nothing and freeing it is a no-op.
Because return <lvalue> is lowered to that same assignment, a function that returns a borrowed string — a parameter or a field — returns a clone. That is what makes every call result a fresh buffer, and why the third row above is safe.
Arrays: reference-counted, freed automatically
An array is a fat pointer, {data, size}, held in the variable's own storage. The elements live in a heap buffer preceded by an 8-byte reference count:
variable heap buffer
┌────────┬──────┐ ┌──────────┬─────────────────────┐
│ data │ size │ │ refcount │ element 0, 1, 2, … │
└───┬────┴──────┘ └──────────┴─────────────────────┘
│ ◄─8 bytes─►▲
└─────────────────────────── points HERE
Arrays therefore have reference semantics, and this is the one place where Fly deliberately diverges from the rest of the language — structs and strings copy, arrays do not:
void demo() {
int[] k = {1, 2, 3}
int[] j = k // NO copy: one buffer, two names, count = 2
j[0] = 9
int x = k[0] // ← 9. The write through j is visible through k.
} // ← k releases (count 1), then j releases (count 0) → the buffer is freed, once
The rules, all of them:
- Declaring an array variable makes it an owner: it holds a reference and releases it at scope exit. The buffer goes back when the last owner releases it.
- Binding another array (
int[] j = k) copies the fat pointer and retains. No element is ever copied, whatever the array's size. - Reassigning (
k = {7, 8}) retains the new buffer, releases the old one, then stores — in that order, sok = kis harmless. - Passing as an argument is a borrow: no retain, no release. The callee sees the array for the duration of the call.
- Returning an array transfers ownership to the caller: the callee retains on the caller's behalf, then its own variable releases, leaving the caller holding the only reference.
- The item of a
for inis a view of the element, not an owner. - Nested arrays (
int[][]) have one buffer and one count per level. Releasing the outer array walks its elements and releases each inner buffer first. - An empty array (
int[0], or a runtime size of zero) has no buffer at all. Declaring, binding and iterating one are all legal and allocate nothing.
The ownership rule. An array owns its buffer and the values its elements hold (from 0.16.0): when the last reference goes, each string element is freed, each array element loses one reference (an inner array is itself reference counted, so what it receives is a decrement, not a free), and each struct element releases its own strings and arrays. It never deletes the objects its elements refer to: every object is released by whoever is responsible for it, exactly as in the summary table below.
Two consequences deserve stating plainly.
An array of classes is born full, but the instances are yours. Declaring C[3] builds three distinct instances, one per index, with C's no-argument constructor — every class has one, implicitly, when it does not declare it. They are ordinary new allocations and follow the class convention: the array releasing its buffer does not free them.
void demo() {
Cell[3] cells // three separate instances, already constructed
Cell first = cells[0]
first.set(7) // does not affect cells[1] or cells[2]
} // ← the buffer of pointers is freed; the three Cell instances are NOT
An element that fails stops the declaration. When the constructor or a field initializer of element k fails, C[n] cs fails with it, and from 0.16.0 nothing is left behind: element k is released as any new that fails is (its fields, then its memory, without free()), the elements already built are deleted from k-1 down to 0 (their free() runs), then the buffer goes. A sized struct array whose field initializer fails at element k stops the same way. Up to 0.15.x a failing element constructor did not stop the declaration, and a failing initializer left the elements behind.
A sized array of an interface is rejected at the declaration: an interface has no constructor to build the elements with. Supply them with an array literal instead.
A struct element is a copy. A struct variable lives on the stack, in the frame of the function that declares it, while a class instance lives on the heap. An array cannot refer to a struct where it is — that storage is gone when the function returns — so an array of structs holds the structs themselves. Writing one into the array — as an element of an array literal or by assignment to an element — copies its fields, as an assignment between two struct variables does; reading one out, or taking it as the item of a for … in, copies them again. The element and the variable then change independently:
Cell c = {tag = 5}
Cell[] cells = {c, {tag = 6}}
c.tag = 9 // cells[0].tag is still 5
cells[1] = c // a copy: cells[1].tag is 9
for each in cells {
each.tag = 0 // changes the item, not the element
}
Up to 0.15.x a struct written into an array, in a literal or by assignment, was not stored: the element read back as something else.
Elements own their values (from 0.16.0). Storing a string into an element copies it, storing an array takes one more reference to it, and the element releases what it held first; an array literal copies the strings it is given, its string literals included. The element and the variable it came from then live independently:
string[] names = {"a", "b"}
{
string s = str.toUpper("hello")
names[0] = s // a copy: "a" is freed, names[0] holds its own "HELLO"
} // ← s is freed here; names[0] is still "HELLO"
A class stored into an element is a reference, as everywhere: the array does not own the object. Up to 0.15.x an element was a borrow: it kept the very buffer it was given, so names[0] above dangled once s was freed, and nothing an element held was ever freed.
When the release happens. An owned array is released when its scope ends: where the scope falls through its end, and on every exit that leaves it early — a return, a break or continue, a failure that returns from the function, and (from 0.16.0) a failure that jumps to the end of an enclosing handle (see Handle Statement) or of a suite case. Strings are released on the same paths; objects never are (they wait for a delete).
In which order. The scopes an exit leaves are released innermost first, and within one scope the locals go last declared first (from 0.16.0), on every exit, the scope's end included. Up to 0.15.x the locals of a scope went in declaration order. Objects are deleted in the order the program writes its deletes: one whose free() reads an object declared before it is deleted first.
{
Res a = new Res()
User u = new User(a) // u keeps a plain reference to a's object
delete u // u first (its free() may use a), then a
delete a
}
Fields of array type are released with their object (from 0.16.0): the delete drops one reference, and assigning a new array to the field drops the one it held. Up to 0.15.x they were never released.
Stack size
Every Fly program reserves 8 MB of stack for its main thread, on Windows, Linux
and macOS alike. The memory is reserved, not taken: pages are used as the stack
grows. A thread started with fly.sync.spawnThread reserves the size it is given,
8 MB when it is given 0. A recursion that goes deeper ends the program with
fatal error: stack overflow.
int depth(const int n) {
if n == 0 {
return 0
}
return depth(n - 1) + 1
}
void main() {
int d = depth(20000) // runs on every platform
}
Up to 0.15.x a program linked on Windows had the linker's default of 1 MB, so the same recursion overflowed there about eight times sooner than on Linux and macOS (fly-lang/fly#350).
Summary
| Expression | Memory | Reclaimed by |
|---|---|---|
struct S = new S() | stack (alloca) | automatic at scope exit |
class C = new C() | heap (the object heap) | delete x (runs the destructor, releases, sets x to null); never deleted, it is reported and released at the end of main |
string s = … (non-const, initialized) | heap | automatic at scope exit; reassignment frees the old buffer |
const string s = … | static/null | nothing to free |
int[] xs = … / int[3] xs | heap, [refcount | elements] | reference counted: released at scope exit, freed when the last owner goes |
| an array's elements | strings and arrays: their own copy / reference; objects: wherever they came from | the array releases the strings, arrays and struct members it holds with its last reference; each object is freed by whoever is responsible for it |
a field or struct member of type string, array or struct | its own copy / reference | the container: an assignment releases the old value, delete (or the end of a struct's scope) releases the rest |
C[3] cells (array of classes) | heap buffer + one new C() per index | the buffer automatically; the instances by the class convention |
Objects never deleted: the report at the end of main
From 0.16.0 every class object lives in the runtime's object heap, which knows the live ones. When main ends, the program reports on stderr the objects it never deleted, by class, most first, and then releases them. The exit code does not change, unless a free() fails in that release (see A free() that fails). A program that deletes everything prints nothing.
namespace app
class Node {
int v
}
void main() {
Node a = new Node()
Node b = new Node()
}warning: 2 objects not deleted (32 B)
app.Node x2, 32 B
- The count includes the objects a leaked object refers to through its fields, when nothing deleted them either. A generic class is named with its type arguments (
fly.data.List<string>); a class compiled by an earlier release (a package built with 0.15.x) has no type information and is counted as(a class built by an earlier compiler). - Release. Each leaked object is then released: the memory goes, and its destructor does not run (from 0.16.0); a class without a destructor in its hierarchy has its
free()run, asdeletewould. An object is released before the objects its fields refer to, so afree()still finds them (and may delete them); objects that refer to each other are released once each. ABufWriternobody closed writes out its buffered bytes. Afree()that fails here is reported after the list: aserror <code>: <message>, which sets the exit code, whenmainended cleanly; asalso: error …after the failure of amainthat failed. Throughfly.os.env.exitit is reported and the exit code stays the one given toexit. - When. When
mainreturns or ends with an unhandledfail, and also when the program ends throughfly.os.env.exit. Not after a run-time trap (error 134,error 2989…) or a crash: a broken program is not walked. - Static fields. The object a static field refers to, and the objects reached from it through fields, live to the end of the program by design: it is not counted, whether an initializer or the code stored it (from 0.16.0), and it is released with the rest, its
free()included. An object reached only through an array or a collection that a static field holds is counted: a collection does not own its elements. - Test suites. A suite's generated
mainreports at its end like any program, and eachcasethat leaves objects alive gets a line under its result — a warning, the case still passes (see the Testing page). - Not covered. Strings and arrays (released automatically), raw
fly.memblocks, structs (stack). From 0.16.0 the toolchain (fly,fly-lsp,fly-registry) deletes what it allocates and reports like any program.
6.7 Generics
Fly supports generic classes and generic functions via monomorphization. Each unique instantiation is compiled into a distinct, fully specialized implementation — no type erasure, no boxing overhead, no runtime cost.
6.7.1 Generic Class Declaration
Add one or more type parameters in angle brackets after the class name.
Syntax:
GenericClass ::= [ Modifiers ] 'class' Identifier '<' TypeParam ( ',' TypeParam )* '>' [ ':' BaseType ( ',' BaseType )* ] '{' ClassMember* '}'
TypeParam ::= Identifier [ ':' Type ]
A type parameter may carry an optional bound after a colon (<T : SomeType>), constraining the types it can be instantiated with. The list names at least one type parameter: class Box<> {} is an error from 0.16.0 (a class that is not generic has no <>).
Example:
public class Wrapper<T> {
private T value
public Wrapper(T v) {
value = v
}
public T get() {
return value
}
public void set(T v) {
value = v
}
}6.7.2 Instantiation
Provide concrete type arguments in angle brackets when declaring a variable. Each unique combination of type arguments produces a separate monomorphized type at compile time.
import fly.data
void main() {
// Wrapper<string> — holds a string
Wrapper<string> ws = new Wrapper<string>("hello")
string s = ws.get() // s = "hello"
ws.set("world")
// Wrapper<int> — holds an int
Wrapper<int> wi = new Wrapper<int>(42)
int n = wi.get() // n = 42
// Wrapper<bool>
Wrapper<bool> wb = new Wrapper<bool>(true)
bool b = wb.get() // b = true
}
Wrapper<string> and Wrapper<int> are entirely separate types: the compiler emits a distinct LLVM struct and a distinct set of methods for each instantiation.
6.7.3 Generic Functions
Functions can also declare type parameters, placed between the function name and the parameter list.
Syntax:
GenericFunc ::= [ Modifiers ] ReturnType Identifier '<' TypeParam ( ',' TypeParam )* '>' '(' [ Parameters ] ')' Block
TypeParam ::= Identifier [ ':' Type ]
The type argument is inferred from the call's arguments — and only from them. A generic function is called like any other, with no <…> at the call site:
// Generic identity function — returns its argument unchanged
T identity<T>(const T v) {
return v
}
void main() {
int i = identity(10) // T inferred as int
string s = identity("fly") // T inferred as string
bool b = identity(true) // T inferred as bool
}
Explicit type arguments are for generic classes, not functions.
new Wrapper<int>(42)is how you name an instantiation (6.7.2);identity<int>(10)does not compile — the compiler reads<as a comparison and reports thatidentityis a function, not a value. Writeidentity(10)instead.It follows that a type parameter must appear among the parameters: one that shows up only in the return type (
T make<T>()) has nothing to be inferred from, and such a function cannot be called.
Each type parameter is bound by the first argument that gives it, either a parameter of
type T or an array parameter T[] (an int[] binds T to int). The call is then checked
like a call to the specialized function: as many arguments as parameters (fewer when the
rest have defaults), and every argument must fit its parameter type, with the usual
conversions. A mismatch is the usual no function or method named '…' matches this call:
T pick<T>(const T a, const T b) {
return b
}
T last<T>(const T[] xs) {
T r
for x in xs {
r = x
}
return r
}
void main() {
int[] xs = {3, 4}
long big = 4294967296
int n = last(xs) // T bound to int through T[]
long l = pick(big, 2) // T is long; the int 2 widens to long
int y = pick(1, "hello") // error: T is int, "hello" is not an int
int z = pick(1, 2, 3) // error: pick takes two arguments
}
A generic function is found like any other function: a bare name in the caller's scope (its file, its namespace, what it imports), a name written with a namespace in that namespace. Two namespaces may each declare a generic function of the same name, and each call reaches the one it names:
import one.a
import two.b
void main() {
int x = a.pick(1) // one.a's pick
int y = b.pick(1) // two.b's pick
}6.7.4 Managing a List of Strings — fly.data.List<string> Pattern
fly.data.List is an untyped dynamic array that stores long values (raw integers or object addresses). To maintain a typed list of strings, wrap each string in a Wrapper<string> and store the wrapper reference in the list. Retrieve the wrapper and call .get() to recover the string.
import fly.data.list
import fly.data.wrapper
void main() {
List lst = new List()
// Box each string into a Wrapper<string>
Wrapper<string> a = new Wrapper<string>("apple")
Wrapper<string> b = new Wrapper<string>("banana")
Wrapper<string> c = new Wrapper<string>("cherry")
lst.add(a)
lst.add(b)
lst.add(c)
// Iterate — retrieve wrapper, then unwrap the string
int total = lst.size() // total = 3
for int i = 0; i < total; i++ {
Wrapper<string> item = lst.get(i)
string text = item.get()
// use text …
}
lst.free()
}
The same pattern applies to any heap-allocated type: Wrapper<int>, Wrapper<MyClass>, etc.
| Goal | Approach |
|---|---|
| Store strings in a list | Wrapper<string> + List |
| Store ints in a list | Wrapper<int> + List (or raw long directly) |
| Single typed value | Wrapper<T> alone |
7. Enumerations
7.1 Enum Declaration
Enumerations define a set of named constants. Enums cannot extend any other type.
An enum has at least one constant (a variable of the enum starts at the first one), each constant is named once, and neither the enum nor a constant may be named by a reserved word (2.1). From 0.16.0 each is a compile error: enum 'Mode' declares no constant: an enum has at least one, constant 'ON' is declared twice in enum 'Mode', 'while' is a reserved word and cannot be used as a name. Up to 0.15.x they were accepted.
Syntax:
Enum ::= [ Modifiers ] 'enum' Identifier '{' EnumEntryList '}'
EnumEntryList ::= EnumEntry ( ',' EnumEntry )*
EnumEntry ::= Identifier
Examples:
// Simple enum with comma-separated entries
enum Color {
RED, GREEN, BLUE
}
// Public enum
public enum Status {
IDLE, RUNNING, STOPPED, FAILED
}
// Multi-line enum for readability
enum Direction {
NORTH,
SOUTH,
EAST,
WEST
}7.2 Using Enums
Examples:
void processColor() {
// Declare and initialize
Color c = Color.RED
// Assignment
c = Color.BLUE
// Pass to function
setColor(Color.GREEN)
// Compare
if c == Color.RED {
// handle red
}
}
void setColor(const Color c) {
// use color
}
Every constant has a .value — its position in the declaration, from 0
(Color.RED.value is 0, Color.BLUE.value is 2) — and a .name, the declared
identifier ("RED"); both work on a constant and on a variable. An enum variable
declared without an initializer holds the first constant: after Color c,
c == Color.RED is true. Up to v0.15.2 values started at 1 and an uninitialized
enum variable equalled none of the constants.
8. Expressions
8.1 Primary Expressions
8.1.1 Literals
42 // integer literal
3.14 // float literal
true // boolean literal
"string" // string literal
null // null literal8.1.2 Identifiers
myVariable // simple identifier
obj.field // member access
array[0] // array access8.1.3 Array Subscript
xs[i] reads or writes one element of an array. The index is any integer expression; the element takes the array's element type.
int[] k = {5, 6, 7}
int x = k[1] // read → 6
k[0] = 40 // write
int y = k[x - 5] // the index is an ordinary expression
Both forms are bounds-checked at run time, and on both sides: the index is compared against the array's size field and must satisfy 0 <= i < size. A negative index is caught as surely as one past the end — the check is signed precisely so it can be.
An out-of-range access fails with the dedicated error code 2989 (0x0BAD; a shift count out of range fails with 2990, a conversion from a floating-point value out of range with 2991, a sized array declared with a negative size with 2992, from 0.16.0), which behaves like any other fail: it propagates to the caller, sets the exit code of main, and can be intercepted with handle. Its message says where: uncaught, the program prints error 2989: index out of range at main.fly:4:5.
Reading the code from a shell.
mainreturns 2989 on every platform, but POSIX passes only the low 8 bits of a process status throughwait(), so a Unix shell reports173. Windows preserves the full value. Intercepting withhandle— below — is unaffected and is the portable way to inspect the code.
void demo() {
int[] k = {5, 6, 7}
handle {
int bad = k[9] // out of range → fail 2989
}
bool caught = error // ← true; execution continues after the handle
}
A caught failure leaves the array — and every other local — untouched and still usable: control resumes in the same scope, so nothing is released early.
What the subscript yields depends on the element type, and follows the ownership rules of §6.6: a number is a value, a class element is the instance itself (a reference), a struct element is copied by value, and a string element is a borrow that is cloned when it is bound to an owned slot.
Note. Chaining a subscript directly into a member access —
cells[0].set(7)— is accepted by the self-host compiler but not by the reference, whose subscript does not chain. For code that must build with either, bind the element first:Cell c = cells[0]thenc.set(7).
8.1.4 Parenthesized Expressions
(a + b)
(x * y + z)8.2 Unary Expressions
Syntax:
UnaryExpr ::= ( '++' | '--' | '!' | '-' ) Expression
| Expression ( '++' | '--' )
Unary - negates any numeric operand (-5, -x, -(a * 2), -2.5).
There is no unary +. Postfix ++/-- bind same-line only — a
++/-- at the start of a line is always a prefix statement.
Examples:
// Pre-increment/decrement
++counter
--index
// Post-increment/decrement
value++
count--
// Logical negation
!flag
!isActive
// Unary minus/plus
-value
+number8.3 Binary Expressions
8.3.1 Arithmetic Operators
a + b // addition
x - y // subtraction
m * n // multiplication
p / q // division
r % s // modulo
Integer / truncates toward zero and % takes the sign of the dividend
(-17 / 5 is -3, -17 % 5 is -2). From 0.15.0 both are checked in every
build:
- a zero divisor stops the program with
error 134: division by zero at main.fly:2:5and exit code 134; - the minimum value of a signed type divided by
-1(-2147483648 / -1, whose result does not fit) stops it witherror 134: integer overflow: the minimum value divided by -1 at …; %by-1is always0, the minimum value included.
The compound forms /= and %= are checked the same way. A constant divisor
(x / 2) costs nothing: the check is resolved at compile time. Floating-point
division follows IEEE 754 instead: 1.0 / 0.0 is infinity, not a trap.
On float and double, % is the remainder of the division with the sign of the
dividend, like C's fmod: 7.5 % 2.0 is 1.5, -7.5 % 2.0 is -1.5 (from 0.16.0;
up to 0.15.x it stopped the compiler with an internal error).
+, - and * on integers are checked in every build from 0.15.0 too, like
++, -- and unary -: a result that does not fit its type stops the program
with error 134: integer overflow in '+' at main.fly:2:5. That covers signed and
unsigned types alike (uint 3 - 5 stops), and a compound assignment computed in
a wider type must still fit its variable (short s = 32000; s += 1000 stops with
the result does not fit in 'short'). Not checked: pointer arithmetic (address
offsets wrap by design), shifts and bitwise operators, and explicit casts
((byte)300 is 44). When the wrapping result is the point — a hash, a checksum,
a random generator — ask for it: math.wrapAdd(a, b) and its siblings in fly.math.
What is certain to stop is a compile-time error (from 0.16.0, fly-lang/fly#200). An expression whose operands are constants is computed by the compiler, and where the program would stop on it, the compiler stops instead, at the operator:
int a = 2147483647 + 1 // error: integer overflow in '+': the result of these
// constants does not fit 'int'
long l = 2147483647 + 1 // the same error: the sum is computed in int;
long ok = (long)2147483647 + 1 // computed in long: 2147483648
int b = -(-2147483647 - 1) // error: integer overflow in '-'
int c = x % 0 // error: division by zero in '%' (any dividend)
int d = 1 << 40 // error: shift count 40 out of range for 'int'
The same rule as at run time decides: the operator's type is the type of its
operands, not of where the result is stored. Up to 0.15.x an overflow between
constants wrapped silently (2147483647 + 1 was -2147483648, 65536 * 65536
was 0), and a division by the constant 0 or a constant shift count out of range
stopped only when the program ran.
8.3.2 Comparison Operators
a == b // equal to
x != y // not equal to
m < n // less than
p > q // greater than
i <= j // less than or equal
k >= l // greater than or equal
Numbers of different types compare in their common type (int with long as long,
an integer with a double as double). On floating-point values the comparisons follow
IEEE 754: NaN is unordered, so every comparison with it is false except !=, which
is always the opposite of == (n != n is true when n is NaN; up to 0.15.x it was
false). A bool orders false before true.
Two strings compare byte by byte (from 0.16.0): == when they have the same bytes,
< <= > >= in the order of str.compare — the first byte that differs decides,
read as unsigned (for UTF-8 text, the order of the code points), and a prefix sorts
first:
"abc" < "abd" // true
"ab" < "abc" // true: a prefix sorts first
"b" > "abc" // true: the first byte decides
"abc" <= "abc" // true
Up to 0.15.x < <= > >= on strings compiled as ==.
Arrays are not compared: a == b, a < b and the others on an array are a compile
error (this operator cannot be applied to operands of type 'array' and 'array',
from 0.16.0; up to 0.15.x an internal error of the compiler). Compare the elements
in a loop.
8.3.3 Logical Operators
flag1 && flag2 // logical AND
cond1 || cond2 // logical OR
Both operators short-circuit: the right operand is evaluated only when the
left one does not already decide the result. a && f() never calls f() when
a is false, and a || f() never calls f() when a is true — so the
right operand may safely guard on the left (p != null && p.ready()).
8.3.4 Bitwise Operators
a & b // bitwise AND
x | y // bitwise OR
m ^ n // bitwise XOR
p << 2 // left shift
q >> 1 // right shift
A shift count must be at least 0 and less than the width of the type (32 for an
int): 1 << 32 and 1 << -1 fail (from 0.16.0) with the code 2990 and
shift count out of range at main.fly:4:12, like an index out of range (a
handle catches it). >> is arithmetic on a signed type (-8 >> 1 is -4) and
logical on an unsigned one. Up to 0.15.x the result was undefined: the CPU's
masked count at -O0 (1 << 40 was 256), whatever the optimizer derived above it.
8.4 Assignment Expressions
Syntax:
Assignment ::= Identifier AssignOp Expression
AssignOp ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
| '&=' | '|=' | '^=' | '<<=' | '>>='
Examples:
// Simple assignment
x = 10
name = "Fly"
// Compound assignment
a += 5 // a = a + 5
b -= 3 // b = b - 3
c *= 2 // c = c * 2
d /= 4 // d = d / 4
e %= 7 // e = e % 7
// Bitwise compound assignment
f &= mask // f = f & mask
g |= flag // g = g | flag
h ^= toggle // h = h ^ toggle
i <<= 2 // i = i << 2
j >>= 1 // j = j >> 1
// Appending to a string
s += "!" // s = s + "!"
+= appends to a string variable, field or array element, as s = s + t
does, with s evaluated once; the old value is released after the new one is
built, so s += s doubles s. No other compound operator applies to a string.
Up to 0.15.x (the v0.15.2 seed included) s += t was refused with compound assignments on strings are not yet supported by the self-host compiler.
What a class or an enum variable takes. A class value is accepted where its own class, one of its bases or one of its interfaces is expected: in a declaration, an assignment, a return, a field initializer and a struct literal. An unrelated class, or a base where a subclass is expected, is an error (cannot assign a value of type 'Cat' to a variable of type 'Dog'); two classes with the same short name from two namespaces are named in full (probe.right.P, probe.left.P). An enum variable takes only its own enum. null, and the integer and pointer conversions of a class handle, stay as they are. Up to 0.15.x (the v0.15.2 seed included) only the kind was checked, so any class went into any class variable and any enum into any enum variable.
class Animal {
}
class Dog : Animal {
}
class Cat {
}
Animal a = new Dog() // ok: Dog derives from Animal
Dog d = new Cat() // error: Cat is not a Dog
Dog e = a // error: an Animal is not a Dog
What can be assigned. The left side of = and of a compound assignment
(+= …), and the operand of ++ and --, must be a variable, a parameter, a
field or an array element. Anything else is a compile error from 0.16.0:
3++ // error: cannot assign to a constant: only a variable, a field or an array element can be assigned
f() = 2 // error: cannot assign to the result of a call: …
x + 1 = 2 // error: cannot assign to the result of an expression: …
E.A = E.A // error: cannot assign to a constant: …
this = other // error: cannot assign to 'this': …
Up to 0.15.x most of these stopped the compiler with an internal error
(backend module verification failed), and null = null and this = other were
accepted (the second one rebound this for the rest of the method).
8.4.1 Assignment vs Equality: Important Distinction
Fly clearly distinguishes between the assignment operator = and the equality comparison operator ==:
=(Assignment): Stores a value into a variable. This is a statement-level operation.==(Equality): Compares two values for equality. This is an expression that evaluates to a boolean.
Examples:
// Assignment: stores the value 5 into variable x
x = 5
// Equality comparison: compares x with 5, evaluates to boolean
if x == 5 {
// x is equal to 5
}
// Assignment with equality comparison on right side
result = x == 5 // result gets true or false
// Complex example
a = a + 1 // a = (a + 1) - addition then assignment
b = a == 10 // b = (a == 10) - comparison then assignment
Parser Representation: Under the hood, the parser creates different AST structures:
- Assignment
a = exprcreatesASTBinaryOp(OP_BINARY_ASSIGN)with left=aand right=expr - Equality
a == bcreatesASTBinaryOp(OP_BINARY_EQ)with left=aand right=b - Assignment with equality
a = (b == c)creates nested structure:- Outer:
ASTBinaryOp(OP_BINARY_ASSIGN)with left=a - Right child:
ASTBinaryOp(OP_BINARY_EQ)with left=band right=c
- Outer:
Common Mistake:
// WRONG: Using = instead of == in condition
if x = 5 { // This assigns 5 to x, then evaluates the result
// ...
}
// CORRECT: Using == for comparison
if x == 5 { // This compares x with 5
// ...
}8.5 Ternary Conditional Expression
Syntax:
TernaryExpr ::= Condition '?' TrueExpr ':' FalseExpr
Examples:
result = condition ? valueIfTrue : valueIfFalse
max = a > b ? a : b
status = isActive ? Status.RUNNING : Status.IDLE
The two branches need a common type, which is the type of the expression:
two numbers (the wider one; a double beats any integer; at one width a
signed and an unsigned mix only as in arithmetic, see 3.1.4,
and c ? 1 : aUint is a uint), two strings, two bools, two arrays of one
type, two values of one enum, or two classes of which one derives from the
other (the base: c ? aDog : anAnimal is an Animal). null goes with a
class. Anything else is an error from 0.16.0: int x = c ? 1 : "two" gives
the two branches of '?:' have no common type: 'int' and 'string'. Up to 0.15.x
(the v0.15.2 seed included) it compiled, and read one branch as the other
type: garbage, or an invalid memory access.
8.6 Function Call Expressions
Examples:
// Function call without arguments
result = calculate()
// Function call with arguments
sum = add(10, 20)
process(x, y, z)
// Method call
obj.doSomething()
person.getName()8.7 Array Value Expressions
Examples:
// Empty array
empty = {}
// Array with values
values = {1, 2, 3, 4, 5}
matrix = {{1, 2}, {3, 4}}
Each literal allocates its own reference-counted buffer, and a nested literal allocates one per level — matrix above is three buffers, the outer one holding the two rows. They are released like any other array (see 6.6).
An empty literal allocates nothing at all.
8.8 Limits: Nesting and Expression Length
From 0.16.0 the compiler has two documented limits, so that no source, however it was written or generated, can overflow its stack:
- Nesting: at most 256 levels, blocks and expressions together. Each statement
inside a block is a level deeper than the block, an expression a level deeper
than its statement, and inside an expression each parenthesis, argument list,
prefix operator (
!,-,++,--), cast and assignment adds a level. Past it:nesting too deep (limit 256): blocks and expressions nest at most 256 levels. - Expression length: at most 4096 operators in one expression: binary
operators, assignments,
? :,.and[ ], the sub-expressions included. A long chain (x + x + x + …) is a level of the tree for each operator, though it is not nested. Past it:expression too long (limit 4096 operators): split it with intermediate variables.
int total = a1 + a2 + … + a5000 // 4999 operators: error
int part = a1 + … + a2500 // split: each expression under the limit
int total = part + a2501 + … + a5000
Both limits fit the compiler's stack with room to spare: like every Fly program it reserves 8 MB for its main thread (see Stack).
Up to 0.15.x (the v0.15.2 seed included) there was no limit, and on Windows
about 450 nested parentheses, or a chain of about 1,500 operators, stopped the
compiler with fatal error: stack overflow.
9. Statements
9.1 Expression Statements
Any expression can be used as a statement.
Examples:
// Function call
doSomething()
calculate()
// Increment/decrement
counter++
--index
// Assignment
x = 429.2 Block Statements
Syntax:
Block ::= '{' Statement* '}'
Examples:
{
int x = 10
int y = 20
int z = x + y
}9.3 If Statements
Syntax:
IfStmt ::= 'if' Expression Statement
( 'elsif' Expression Statement )*
[ 'else' Statement ]
The condition is a bool or a number, which is false when it is 0
(from 0.16.0, see Numeric Conversions).
The condition is written without parentheses around it: if (x > 0) { is an
error (the compiler suggests if x > 0 {). Parentheses inside it group as usual —
if (a + b) * 2 > c { is fine. The same holds for elsif, while, switch, for
and for-in.
Examples:
// Simple if
if condition {
// code
}
// If-else
if x > 0 {
positive = true
} else {
positive = false
}
// If-elsif-else
if a == 1 {
b = 0
} elsif a == 2 {
b = 1
} elsif a == 3 {
b = 2
} else {
b = -1
}
// Inline if (without braces)
if condition doSomething()9.4 Switch Statements
Syntax:
SwitchStmt ::= 'switch' Expression '{' CaseClause* [ DefaultClause ] '}'
CaseClause ::= 'case' Expression ( ',' Expression )* ':' Statement+
DefaultClause ::= 'default' ':' Statement*
Examples:
switch value {
case 1:
result = "one"
case 2:
result = "two"
case 3, 4:
result = "three or four"
default:
result = "other"
}
switch value {
case 0:
result = "zero"
if strict {
break // leaves the switch early
}
result = "zero, relaxed"
default:
result = "other"
}
No fall-through (from 0.15.0): when a case body ends, the switch ends — it
never continues into the next case or into default, so a break at the end of
a case is not needed (it is still allowed, and break in the middle of a body
leaves the switch early). Several values share one body by being listed in one
case: case 3, 4:. A case with no statements is a compile-time error: up to
0.14 it shared the next case's body (C stacking), and the same text must not
quietly turn into a case that does nothing. Case bodies may be braced:
case 1: { r = 10 }.
Subject and labels (checked from 0.16.0): the value a switch selects on is
an integer, a bool or an enum value — not a string, a floating value, a
pointer or an object. Each label is a constant of that type: a literal,
an enum constant (Color.RED), a static const field, or an
expression over them (2 * 3 + 1, (byte)300); a variable is not a label. A
label must fit the type of the value (case 300: over a byte is an error, as
is case -1: over a uint), an enum switch takes only the constants of its own
enum, and no value may appear as a label twice, in one case's list or across
cases. Up to 0.15.x none of this was checked: most mistakes stopped in the LLVM
backend, and a label outside the type was cut to it and matched (a byte 44
took case 300:).
Up to 0.14.x the
switchwas C-style: a case body that did not end inbreak,returnorfailfell through into the next case body, and stacked empty labels (case 3:case 4:) shared the following body.
9.5 Loop Statements
9.5.1 While Loop
Syntax:
WhileStmt ::= 'while' Expression Statement
Examples:
// While
while count < 10 {
count++
}
// Infinite loop
while true {
// loop body
if shouldBreak break
}
// Inline while
while condition doSomething()9.5.2 For Loop
Syntax:
ForStmt ::= 'for' VarDecl ( ',' VarDecl )* ';' Expression ';'
Expression ( ',' Expression )* Statement
Examples:
// Standard for loop
for int i = 0; i < 10; i++ {
// loop body
}
// Multiple initialization and post expressions
for int i = 0, int j = 10; i < j; i++, j-- {
// loop body
}
// Over an array
for int i = 0; i < length; i++ {
process(array[i])
}9.5.3 For-In Loop
Fly also provides a for-in loop that iterates a loop variable over the elements of a collection expression.
Syntax:
ForInStmt ::= 'for' Identifier 'in' Expression Statement
Examples:
// Iterate over the elements of a list
for item in items {
process(item)
}9.6 Jump Statements
9.6.1 Return Statement
return leaves the function. In a function that declares a return type it carries the value — one expression per declared type — and every path through the body must reach one. In a void function it takes no value and is used to exit early.
Syntax:
ReturnStmt ::= 'return' [ Expr { ',' Expr } ]
A value must begin on the same line as the keyword: Fly has no statement
terminator, so that is what separates return followed by a value from a bare
return followed by the next statement.
Examples:
// Hand a value back
return n * n
// One value per declared return type
return a / b, a % b
// Early exit from a void function
if done {
return
}9.6.2 Break Statement
Syntax:
BreakStmt ::= 'break'
Examples:
while true {
if condition {
break // exit loop
}
}
switch value {
case 1:
doSomething()
break // exit switch
}9.6.3 Continue Statement
Syntax:
ContinueStmt ::= 'continue'
Examples:
for int i = 0; i < 10; i++ {
if i % 2 == 0 {
continue // skip even numbers
}
process(i)
}
Nothing runs after a jump. A statement that follows return, break or
continue in the same block, or follows a nested { } block that ends in one of
them, can never run, and is a compile error:
while true {
break
count++ // error: unreachable code: the statement before it always jumps away (return, break or continue)
}
After return this was already an error; after break, continue and a nested
block it is one from 0.16.0 (up to 0.15.x the compiler stopped with an internal
error). A fail is not counted as a jump: it is commonly followed by the return
that the every-path rule asks for.
9.7 Error Handling Statements
Fly error handling is built on two keywords — fail and handle — and a built-in error type. The mechanism is not exception-based stack unwinding. Instead, every function receives a hidden first parameter: a pointer to an error struct. When fail fires, it writes into that struct and either jumps past the surrounding handle block (if one exists in the same function) or returns immediately.
A failure cannot be ignored (since 0.15.1). After every call to a Fly function the caller checks the struct: if the callee failed, the caller stops right there and takes the same exit its own fail would take — out of the enclosing handle, or a return to its caller. So the error travels up the call stack, one frame at a time, until a handle stops it; an error nobody handles ends the program from main.
9.7.1 The Error Type
The error type is a built-in type that holds the result of a fail. Internally it is:
%error = type { i32 code, ptr str_ptr, ptr obj_ptr }
code— integer code. Non-zero means an error occurred.str_ptr— pointer to an error string (null if none).obj_ptr— pointer to an error object (null if none).
From Fly code you declare an error variable and test it with if:
error err // declare
// …
if error { /* error occurred */ }9.7.2 Fail Statement
fail signals an error. It accepts zero, one, two, or three comma-separated arguments (integer, string, and/or object instance, in any order and combination, up to one of each).
Syntax:
FailStmt ::= 'fail' [ Expr [ ',' Expr [ ',' Expr ] ] ]
Forms:
fail // code = 1, no message, no object
fail 404 // code = 404
fail "file not found" // str = "file not found", code = 1
fail new MyError() // obj = MyError instance, code = 1
fail 404, "not found" // code = 404, str = "not found"
fail 1, "oops", new Ctx() // code = 1, str = "oops", obj = Ctx instance
The code is an int: an integer operand converts to it as an int
declaration would take it, so fail aLong, fail aUint and fail 3000000000
need a cast (the code of a fail is an 'int': a 'long' needs a cast). Any other
operand is an error, a float, a bool, an enum value (cast it: (int)e),
a struct and an array included, and so are two codes, two messages or two
objects (fail takes at most one string message). From 0.16.0; up to 0.15.x
(the v0.15.2 seed included) the compiler took them: the last code, message or
object won (the other object was never deleted), a bool or a float became
code 1, and fail 3000000000 failed with a negative code while the process
exited 0.
The error owns its object: when a handle consumes the failure, or main reports it, the object is deleted (from 0.16.0; up to 0.15.x it was only dropped from the error, and leaked). In a constructor the object cannot be this (from 0.16.0): 'this' cannot be the object of a fail in a constructor, because a constructor that fails releases the object it was building. When the object's free() fails as it is deleted, that is a new failure, after the handle (see A free() that fails).
Behavior of fail:
| Context | What happens |
|---|---|
Inside a handle block (same function) | Writes to error struct; jumps directly to the safe block (skips remaining handle body) |
Outside any handle (no enclosing handle in the current function) | Writes to error struct; returns void immediately |
Any code after fail within the same basic block is unreachable.
The operands are evaluated first, all of them, and only then written to the
error: a message may be any string expression, a call included
(fail 400, str.concat("bad field: ", name)). The error keeps its own copy of
the message, so a temporary message is moved into it.
0.15.1 and 0.15.2 wrote the code before evaluating the message: when the message came from a call (a
+with astr.convert(...)in it included, like thefly.assertmessages), the check after that call saw the code already set and the message was lost —error 1instead oferror 1: …. Fixed in 0.16.
void validate(const int age) {
if age < 0 {
fail 400, "age must be non-negative"
// unreachable
}
if age > 150 {
fail 1001
}
// continues here if no fail
}9.7.3 Automatic Error Propagation
Every function (except main) has a hidden first parameter: a pointer to the caller's error struct. When a function fails without a handle in its own body, it writes to that pointer and returns. Right after the call, the caller tests the struct's code; when it is set, the caller stops too:
- inside a
handleblock, it jumps past the block (the handle consumes the error); - inside a suite
case, it ends the case (reported as that case's failure); - otherwise it frees its locals and returns, leaving the error for its own caller.
void fetchData() {
fail 503, "service unavailable" // writes the error, returns
}
void load() {
fetchData() // failed: load returns here, the error goes on up
parse() // NOT reached
}
void main() {
load() // failed: main stops here
// main() prints "error 503: service unavailable" to stderr
// and exits with code 503
}
Nothing has to be written for this: no annotation on the function, no marker at the call. The check is a load and a branch after the call, and costs nothing else on the success path. Calls into C (the fly.bridge bridge) and the runtime intrinsics take no error pointer and are not checked.
Before 0.15.1 a failing callee returned and the caller went on with the next statement, so an error could be silently ignored. Code that relied on that now stops at the call; to go on after a failure on purpose, put the call in a
handle.
9.7.4 Handle Statement
handle creates a guarded region. Failures raised inside it — directly or in
a callee — are consumed by the handle instead of reaching the caller.
After the block, the implicit error variable tells whether the guarded
region recorded a failure.
Syntax:
HandleStmt ::= 'handle' Block
How it works:
The compiler emits two LLVM basic blocks for each handle:
handle— the guarded codesafe— the continuation (code after the handle)
When fail fires directly inside the handle body (same function), execution jumps to safe, skipping the rest of the handle body. When fail fires in a callee (at any depth), the callee returns, and the call inside the handle body jumps to safe the same way: the rest of the body is skipped.
The scopes a failure leaves are cleaned up (from 0.16.0). On its way to safe the failure releases the strings and arrays of every scope it leaves — the handle body and the blocks nested in it, innermost first — as a return does. The same holds for a failing new and an index out of range. Only the locals declared before the failure count; one whose own initializer failed holds nothing and is skipped. Up to 0.15.x those strings and arrays leaked. An object is never released by the jump (fly-lang/fly#321): code that must release it declares it before the handle and deletes it after.
Res r = new Res()
handle {
int v = boom() // fails: execution goes on after the handle
}
delete r // on both paths
On exit the handle consumes the error: the failure never propagates to
the caller, and the implicit error variable — automatically in scope after
any handle, no declaration needed — holds the outcome. It reads as a boolean:
true when the guarded block recorded a failure, false otherwise. Each
handle opens a fresh window: a later handle that stays clean resets error
to false.
The handle consumes the whole failure: its code, its message (freed) and its
object (deleted from 0.16.0: the error owns it; up to 0.15.x it was only dropped), and
the failures attached to it — those raised by a free() while it was in flight, from
0.16.0 (see A free() that fails). A
free() that fails as the handle deletes one of those objects is a new failure, which
goes on after the handle as if a statement there had failed. A later
failure starts empty — up to 0.15.2 a handled failure's message stayed behind,
and a later fail without a message, or with one built by a call, was reported
with the old text.
Forms:
1. Detect and recover:
void main() {
handle {
riskyOperation()
}
if error {
// failure recorded — take the fallback path
return
}
// success path
}
2. Discard — swallow any failure:
void main() {
handle {
riskyOperation()
anotherOp()
}
// execution always reaches here; a failure was consumed silently
}
3. Nested handles — the innermost intercepts first:
void process() {
handle {
handle {
deepOp() // a failure here sets the INNER window
}
if error {
fail // re-raise to the outer handle
}
followupOp()
}
if error {
// handle the top-level failure
}
}
Legacy form. Older code may name the variable explicitly —
error err handle { … }followed byif (err). The unnamed form with the impliciterrorvariable is the canonical syntax; the named form is deprecated and will be removed.
9.7.5 Complete Examples
Example 1: Propagation without handle
void openFile(const string path) {
if path == "" {
fail 400, "empty path"
}
}
void main() {
openFile("") // fails with 400: main stops here
openFile("/tmp") // NOT called
// main prints "error 400: empty path" and exits with code 400
}
Example 2: Intercepting with handle
void openFile(const string path) {
if path == "" { fail 400, "empty path" }
}
void main() {
handle {
openFile("") // fails: the handle body stops here
openFile("/tmp") // NOT called
}
if error {
// the 400 failure was recorded and consumed here
}
openFile("/tmp") // runs: the error did not get past the handle
}
Example 2b: Going on after a failure, on purpose
void main() {
handle { openFile("") } // a failure here is expected and dropped
handle { openFile("/tmp") } // runs whatever happened above
}
Example 3: Direct fail in handle — jumps immediately
void main() {
handle {
if someCondition {
fail 500 // jumps directly to safe block
}
neverReached() // skipped when fail fires above
}
if error { /* the failure (code 500) was recorded */ }
}
Example 4: Re-raise to caller
void inner() {
fail 503
}
void outer() {
handle {
inner()
}
if error {
fail // re-raise; outer's caller sees the error
}
}
Example 5: Object payload
class NetError {
int code
string host
}
void connect(const string host) {
NetError e = new NetError()
e.code = 503
e.host = host
fail e
}9.7.6 The Main Function and Exit Codes
main() allocates its own error struct. On exit, the compiler emits:
ret i32 load(error.code)
So the process exit code equals the error code of the last unhandled failure — 0 means clean exit. See Section 5.5 for the full behaviour table.
After the error is printed, each failure attached to it is printed on a line of its own ( also: error 43: free, from 0.16.0: a free() that failed while the error was in flight, §6.6); then its message and object are released, and the end-of-main report lists the objects the program never deleted (from 0.16.0, §6.6). A free() that fails in that release sets the exit code when main ended cleanly, and is reported as attached when it failed.
9.7.7 Key Differences from try-catch
| Feature | Fly fail/handle | Traditional try/catch |
|---|---|---|
| Signal error | fail | throw |
| Intercept | handle { } | try { } catch { } |
| Payload | int, string, or object (comma-separated, up to one each) | typed exception object |
| Stack unwinding | No — each frame returns normally (locals freed), one after the other | Yes — stack frames are unwound by the runtime |
| Callee fail bypasses rest of caller? | Yes (since 0.15.1) | Yes |
| Error propagation | automatic through the hidden pointer parameter, until a handle | automatic until caught |
| Overhead | one load + branch after each call; ordinary returns on failure | zero-cost on success; unwinder on failure |
9.8 Testing Constructs
Fly has built-in testing support based on three constructs: inline test blocks, suite declarations, and case labels. These are compiled only when the compiler runs in test mode (the --test driver flag, also implied by --suite, which additionally builds and runs the suite). Outside test mode, test blocks are stripped during semantic analysis and have no effect on the produced binary. See the Testing guide for the full runner, --suite=Name/--test=Method filters, and assertion reference.
9.8.1 Inline test Block
A test { … } block embeds test-only code inside ordinary functions. The body is parsed normally but is included in code generation only under --test.
Syntax:
TestStmt ::= 'test' Blockvoid compute() {
int result = doWork()
test {
// Only runs when compiled with --test
assert.assertEqI(result, 42, 1)
}
}
A test block is code of the function that holds it: it uses what that
function can use (the private members of its class, the private functions of
its file, its namespace) and nothing more. The freedom of a suite
(9.8.2) does not extend to it.
9.8.2 suite Declaration
A suite is a declaration that groups related tests. It is declared like a class (same modifiers and member syntax) but uses the suite keyword and has no constructors.
Syntax:
Suite ::= [ Modifiers ] 'suite' Identifier '{' SuiteMember* '}'public suite MathTests {
void additionsTest() {
case "adds positives": {
assert.assertEqI(add(2, 3), 5, 1)
}
case "adds negatives": {
assert.assertEqI(add(-2, -3), -5, 2)
}
}
}
A method whose name ends in Test is a test method and runs automatically;
setup() and teardown() run once before and after them; any other method is a
helper. See the Testing guide.
A suite is not subject to visibility (from 0.16.0). A suite exists to use
the code that ships, the parts that code hides included, so inside a suite
declaration no visibility check applies: a private or protected member of
a class, a private function or type of another file, and a function or type
without a modifier of another namespace are all usable. What a suite reaches
is still what its file names: the namespace it declares, if any, and the
namespaces it imports. See 11.1.
9.8.3 case Label (inside a suite method)
Inside a suite test-method body, a standalone case "label": … statement names an individual test scenario. Consecutive case statements in the same block each describe a labelled scenario. (The same case keyword is also used inside switch statements — see §9.4.)
Syntax:
SuiteCase ::= 'case' StringLiteral ':' Statement
The standard library, the runtime, the compiler and the tools are tested this way: every
*Suite.flyunderstd/test,compiler/testandtools/*/testis asuiterun byfly --suitein the bootstrap's test stages.
10. Namespaces and Imports
10.1 Namespace Declaration
Namespaces organize code and prevent name conflicts.
Syntax:
Namespace ::= 'namespace' Identifier ( '.' Identifier )*
Examples:
// Single namespace
namespace mylib
// Nested namespace (dotted notation)
namespace my.library
namespace company.project.module
Rules:
- A namespace declaration must appear before any imports or top-level declarations
- Only one namespace declaration per file
- If no namespace is declared, the file is in the default namespace. The files without a
namespaceare one namespace like any other, under the same rules (from 0.16.0): they are found under the source directories and read together, what one declares is visible in the others without animport, a function or a type may be defined once among them, and aprivateone belongs to its file. The default namespace has no name, so noimportreaches it and nothing in it can be written with a prefix: give a file anamespacewhen another namespace must use what it declares. A program whosemain.flyhas no namespace is built with every other file without one under its source directories, its suites included (outside test mode a suite is compiled but never run); the project'sManifest.flyis not one of them. Several one-file programs without a namespace in one source directory are severalmainin one namespace, an error: give each its own directory (or project), or anamespace. In the compiled program the symbols of such a file carry the file's base name. Up to 0.15.x (the v0.15.2 seed included) each file without a namespace was a namespace of its own: only the entry file was read, nothing it declared was visible from another file, and two such files compiled together (a library, a run of every suite) could declare the same class, function or enum, sharing their symbols: an object could be initialized or released as the other file's class. - A namespace is one scope spread over files. The files that declare the same
namespacesee each other's classes, functions and enums without animport, by their bare names (Counter,twice(3)), or fully qualified (probe.samens.twice(3)). The compiler reads those files from the project's sources (the current directory or each--src-dir) because the namespace is the file's own, as it reads the files of an imported namespace. An explicitimportof a symbol of the same namespace stays legal. A short prefix of the file's own namespace (samens.twice(…)insidenamespace probe.samens) is not: a prefix comes from an import of another namespace. Up to 0.15.x (the v0.15.2 seed included) the other files of the namespace were read only when something imported it, so a file used a sibling's class only afterimport probe.samens.Counter. - A namespace is the list of its segments.
a.b_canda_b.care two namespaces, and so arex.zandy.z: each may declare a functionf()or a classP, and every caller reaches its own. In the compiled program a symbol carries the namespace as it is written, with its dots, and the file of aprivatedeclaration after them, so no two namespaces spell one symbol (from 0.16.0). Up to 0.15.x (the v0.15.2 seed included) the segments were joined with_, a character a segment may contain, and the symbols of a class carried the last segment only: the secondfwas reported as already defined, a namespace could spell the symbols another one kept private (app._f_pand theprivatenames ofp.flyinnamespace app), and two libraries with a classPinx.zand iny.zdid not link together (duplicate symbol: vtable.z.P). A type named in a symbol (the type of a parameter, the argument of a generic specialization) is spelled the same way, with its namespace, and a specialization as it is written (Box<int>): two overloads that differ by whichPthey take are two symbols, in a library too. A library built by 0.15.x does not link into a 0.16.0 program. - A source file is UTF-8, with or without a byte order mark (from 0.16.0: up to 0.15.x a file that opened with one did not compile). An empty file is a module without declarations, like a file of blank lines (up to 0.15.x:
cannot read input file). Only declarations live at the top level: a variable there (int calls = 0) is an error that says so — declare it inside a function, or as a static field of a class (fly-lang/fly#343). - A source file is identified by its path. Two files with the same base name in different directories (
a/p.flyinnamespace a,b/p.flyinnamespace b) are two files and both are read; a file in a subdirectory may be named like the entry file too. Up to 0.15.x (the v0.15.2 seed included) the compiler listed the files it had read by base name and skipped the second one: what it declared was missing (unknown type 'P',cannot find 'b' in this scope), with no message about the file.
// parts.fly
namespace probe.samens
public int twice(const int n) {
return n * 2
}// main.fly
namespace probe.samens
void main() {
int t = twice(3) // no import: same namespace
}
- One definition per name in a namespace. Two functions of one namespace with the same name and the same parameter types are an error from 0.16.0, whether they are in one file or in two: the error is on the second, with a note at the first. Two types of the same name (class, struct, interface or enum, in any mix) in one namespace are an error in the same way. The files without a
namespaceare one namespace too, the default one, and checked together: the error then saysin the default namespace. Overloads stay legal: they differ in their parameter types. Two classes or enums with the same short name in two namespaces (probe.left.P,probe.right.P) are two types, soh(probe.left.P)andh(probe.right.P)are two overloads, as arek(Box<probe.left.P>)andk(Box<probe.right.P>), and each call picks its own; up to 0.15.x types were compared by their short name and the secondhwas reported as already defined. Up to 0.15.x (the v0.15.2 seed included) only two functions in one file were reported; across files the program compiled and which body ran depended on the link order, and a type declared twice was taken without a word. - A
privatefunction or type stays in its file. A top-levelprivatefunction, class, struct, interface or enum is not part of what the namespace shares: the other files of the namespace do not see it, and neither does a file that imports the namespace (see 11.1). Two files of one namespace may each declare aprivatefunction or type of the same name, each using its own; aprivateone and one of the same name that the whole namespace sees are still two definitions of a name, and an error. Up to 0.15.x (the v0.15.2 seed included)privateat the top level was not checked.
10.2 Import Declaration
Imports make symbols from other namespaces available. Fly supports four import forms, all modelled on Java-style imports.
Syntax:
Import ::= 'import' Name ( '.' Name )* // namespace import
| 'import' Name ( '.' Name )* '.' '*' // wildcard import
| 'import' Name ( '.' Name )* 'as' Name ( '.' Name )* // alias import10.2.1 Namespace import
Brings the last namespace segment into scope. Access symbols with the segment prefix.
import fly.str // 'str' is in scope
import fly.os.time // 'time' is in scope
void main() {
int n = str.len("hello") // qualified access
Time t = time.now()
}
The prefix names the namespace's types as well as its functions, in every type position: a declaration, a parameter, a return type, a field, a type argument, an array (left.P[] ps as a parameter, left.P[2] all or probe.left.P[] some = {} as a local) and a new (left.P p = new left.P() after import probe.left). new also takes the full path (new probe.left.P()). A dotted type name must start with a namespace, in full or as the prefix of an import: zzz.P, where zzz is neither, is an unknown type. Up to 0.15.x (the v0.15.2 seed included) the prefix of a namespace with more than one segment named only functions, new took no dotted name, and an unknown prefix fell back to the bare name (zzz.P was any P in scope); a local array with a dotted element type was not read as a declaration (probe.left.P[2] all was taken for an index into a member, left.P[] some = {} did not parse).
The prefix also reaches what a type holds. An enum value takes it wherever a value is written — an initializer, an assignment, a comparison, a case label, an argument, a return — by the full path (probe.left.Mode.ON) or through the import (left.Mode.ON), and so does a static member of a class (left.P.count, left.P.twice(2)). A local variable named like the prefix shadows it, as for a call. Up to 0.15.x (the v0.15.2 seed included) the type itself had to be in scope (import probe.left.Mode, then Mode.ON): with a prefix the value was an error ('probe' is a namespace, not a value, cannot find 'left' in this scope).
A namespace import binds only the prefix — it does not bring the namespace's members into scope, so bare calls are an error:
import fly.str
void main() {
int n = len("hello") // → compile error: no function 'len' in scope
// (use str.len(...), or import fly.str.*)
}
A prefix that names a namespace of the program in full and, through an import, another
namespace is ambiguous, and an error wherever it is written (a call, a type, a new, an enum
value): the full name says which one is meant. The other namespace counts when the program has it,
as the root of a longer one too (from 0.16.0):
namespace app
import probe.util // binds the prefix `util`
import util.extra // the program also has the namespace `util`
void main() {
int a = util.twice(2) // → compile error: 'util' is a namespace and also the
// import of 'probe.util': write the full name
int b = probe.util.twice(2) // OK: the full name
int c = util.extra.one() // OK: `util.extra` names a namespace in full
}
Up to 0.15.x (the v0.15.2 seed included) the namespace written in full won and the import was
not tried: util.twice(2) was no function or method named 'twice', and the same shadowing
hit a library whose code used the short prefix when the program had a namespace of that name.
10.2.2 Class import (Java style)
When the last component of the path names a class (or enum/struct), that type is placed directly in the current scope — no prefix needed. This is the Fly equivalent of Java's import java.util.List.
import fly.data.List // 'List' class is in scope
import fly.data.Stack // 'Stack' class is in scope
void main() {
List<int> l = new List<int>() // no 'data.' prefix needed
Stack<int> s = new Stack<int>()
}
There is no coupling between the filename and the class name. The import path navigates the namespace hierarchy; the filename is irrelevant. By convention, stdlib files use the capitalized class name (list.fly → List), but this is optional for user code.
10.2.3 Wildcard import
.* brings all public symbols (classes, enums, structs, functions) declared directly in the target namespace into the current scope. The target must be a namespace — using .* on a class or function is a compile-time error.
import fly.data.* // List, Stack, Queue, Deque, Map, Set, Tree all in scope
void main() {
List<int> l = new List<int>()
Map<string, int> m = new Map<string, int>()
}// Error: fly.data.List is a class, not a namespace
import fly.data.List.* // → compile error: wildcard requires a namespace target
A wildcard import brings in the symbols, never the namespace prefix — the two forms are complementary, not overlapping:
import fly.str.*
void main() {
int n = len("hello") // OK: bare call, 'len' is in scope
int m = str.len("hello") // → compile error: 'str' is not defined in this
// scope (a wildcard does not bind the prefix;
// add `import fly.str` for prefixed calls)
}10.2.4 Alias import
Binds the imported namespace or symbol under a different local name. Cannot be combined with wildcard (.*). An aliased class or function is in scope under the alias only (import geom.Circle as C … C c = new C()); up to 0.15 the alias of a class or function import was ignored.
import fly.str as s // 's' is in scope
import fly.data.List as L
void main() {
int n = s.len("hello")
L<int> myList = new L<int>()
}10.3 Using Imported Symbols
Full example:
// File: shapes.fly
namespace geom
public class Circle {
public int radius
}
public int area(const int r) {
return r * r
}// File: main.fly — class import (Java style)
import geom.Circle
void main() {
Circle c = new Circle()
c.radius = 5
}// File: main.fly — namespace import
import geom
import geom.Circle
void main() {
int a = geom.area(5) // functions: through the prefix
Circle c = new Circle() // types: through a class import
}
From 0.16.0 the prefix names the type too (geom.Circle c = new geom.Circle(),
see above); up to 0.15.x it was for calls only. A type comes into scope under
its bare name through a class import, a wildcard import or an alias import.
// File: main.fly — wildcard import
import geom.*
void main() {
Circle c = new Circle()
int a = area(5) // function in scope too
}
10.4 Reserved namespaces
From 0.15.0, two namespaces of the standard library are reserved to the standard
library and the toolchain — that is, to modules whose namespace is fly or starts
with fly.:
fly.llvm.*— compiler intrinsics (raw string and pointer access, atomics, …);fly.runtime.*— the operating-system primitives under the std.
A call to either from any other module is an error:
main.fly:2:17: error: 'fly.runtime.proc_exit' can only be called from the standard library
(namespace fly.*): use fly.mem or a std function
User code reaches raw memory through fly.mem, and everything else through a std
function that wraps the primitive; what is missing is added to the std as a wrapper.
The unsafe code of a program is therefore found by searching for its calls to
fly.mem. Generic templates of the std (List<T>, …) keep using fly.llvm
internally: their bodies are std code wherever they are instantiated.
11. Modifiers
11.1 Visibility Modifiers
Control the accessibility of declarations.
| Modifier | Scope | Applies To |
|---|---|---|
private | The file (a function, a type); the class (a member) | Functions, classes, members |
protected | Within the class and every class derived from it | Methods and attributes of a class |
public | Accessible from anywhere | Functions, classes, members |
| (none) | The namespace (a function, a type) | Functions, classes |
For a function or a type declared outside a class the three levels nest:
private is the file, no modifier is the namespace, public is every
namespace.
Examples:
// Private function: this file only
private void internalHelper() {}
// Protected member
class Base {
protected int value
}
// Public class
public class PublicAPI {
public void exportedMethod() {}
}
// No modifier: this namespace only
void packageFunction() {}
class DefaultClass {}
A top-level private, checked by the compiler. A private function or
type (class, struct, interface, enum) declared outside a class is private to
its file: only the code of that file can call the function or name the
type. Another file gets an error that names the file, whether it belongs to the
same namespace or imports it, and however it writes the name (helper(),
app.helper(), util.helper() through an import, new P(), P.count(),
E.A).
// parts.fly
namespace app
private int helper() {
return 5
}
int open() {
return helper() // ok: same file
}// main.fly
namespace app
void main() {
int a = open() // ok: open is visible to the whole namespace
int b = helper() // error: 'helper' is private to 'parts.fly'
}
Because a private name never leaves its file, two files of one namespace may
each declare a private function or type of the same name: each file uses its
own, and the compiled program keeps them apart: their symbols carry the file,
by its base name or, when two files of the namespace share a base name in
different directories (a/p.fly, b/p.fly), by the path that tells them
apart. A private name and a name the whole namespace sees are still one
name defined twice, and an error (10.1).
A library's header (.fly.h) declares the functions and types that are
public. Two exceptions. A type that is not public and that a declaration
of the header names — in a field, a signature, a base — is declared too, with
its own modifier, and stays as closed to the program as it is from source
(from 0.16.0, see 11.1). And a
private function that a public generic function or class uses is shipped in
the header as source, with the header-private warning, because the code that
instantiates the generic must be able to call it. Its symbol carries the file
name from 0.16.0, so a library with such a function and the programs that use
it must be compiled by the same release line.
Up to 0.15.x (the v0.15.2 seed included) private at the top level was
accepted and not checked: every file that could see the namespace could use the
name, and two private functions of the same name in two files of a namespace
were one symbol defined twice.
No modifier, checked by the compiler. A function or a type (class, struct,
interface, enum) declared outside a class without a modifier is visible in its
namespace: every file of that namespace can use it, with no import
(10.1), and no file of another namespace can.
Only public opens a declaration to the other namespaces. The error names the
namespace, and it does not depend on how the name is written: through an import
prefix (util.inner()), by the full path (lib.util.inner()), or bare after
import lib.util.inner or import lib.util.*. An import brings a name in
scope; it does not make it public.
// lib/util.fly
namespace lib.util
int inner() { // no modifier: lib.util only
return 5
}
class Plain { // no modifier: lib.util only
public int v
}
public int open() {
return inner() // ok: same namespace
}// main.fly
namespace app
import lib.util
void main() {
int a = util.open() // ok: open is public
int b = util.inner() // error: 'inner' is not public in namespace 'lib.util'
util.Plain p = new util.Plain() // error: 'Plain' is not public in namespace 'lib.util'
}
A namespace is its full name: lib and lib.util are two namespaces, and
neither sees what the other declares without a modifier. The files with no
namespace are one namespace, the default one, under the same rule: they see
each other's declarations, and need public on what they use from a named
namespace.
The rule looks at where a name is written: a call of the function; the
type of a variable, a parameter, a field or a return value; new; a cast; a
base class; a type argument (List<util.Plain>); the receiver of a static
member or of an enum entry (util.Plain.count(), util.Mode.ON). A value
whose type has no modifier can still travel: when a public function of
lib.util returns a Plain, another namespace may use that value and its
public members without ever writing Plain. The members of a class follow
their own rule, below. Code that a generic function or class of lib.util
contains is code of lib.util, whichever namespace instantiates it.
Up to 0.15.x (the v0.15.2 seed included) a declaration without a modifier
could be used from every namespace of the same build. Across packages the rule
already held, because a library's header declared only what is public; from
0.16.0 a header may declare a type without a modifier that it has to name, and
the rule is applied to it as it is to source.
Member access, checked by the compiler. A private member (field, method,
constructor, static or not) is reachable only from the methods of the class that
declares it. A protected member is reachable from the methods of that class and
of every class derived from it, directly or not. The rule looks only at where
the code is, never at the receiver: inside a subclass, this.v, super.v, o.v
on another instance of the subclass and b.v on a plain Base are all allowed.
A protected constructor can be called with super(...) and with new from a
subclass only.
class Base {
protected int v
protected Base(const int v) {
this.v = v
}
}
class Derived : Base {
public Derived() {
super(1)
}
public int twice(const Base other) {
return this.v + other.v // ok: Derived derives from Base
}
}
void main() {
Derived d = new Derived()
int x = d.v // error: 'v' is protected in 'Base'
}
protected is written only on the methods and attributes of a class. On a
function, a parameter or local variable, a type, or a member of an interface,
struct or suite it is an error: none of them has subclasses to open a member to.
A private method is never overridden (from 0.16.0). It belongs to its
class alone: a call of it always runs that class's method, whatever the object
is. A subclass may declare a method with the same name and parameters, and the
two are separate methods, each class calling its own. What a private method
cannot do is take the place of a method its class inherits — from a base class
or from an interface — because a call through the base would run one method
and a call through the class the other:
class Base {
public Base() {
}
private int secret() {
return 1
}
public int run() {
return this.secret() // always Base's secret()
}
}
class Derived : Base {
public Derived() {
}
private int secret() { // ok: a method of Derived, not an override
return 2
}
private int run() { // error: private method 'run' cannot
return 3 // override 'run' of 'Base'
}
}
Up to 0.15.x (the v0.15.2 seed included) a private method was overridden
like any other: in the example run() on a Derived returned 2, and a
private run() replaced the inherited one.
An override declares const as the method it overrides (from 0.16.0).
const on a parameter decides how the argument travels: a const one by
value, a non-const one by reference, since the callee may write it back into
the caller's variable (§5.2). A call through a base class or an interface is
built from the method it names, so each parameter of an override, or of a
method implementing an interface method, must be const exactly when the
overridden one is:
interface Sink {
void put(Box b)
}
class Log : Sink {
public void put(const Box b) { // error: parameter 'b' differs in 'const' from
} // the method it overrides of 'Sink'
}
Up to 0.15.x (the v0.15.2 seed included) the difference was not checked: the
override read its arguments one indirection off, a write through them was lost
and the program could end with invalid memory access.
The same through a library (from 0.16.0). A program that takes a library
from a -L directory reads its header instead of its source, and gets the
same answers. The header of a public class lists every field, because the
layout of an object needs them all, and every method and constructor that is
not private, each with the modifiers it was declared with: protected,
static, const, final, abstract (and abstract or final on the
class). So a private field of a library class is refused with the message
above, a protected member is open to a class the program derives from it, a
static member is reached through the class, a const field cannot be
assigned, a final method cannot be overridden, and a method or constructor
without a modifier is called as it is from source. A private method or
constructor is not in the header at all: calling it is no function or method named … matches this call. A class whose constructors are all private says
so in its header, and new on it is refused as it is from source.
The methods a header lists are the ones a subclass can override, in the order
the class declares them. A program may therefore derive a class from a library
class and override its methods, wherever the library class declares its
private ones.
A type that is not public, through a library (from 0.16.0). A public
class may have a field whose type is a class, a struct or an enum of the
library that is not public; a public function or a listed method may take
or return one; a public class may derive from one. All of this is accepted
from source, and it is through -L: the header declares every such type, with
the modifier it has — none, or private — and with its members as it declares
those of a public class, and then the types that one names in turn. Types
that nothing in a header names are not declared.
// lib/shapes.fly
namespace lib.shapes
class Helper { // no modifier: its namespace
public int k
public Helper() {
this.k = 5
}
}
private struct Size { // private: its file
int w
int h
}
public class Shape {
Helper helper
Size size
public Shape() {
this.helper = new Helper()
}
public Helper help() {
return this.helper
}
public void free() {
delete this.helper
}
}
A program of another namespace uses a Shape through -L as it does from
source. It may use the value s.help() hands out, and its public members
(s.help().k); it may not write the type's name: shapes.Helper is 'Helper' is not public in namespace 'lib.shapes', and shapes.Size is 'Size' is private to 'shapes.fly', the two messages of the source. A struct field lies
inside the object, so the program needs the struct's own fields to place the
ones that follow it; that is why the declaration is complete.
Up to 0.15.x (the v0.15.2 seed included) the header named such a type without
declaring it, and no program could read it (unknown type 'Helper').
Up to 0.15.x (the v0.15.2 seed included) a header wrote a field without any
modifier, a method without static or final, a class without abstract or
final, and only the public methods: through -L a program read and wrote
the private fields of a library class, could not call a protected method
from a subclass nor reach a static field, and was allowed what const,
final and abstract forbid. A library class that declared a method or a
constructor that was not public before a public method was unusable
through its header: the call ran another method, with no diagnostic, and a
class with only private constructors could be created with new.
Inside a suite, no visibility applies (from 0.16.0). The code of a suite
declaration (9.8.2) may use every declaration of
its own namespace and of the namespaces its file imports, whatever the
modifier: a private or protected member (field, method, constructor,
static or not), a private function or type of another file, a function or
type without a modifier of another namespace. The names are written as they
would be if they were public: bare, through the import prefix, or by the full
path.
// lib/shapes.fly
namespace lib.shapes
private int hush() { // this file only
return 11
}
int inner() { // lib.shapes only
return 5
}
public class Box {
private int secret
private Box(const int v) {
this.secret = v
}
protected int half() {
return this.secret / 2
}
}// test/ShapesSuite.fly
import lib.shapes
suite ShapesSuite {
void boxTest() {
case "what lib.shapes hides": {
shapes.Box b = new shapes.Box(8) // a private constructor
int v = b.secret + b.half() // a private field, a protected method
delete b
int n = shapes.hush() + shapes.inner() // private to its file; without a modifier
}
}
}
The freedom has three limits.
- It belongs to the suite declaration: a function declared beside the
suite in the same file is ordinary code, under every rule above, and so is
a
testblock (9.8.1), which is code of the function that holds it. - A suite reaches what it imports. The default namespace has no name, so
no
importreaches it, and a suite that declares no namespace is not part of it: code that a suite must test declares anamespace. - A name must still say one thing. When two files of a namespace each
have a
privatefunction of the same name and parameter types, or aprivatetype of the same name, a suite that writes that name gets an error naming both files ('pick' is private to 'one.fly' and to 'two.fly': inside a suite the name does not say which file is meant). Private overloads that differ in their parameters are told apart by the arguments.
The rule covers code compiled from source with the suite. A library taken from
a -L directory shows what its header declares, to a suite as to any program:
the fields of its public classes and their methods that are not private,
which a suite may use whatever their modifier, and nothing else.
Up to 0.15.x (the v0.15.2 seed included) most of these checks did not exist, so a suite could reach what it wanted for that reason; as each check arrived in 0.16.0 it applied inside a suite as anywhere else.
11.2 Constant Modifier
The const modifier marks values as immutable.
Status: an assignment to a
constvariable or parameter is rejected from v0.14.9 — see Conformance.constprotects the variable itself, not the fields of an object it refers to.
Examples:
// Constant function parameter — const is optional on parameters,
// and marks the parameter read-only inside the body
void process(const int size) {
// size cannot be modified
}
// Constant local variable
void func() {
const int limit = 50
// limit = 100 // not allowed: limit is const
}11.3 Static Modifier
The static modifier creates class-level members.
Examples:
class Counter {
static int totalCount = 0
public static int getTotal() {
return totalCount
}
public void increment() {
totalCount++
}
}
void main() {
Counter c = new Counter()
c.increment()
int total = Counter.getTotal() // total = 1
}
Inside its class a static field is named bare (totalCount) or through the class (Counter.totalCount); elsewhere through the class. Its initializer is the field's initial value when it is a constant, and runs on the first use otherwise (see Field initializers in §6.4).
11.4 Combining Modifiers
Multiple modifiers can be combined. Each is written once, and a declaration has at most one of public, private and protected: from 0.16.0 private private int x (modifier 'private' is written twice) and public private int x are errors. Up to 0.15.x they were accepted, and the last visibility won.
Examples:
// In a class context
class Configuration {
// Public constant (class-level)
public const int BUFFER_SIZE = 1024
// Private static field
private static int instanceCounter = 0
// Public static constant
public static const string APP_NAME = "FlyApp"
}
// In a function
void process() {
// Constant local variable
const int maxRetries = 3
}11.5 Abstract and Final Modifiers
Two further modifiers apply mainly to type and method declarations:
| Modifier | Meaning |
|---|---|
abstract | The declaration is incomplete and must be implemented by a subtype (e.g. an abstract class or method). |
final | The declaration cannot be further extended or overridden. |
Examples:
// Abstract class — cannot be instantiated directly
public abstract class Shape {
public abstract int area()
}
// Final class — cannot be subclassed
public final class Vector2 {
int x
int y
}
From 0.16.0 the compiler holds them to that meaning: an abstract method has no body ('area': an abstract method has no body), a method without a body (abstract, with or without the word) is declared only in an abstract class or an interface, and a class is not both final and abstract ('Shape': a class cannot be both 'final' and 'abstract'). Up to 0.15.x these were accepted.
12. Comments
12.1 Line Comments
Line comments start with // and continue to the end of the line. A newline
always terminates a line comment: Fly has no line-splicing, so a backslash
at the end of the line is an ordinary comment character and does not
continue the comment onto the next line.
Examples:
// This is a line comment
int value = 42 // End-of-line comment
// Multiple line comments
// can be used for
// multi-line documentation
// A trailing backslash does not extend this comment \
int next = 1 // this line is code, not comment12.2 Block Comments
Block comments are enclosed between /* and */.
Examples:
/* This is a block comment */
/*
* Multi-line block comment
* for detailed documentation
*/
void calculate() {
/* inline comment */ return
}
Note: Block comments can span multiple lines and are preserved by the parser for documentation purposes. A block comment ends only at a literal */: since Fly has no line-splicing, a backslash-newline between * and / does not terminate the comment. A block comment, a string, a character or a raw string literal that the end of the file leaves open is a compile-time error, reported where it starts (unterminated comment: the closing '*/' is missing); from 0.16.0 that holds after the last declaration too, where up to 0.15.x an open comment was accepted (fly-lang/fly#343).
12.3 No Line Splicing
Unlike C and C++, Fly performs no line-splicing anywhere: a backslash followed by a newline is never a line continuation. Inside comments it is ordinary comment text; outside comments and string literals a stray backslash is a lexical error.
13. Grammar Summary
13.1 Program Structure
Program ::= [ Namespace ] Import* TopDecl*
Namespace ::= 'namespace' Name ( '.' Name )*
Import ::= 'import' Name ( '.' Name )*
| 'import' Name ( '.' Name )* '.' '*'
| 'import' Name ( '.' Name )* 'as' Name ( '.' Name )*
TopDecl ::= Comment
| ClassDecl
| EnumDecl
| FunctionDecl
Modifiers ::= ( 'public' | 'private' | 'protected'
| 'const' | 'static' | 'abstract' | 'final' )*13.2 Type System
Type ::= BuiltinType
| NamedType
| ArrayType
BuiltinType ::= 'void' | 'bool' | 'byte'
| 'short' | 'ushort' | 'int' | 'uint'
| 'long' | 'ulong' | 'float' | 'double'
| 'string' | 'error'
NamedType ::= Name ( '.' Name )*
ArrayType ::= Type '[' [ Expression ] ']'13.3 Declarations
ClassDecl ::= Modifiers ( 'class' | 'struct' | 'interface' | 'suite' )
Identifier [ '<' TypeParam ( ',' TypeParam )* '>' ]
[ ':' BaseType ( ',' BaseType )* ] '{' ClassMember* '}'
BaseType ::= NamedType
TypeParam ::= Identifier [ ':' Type ]
GenericFunc ::= Modifiers ReturnType Identifier
'<' TypeParam ( ',' TypeParam )* '>'
'(' [ ParamList ] ')' Block
InterfaceDecl ::= Modifiers 'interface'
Identifier [ ':' Identifier ( ',' Identifier )* ] '{' InterfaceMember* '}'
EnumDecl ::= Modifiers 'enum' Identifier '{' EnumEntryList '}'
EnumEntryList ::= EnumEntry ( ',' EnumEntry )*
EnumEntry ::= [ Modifiers ] Identifier
FunctionDecl ::= Modifiers ReturnType Identifier
[ '<' TypeParam ( ',' TypeParam )* '>' ]
'(' [ ParamList ] ')' ( Block | ';' )
ReturnType ::= Type ( ',' Type )*
ParamList ::= Param ( ',' Param )*
Param ::= [ Modifiers ] Type Identifier [ '=' Value ]
Notes:
ReturnTypeis mandatory (usevoidfor no value). Constructors — a method named like its class —, destructors (delete(), from 0.16.0) and interface methods are the only declarations that omit it.- A class may list one or more base types after
:(a base struct and/or interfaces). Structs extend only structs, interfaces extend only interfaces (one or more), and enums cannot extend anything.
13.4 Statements
Statement ::= Block
| IfStmt
| SwitchStmt
| WhileStmt
| ForStmt
| ForInStmt
| ReturnStmt
| BreakStmt
| ContinueStmt
| FailStmt
| HandleStmt
| TestStmt
| ExprStmt
| VarDeclStmt
| AssignStmt
| MultiAssignStmt
Block ::= '{' Statement* '}'
IfStmt ::= 'if' Expr Statement
( 'elsif' Expr Statement )*
[ 'else' Statement ]
SwitchStmt ::= 'switch' Expr '{'
CaseClause* [ DefaultClause ] '}'
CaseClause ::= 'case' Expr ( ',' Expr )* ':' Statement+
WhileStmt ::= 'while' Expr Statement
ForStmt ::= 'for' VarDecl ( ',' VarDecl )* ';' Expr ';'
Expr ( ',' Expr )* Statement
ForInStmt ::= 'for' Identifier 'in' Expr Statement
ReturnStmt ::= 'return' [ Expr { ',' Expr } ] (* one value per declared
return type; the first must start on the keyword's line *)
BreakStmt ::= 'break'
ContinueStmt ::= 'continue'
FailStmt ::= 'fail' [ Expr [ ',' Expr [ ',' Expr ] ] ]
HandleStmt ::= 'handle' Block (* implicit `error` var after the block; the
named `error Ident handle` form is legacy *)
TestStmt ::= 'test' Block
VarDeclStmt ::= Modifiers Type Identifier [ '=' Expr ]
AssignStmt ::= Identifier AssignOp Expr
MultiAssignStmt ::= Identifier ( ',' Identifier )+ '=' CallExpr
(* every receiver is an ALREADY-DECLARED variable; the
call's return slots bind in order — see §5.4 *)13.5 Expressions
The grammar below reflects the compiler's flat precedence (six binary levels). See Appendix B for the ordering and the important note that bitwise/shift bind looser than comparisons.
Expression ::= AssignExpr
AssignExpr ::= TernaryExpr ( AssignOp AssignExpr )?
TernaryExpr ::= LogicalExpr [ '?' Expr ':' Expr ]
// One level: logical, bitwise and shift operators together
LogicalExpr ::= RelationalExpr
( ( '||' | '&&' | '|' | '&' | '^' | '<<' | '>>' ) RelationalExpr )*
// One level: equality and relational operators together
RelationalExpr ::= AddExpr
( ( '==' | '!=' | '<' | '>' | '<=' | '>=' ) AddExpr )*
AddExpr ::= MultExpr ( ( '+' | '-' ) MultExpr )*
MultExpr ::= UnaryExpr ( ( '*' | '/' | '%' ) UnaryExpr )*
UnaryExpr ::= ( '++' | '--' | '!' | '-' | '+' ) UnaryExpr
| PostfixExpr
PostfixExpr ::= PrimaryExpr ( '++' | '--' | '(' ArgList ')'
| '[' Expr ']' | '.' Identifier )*
PrimaryExpr ::= Literal
| Identifier
| '(' Expr ')'
| 'new' NamedType [ '<' TypeArg ( ',' TypeArg )* '>' ] '(' ArgList ')'
| ArrayValue
| StructValue
ArrayValue ::= '{' [ Expr ( ',' Expr )* ] '}'
StructValue ::= '{' [ Identifier '=' Value ( ',' Identifier '=' Value )* ] '}'
Literal ::= NumericLiteral | StringLiteral
| 'true' | 'false' | 'null'
AssignOp ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
| '&=' | '|=' | '^=' | '<<=' | '>>='
14. Complete Example
Here's a comprehensive example demonstrating various Fly language features:
namespace myapp
import utils
import data.models as models
// Enum declaration (enums cannot extend anything)
public enum Status {
IDLE, RUNNING, PAUSED, STOPPED
}
// Class declaration
public class Application {
// Private fields
private string name
private int value
private Status currentStatus
// Static field
static int instanceCount = 0
// Constructor — same name as the class, no return type
public Application(const string appName) {
this.name = appName
this.value = 0
this.currentStatus = Status.IDLE
instanceCount++
}
// Method with return type — `return` carries the result
public int getValue() {
return this.value
}
// Public void method with error handling
public void process() {
handle {
this.calculateResult()
}
if error {
// Error occurred
this.currentStatus = Status.STOPPED
}
}
// Private helper method that may fail
private void calculateResult() {
if this.value < 0 {
fail "Invalid value" // Fail with string message
}
if this.value > 1000 {
fail 999 // Fail with error code
}
}
// Method demonstrating void error handling
public void validate() {
error validationErr handle {
if this.name == "" {
fail "Name cannot be empty"
}
}
if validationErr {
this.currentStatus = Status.STOPPED
}
}
// Setter method
public void setValue(const int newValue) {
this.value = newValue
}
// Static method
public static void incrementCount() {
instanceCount++
}
}
// Structure declaration (struct can extend only struct)
public struct Point {
int x
int y
}
// Struct extending another struct
public struct Point3D : Point {
int z
}
// Interface declaration (interface can extend only interface)
public interface Drawable {
void draw()
}
// Class implementing an interface
public class Shape : Drawable {
private int width
private int height
public void draw() {
// drawing logic
}
}
// Main entry point
// Note: main() automatically returns 0 if all errors are handled,
// or returns 1 if an unhandled error occurs
void main() {
// Create application instance (constructor invoked by new)
Application app = new Application("MyApp")
// Error handling example: validate the application
handle app.validate()
// Set status
Status status = Status.RUNNING
// Control flow with error handling
if status == Status.RUNNING {
error processErr handle {
app.process()
}
if processErr {
// Handle error gracefully
status = Status.STOPPED
} else {
handleResult()
}
} elsif status == Status.PAUSED {
// Handle paused state
} else {
// Handle other states
}
// Loop through array
int[] numbers = {1, 2, 3, 4, 5}
for int i = 0; i < 5; i++ {
processNumber(numbers[i])
}
// While loop
int count = 0
while count < 10 {
count++
}
// Switch statement
switch count {
case 10:
// count is 10
break
default:
// other value
}
// Create structure (stack-allocated)
Point p = new Point()
p.x = 10
p.y = 20
// Error handling with structure
error distErr handle {
int dist = p.x * p.x + p.y * p.y
if dist > 1000 {
fail "Distance too large"
}
}
}
// Private void helper function
private void handleResult() {
// handle result logic
}
// Function with const parameter
private void processNumber(const int num) {
if num % 2 == 0 {
// even number
} else {
// odd number
}
}
15. Best Practices
15.1 Naming Conventions
- Classes, Structs, Enums: Use PascalCase (e.g.,
MyClass,StatusType) - Functions, Variables: Use camelCase (e.g.,
calculateTotal,userName) - Constants: Use UPPER_SNAKE_CASE (e.g.,
MAX_SIZE,DEFAULT_VALUE) - Private members: Prefix with underscore or use clear naming (e.g.,
_internal,privateHelper)
15.2 Code Organization
- One namespace per file
- Group related functionality in the same namespace
- Use imports to reference external code
- Keep functions focused and small
15.3 Error Handling
- Use
failfor unrecoverable errors - Use
handleblocks to catch and recover from errors - Validate inputs at function boundaries
15.4 Comments
- Use line comments for brief explanations
- Use block comments for detailed documentation
- Document public APIs thoroughly
- Explain complex algorithms and business logic
Appendix A: Reserved Keywords
All keywords are reserved and cannot be used as declared names (variables, parameters, fields, methods, functions, classes) — enforced from 0.15.0:
abstract as bool break byte
case class complex const continue
default delete double else elsif
enum error fail false final
float for handle if import
in int interface long namespace
new null pointer private protected
public return short static string
struct suite switch test true
uint ulong ushort void while
thisis not a reserved keyword (see Section 2.1);deleteis one from 0.15.0. Neither isout, which is now an ordinary identifier — the standard library still uses it as a parameter name for C-ABI output parameters.unique,sharedandweakare ordinary names:new unique,new sharedandweak hwere removed in 0.16.0 and are compile errors (see Releasing is written by the program).
Appendix B: Operator Precedence
Fly uses a flat precedence scheme with only six binary levels. From highest to lowest precedence (tightest to loosest binding):
- Primary / postfix / unary: literals, identifiers, calls
(), subscript[], member., then prefix/postfix++--,!, unary-. Postfix++/--bind same-line only: a leading++/--on the next line is a new prefix statement, never the previous operand's postfix. - Multiplicative:
*,/,% - Additive:
+,- - Relational & Equality (one level):
==,!=,<,>,<=,>= - Logical, Bitwise & Shift (one level):
||,&&,|,&,^,<<,>> - Ternary:
?: - Assignment (right-associative):
=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=
⚠️ Differs from C/C++/Java. Bitwise (
&|^) and shift (<<>>) operators sit at the same, looser level as the logical operators — below the comparison operators. Read the C way,a & b == cwould be(a & b) == c; in Fly it isa & (b == c).From 0.15.0 the ambiguous forms are compile-time errors, so the reading is always written out:
- two different operators of level 5 chained without parentheses —
a || b && c,x << 2 | y,a & b | c— are rejected: write(a || b) && cora || (b && c). The same operator repeated (a && b && c,m & n & 7) is fine;- a comparison as the operand of a bitwise or shift operator —
flags & mask == 0,a == b & c— is rejected: write(flags & mask) == 0. Comparisons joined by&&or||(a == b && c < d) mean the same in every language and stay legal.main.fly:4:14: error: '&' binds looser than the comparison '==' in Fly ('a & b == c' means 'a & (b == c)'): add parentheses
Appendix C: Error Handling Quick Reference
Fly uses fail and handle keywords for error handling, which differs from traditional try-catch mechanisms.
Quick Comparison
| Concept | Fly Syntax | Traditional (Java/C++) |
|---|---|---|
| Throw exception | fail | throw |
| Throw with message | fail "Error message" | throw new Exception("Error message") |
| Throw with code | fail 404 | throw 404 or custom exception |
| Catch exception | handle { ... } | try { ... } catch { ... } |
| Inspect the outcome | handle { ... } then if (error) | catch (Exception err) { ... } |
| Error type | error | Exception or custom class |
Common Patterns
// Pattern 1: Simple fail
void operation() {
fail // Throw exception
}
// Pattern 2: Fail with integer code
void check() {
fail 404 // Error code
}
// Pattern 3: Fail with string message
void load() {
fail "File not found" // Error message
}
// Pattern 4: Simple handle
handle operation() // Catch and ignore
// Pattern 5: Handle with error capture
handle {
riskyOperation()
}
if error {
// Handle error
}
// Pattern 6: Handle with recovery
handle {
computation()
}
if error {
fallbackOperation()
}Error Types
- void:
fail(no value) - integer:
fail 404,fail 500,fail -1 - string:
fail "Error message",fail "Not found" - object:
fail errorObject
Key Points
failimmediately terminates function executionhandlecatches exceptions in the enclosed blockerrortype stores exception information- Multiple operations can be wrapped in a single
handleblock - Error handling is more concise than traditional try-catch
- No exception type hierarchy needed—use simple values
main()function: Unhandled errors cause the application to return exit code 1; handled errors allow return code 0
Main Function and Exit Codes
The main() function has special error handling behavior:
void main() {
// If no error occurs or all errors are handled: returns 0
// If an unhandled error occurs: returns 1
}
Examples:
// Returns 0 (success)
void main() {
handle mayFail()
}
// Returns 1 (failure)
void main() {
mayFail() // Error not handled
}
// Returns 0 (success) - error is caught and handled
void main() {
handle {
riskyOperation()
}
if error {
// Handle gracefully
}
}
© Fly Project - https://flylang.org
Licensed under Apache License v2.0
Documentation Version 1.1 - June 2026 — revised to match the compiler (Parser / AST / Resolver): mandatory return types, constructors & this, for-in loops, generics with bounds, testing constructs, automatic memory management, and corrected operator precedence.