Appendix A: Syntax quick reference
Keywords
| Keyword |
Usage |
Example |
fn |
Function declaration |
fn add(a: int, b: int) -> int |
let |
Immutable binding |
let x: int = 42 |
var |
Mutable binding |
var count: int = 0 |
if / else |
Conditional |
if x > 0 { } else { } |
while |
Loop |
while i < 10 { i += 1 } |
for |
Iterator loop |
for item in items { } |
match |
Pattern matching |
match shape { Circle(r) => ... } |
return |
Return from function |
return 42 or bare return |
defer |
Run at scope exit |
defer { cleanup() } |
struct |
Structure definition |
struct Point { x: int, y: int } |
enum |
Enumeration / ADT |
enum Color { Red, Green, Blue } |
trait |
Trait definition |
trait Display { fn show(self) -> String } |
impl |
Implementation block |
impl Display for Point { } |
import |
Import module |
import "std/json" |
export |
Export symbol |
export fn create() -> Point |
spawn |
Launch goroutine |
spawn { do_work() } |
select |
Wait on channels |
select { case ch => { } } |
async |
Async function |
async fn fetch() -> String |
await |
Await async result |
let r: String = await fetch() |
unsafe |
Unsafe block |
unsafe { free(ptr) } |
extern |
Foreign function |
extern "C" fn puts(s: String) -> int |
true / false |
Boolean literals |
let ok: bool = true |
and / or / not |
Logical operators |
if a > 0 and b > 0 |
as |
Type cast |
let p: int = addr as int |
self |
Current instance |
fn length(self) -> int |
derive |
Derive macro |
#[derive(Clone, Debug)] |
where |
Trait constraint |
fn f() where T: Display |
type |
Type alias |
type Callback = Fn(int) -> int |
macro |
Declarative macro |
macro log!(msg) { print(msg) } |
Operators
Arithmetic
| Operator |
Meaning |
Example |
+ |
Addition / string concat |
a + b, "hi" + name |
- |
Subtraction |
a - b |
* |
Multiplication |
a * b |
/ |
Division |
a / b |
% |
Modulo |
a % 2 |
** |
Power |
2 ** 10 |
Comparison
| Operator |
Meaning |
Example |
== |
Equal |
a == b |
!= |
Not equal |
a != b |
< |
Less than |
a < b |
> |
Greater than |
a > b |
<= |
Less or equal |
a <= b |
>= |
Greater or equal |
a >= b |
Assignment
| Operator |
Meaning |
Example |
= |
Assign |
x = 42 |
+= |
Add-assign |
x += 1 |
-= |
Sub-assign |
x -= 1 |
*= |
Mul-assign |
x *= 2 |
/= |
Div-assign |
x /= 2 |
Bitwise
| Operator |
Meaning |
Example |
& |
Bitwise AND |
flags & mask |
| `\ |
` |
Bitwise OR |
`flags \ |
bit` |
^ |
Bitwise XOR |
a ^ b |
~ |
Bitwise NOT |
~mask |
<< |
Left shift |
1 << 8 |
>> |
Right shift |
value >> 4 |
Other
| Operator |
Meaning |
Example |
.. |
Range |
0..10 |
| `\ |
>` |
Pipe |
`data \ |
> transform \ |
> print` |
=> |
Match arm |
Some(x) => x |
-> |
Return type |
fn f() -> int |
Declarations
Variables
let name: String = "Alice" // immutable
var count: int = 0 // mutable
let inferred = 42 // type inferred as int
Functions
fn add(a: int, b: int) -> int {
return a + b
}
fn greet(name: String, greeting: String = "Hello") -> String {
return greeting + ", " + name
}
fn apply<T>(value: T, f: Fn(T) -> T) -> T {
return f(value)
}
Structs
struct Point {
x: int,
y: int
}
struct Pair<T> {
first: T,
second: T
}
// Tuple struct
struct Meters(int)
Enums
enum Color { Red, Green, Blue }
enum Option<T> {
Some(T),
None
}
enum Shape {
Circle(int),
Rect(int, int),
Triangle(int, int, int)
}
Traits and impl
trait Display {
fn to_string(self) -> String
}
impl Display for Point {
fn to_string(self) -> String {
return "(" + int_to_string(self.x) + ", " + int_to_string(self.y) + ")"
}
}
impl Point {
fn new(x: int, y: int) -> Point {
return Point { x: x, y: y }
}
}
Imports
import "std/json"
import "std/http"
import { parse, stringify } from "std/json"
Types
Primitive types
| Type |
Description |
Example |
int |
64-bit integer |
42, -7, 0xFF |
float |
64-bit float |
3.14, -0.5 |
bool |
Boolean |
true, false |
char |
Character (ASCII) |
'A', 'z' |
String |
UTF-8 string |
"hello" |
Compound types
| Type |
Description |
Example |
Array |
Dynamic array |
[1, 2, 3] |
Map |
Hash map |
Map.new() |
Fn(A) -> B |
Function type |
Fn(int) -> int |
Sized types (systems programming)
| Type |
Size |
Range |
i8 |
1 byte |
-128 to 127 |
i16 |
2 bytes |
-32768 to 32767 |
i32 |
4 bytes |
-2^31 to 2^31-1 |
i64 |
8 bytes |
-2^63 to 2^63-1 |
u8 |
1 byte |
0 to 255 |
u16 |
2 bytes |
0 to 65535 |
u32 |
4 bytes |
0 to 2^32-1 |
u64 |
8 bytes |
0 to 2^64-1 |
f32 |
4 bytes |
IEEE 754 single |
usize |
8 bytes |
Platform pointer size |
Pointer types
| Type |
Description |
*T |
Raw pointer to T |
*int |
Raw pointer to int |
Control flow
If / else
if condition {
// ...
} else if other {
// ...
} else {
// ...
}
While
while condition {
// ...
}
For
for item in collection {
// ...
}
for i in 0..10 {
// ...
}
Match
match value {
0 => print("zero"),
1 | 2 => print("one or two"),
n if n > 100 => print("big"),
_ => print("other")
}
match option {
Some(x) => use(x),
None => default()
}
If-let / While-let
if let Some(x) = maybe_value {
print(int_to_string(x))
}
while let Some(item) = iterator.next() {
process(item)
}
Function attributes
#[naked] // No prologue/epilogue
#[interrupt] // Hardware interrupt handler
#[link_section(".text.boot")] // Place in specific section
#[export_name("_start")] // Control symbol name
#[derive(Clone, Debug, Display)] // Derive trait implementations
#[repr(C)] // C-compatible memory layout
String methods
| Method |
Returns |
Description |
.length() |
int |
String length |
.charAt(i) |
int |
ASCII value at index |
.substring(start, len) |
String |
Extract substring |
.indexOf(sub) |
int |
Find substring (-1 if not found) |
.contains(sub) |
bool |
Check if contains substring |
.split(delim) |
Array |
Split into array |
.trim() |
String |
Remove whitespace |
.toUpper() |
String |
Uppercase |
.toLower() |
String |
Lowercase |
.startsWith(prefix) |
bool |
Check prefix |
.endsWith(suffix) |
bool |
Check suffix |
.replace(old, new) |
String |
Replace occurrences |
Array methods
| Method |
Returns |
Description |
.length() |
int |
Array length |
.push(item) |
void |
Add to end |
.pop() |
any |
Remove from end |
.get(index) |
any |
Get by index |
.set(index, val) |
void |
Set by index |
.slice(start, end) |
Array |
Extract sub-array |
.contains(item) |
bool |
Check membership |
.indexOf(item) |
int |
Find index |
.join(sep) |
String |
Join into string |
.reverse() |
Array |
Reverse array |
.sort() |
Array |
Sort array |
.insert(index, val) |
void |
Insert at index |
.remove(index) |
any |
Remove at index |
Map methods
| Method |
Returns |
Description |
Map.new() |
Map |
Create empty map |
.get(key) |
any |
Get value by key |
.set(key, val) |
void |
Set key-value pair |
.contains(key) |
bool |
Check if key exists |
.remove(key) |
void |
Remove key |
.keys() |
Array |
Get all keys |
.values() |
Array |
Get all values |
.size() |
int |
Number of entries |
.clear() |
void |
Remove all entries |
Built-in functions
| Function |
Description |
print(value) |
Print to stdout |
println(value) |
Print with newline |
int_to_string(n) |
Convert int to string |
float_to_string(f) |
Convert float to string |
string_to_int(s) |
Parse string to int |
string_to_float(s) |
Parse string to float |
typeof(value) |
Get type name as string |
time_us() |
Current time in microseconds |
sleep(ms) |
Sleep for milliseconds |
exit(code) |
Exit program |
chr(code) |
Convert ASCII code to single-character string |
read_byte() |
Read one byte from stdin (returns int, -1 on EOF) |
raw_mode_enter() |
Set terminal to raw mode (no echo, no buffering) |
raw_mode_exit() |
Restore terminal to cooked mode |
term_cols() |
Terminal width in columns |
term_rows() |
Terminal height in rows |
Process control builtins (v0.12.0)
| Function |
Description |
fork() |
Fork process. Returns 0 in child, PID in parent, -1 on error |
execvp(program, args) |
Replace process with program. args is an Array of strings |
waitpid(pid, opts) |
Wait for child process. opts: 0=block, 1=WNOHANG. Returns exit status |
dup2(old_fd, new_fd) |
Duplicate file descriptor (for redirects) |
pipe_new() |
Create pipe. Returns [read_fd, write_fd] |
close_fd(fd) |
Close a raw file descriptor |
open_fd(path, mode) |
Open file as fd. mode: 0=read, 1=write(trunc), 2=append |
getcwd() |
Get current working directory as String |
chdir(path) |
Change working directory. Returns 0 on success |
stat(path) |
File info: returns [size, mode, mtime, is_dir, is_file] |
isatty(fd) |
Returns 1 if fd is a terminal, 0 otherwise |
getpid() |
Get current process ID |
kill_process(pid, signal) |
Send signal to process |
Build configuration (nyx.toml)
Every Nyx project can have a nyx.toml file at its root. This file describes the project metadata, entry point, and dependencies.
[package]
name = "myapp"
version = "0.1.0"
main = "src/main.nx"
description = "My first Nyx project"
no_gc = false
[dependencies]
somelib = "*"
otherlib = "https://github.com/org/otherlib"
| Field |
Section |
Description |
name |
[package] |
Project name (used for binary output) |
version |
[package] |
Semantic version (MAJOR.MINOR.PATCH) |
main |
[package] |
Entry point file (default: src/main.nx) |
description |
[package] |
One-line project description |
no_gc |
[package] |
Disable garbage collector (default: false) |
<name> = "<version>" |
[dependencies] |
Dependency with semver constraint ("*" for any) |
<name> = "<url>" |
[dependencies] |
Git dependency (cloned to packages/) |
Run nyx init to scaffold a new project with a nyx.toml and src/main.nx. Run nyx build to compile, which also generates a nyx.lock file pinning dependency versions.
← Back to Table of Contents