Appendix B: Quick Reference

**Single-page cheat sheet for NanoLang syntax and built-in functions.**

NanoLang Mascot

B.1 Operator Notation and Precedence

NanoLang supports **both prefix and infix** notation for binary operators:


# Prefix notation (Lisp-style)
(+ a b)      # Addition
(- a b)      # Subtraction
(* a b)      # Multiplication
(/ a b)      # Division
(% a b)      # Modulo

# Infix notation
a + b        # Addition
a - b        # Subtraction
a * b        # Multiplication
a / b        # Division
a % b        # Modulo

**Infix precedence:** All infix operators have **equal precedence**, evaluated **left-to-right** (no PEMDAS). Use parentheses to control grouping:


# Prefix: nesting makes order explicit
(+ (* a b) (/ c d))    # (a*b) + (c/d)
(* (+ a 1) (- b 2))    # (a+1) * (b-2)

# Infix: use parentheses for grouping
a * b + c / d           # Evaluates as ((a * b) + c) / d
a * (b + c) / d         # Parentheses control order

**Unary operators:** not flag, -x (no parentheses needed)

Comparison Operators

OperatorDescriptionExample
==Equal(== x 5)
!=Not equal(!= x 5)
<Less than(< x 5)
>Greater than(> x 5)
<=Less than or equal(<= x 5)
>=Greater than or equal(>= x 5)

Logical Operators

OperatorDescriptionExample
andLogical AND (short-circuit)(and cond1 cond2)
orLogical OR (short-circuit)(or cond1 cond2)
notLogical NOT(not condition)

B.2 Built-in Functions

Arithmetic

FunctionSignatureDescription
+`(+ a b) -> int\float`Addition
-`(- a b) -> int\float`Subtraction
*`(* a b) -> int\float`Multiplication
/`(/ a b) -> int\float`Division
%(% a b) -> intModulo (integers only)
abs`abs(int\float) -> int\float`Absolute value
min`min(a, b) -> int\float`Minimum of two values
max`max(a, b) -> int\float`Maximum of two values
sqrtsqrt(float) -> floatSquare root
powpow(base, exp) -> floatPower
floorfloor(float) -> floatRound down
ceilceil(float) -> floatRound up
roundround(float) -> floatRound to nearest
sinsin(float) -> floatSine (radians)
coscos(float) -> floatCosine (radians)
tantan(float) -> floatTangent (radians)

String Operations

FunctionSignatureDescription
+(+ s1 s2) -> stringConcatenation (preferred)
str_lengthstr_length(string) -> intString length
str_substringstr_substring(s, start, len) -> stringExtract substring
str_containsstr_contains(s, substr) -> boolCheck for substring
==(== s1 s2) -> boolString equality (preferred)
str_equalsstr_equals(s1, s2) -> boolString equality
char_atchar_at(s, index) -> intGet ASCII value at index
string_from_charstring_from_char(int) -> stringCreate string from ASCII
is_digitis_digit(int) -> boolCheck if character is digit
is_alphais_alpha(int) -> boolCheck if character is letter
is_alnumis_alnum(int) -> boolCheck if alphanumeric
is_whitespaceis_whitespace(int) -> boolCheck if whitespace
is_upperis_upper(int) -> boolCheck if uppercase
is_loweris_lower(int) -> boolCheck if lowercase
char_to_lowerchar_to_lower(int) -> intConvert to lowercase
char_to_upperchar_to_upper(int) -> intConvert to uppercase

Binary String Operations (bstring)

Binary strings support embedded nulls and UTF-8 aware operations.

FunctionSignatureDescription
bstr_newbstr_new(string) -> bstringCreate from C string
bstr_new_binarybstr_new_binary(string, int) -> bstringCreate with explicit length
bstr_lengthbstr_length(bstring) -> intGet byte length
bstr_concatbstr_concat(bstring, bstring) -> bstringConcatenate
bstr_substringbstr_substring(bstring, int, int) -> bstringExtract substring
bstr_equalsbstr_equals(bstring, bstring) -> boolEquality check
bstr_byte_atbstr_byte_at(bstring, int) -> intGet byte at index
bstr_to_cstrbstr_to_cstr(bstring) -> stringConvert to C string
bstr_validate_utf8bstr_validate_utf8(bstring) -> boolCheck UTF-8 validity
bstr_utf8_lengthbstr_utf8_length(bstring) -> intGet UTF-8 char count
bstr_utf8_char_atbstr_utf8_char_at(bstring, int) -> intGet UTF-8 code point
bstr_freebstr_free(bstring) -> voidFree memory

HashMap Operations

FunctionSignatureDescription
map_newmap_new() -> HashMap<K,V>Create empty hash map
map_putmap_put(map, key, value) -> voidInsert/update key-value pair
map_getmap_get(map, key) -> VGet value by key
map_hasmap_has(map, key) -> boolCheck if key exists
map_sizemap_size(map) -> intGet number of entries
map_freemap_free(map) -> voidFree map memory

Checked Math (Safe Arithmetic)

Import from modules/stdlib/checked_math.nano for overflow-safe operations.

FunctionSignatureDescription
checked_addchecked_add(int, int) -> Result<int, string>Safe addition
checked_subchecked_sub(int, int) -> Result<int, string>Safe subtraction
checked_mulchecked_mul(int, int) -> Result<int, string>Safe multiplication
checked_divchecked_div(int, int) -> Result<int, string>Safe division
checked_modchecked_mod(int, int) -> Result<int, string>Safe modulo

Array Operations

FunctionSignatureDescription
array_newarray_new(size, default) -> array<T>Create new array
array_getarray_get(arr, index) -> TGet element (bounds-checked)
atat(arr, index) -> TGet element (alias)
array_setarray_set(arr, i, val) -> array<T>Set element (returns new array)
array_lengtharray_length(arr) -> intGet array length
array_pusharray_push(arr, elem) -> array<T>Append element
array_poparray_pop(arr) -> TRemove and return last element
array_remove_atarray_remove_at(arr, i) -> array<T>Remove element at index
filterfilter(arr, fn) -> array<T>Keep elements matching predicate
mapmap(arr, fn) -> array<T>Transform each element
reducereduce(arr, init, fn) -> AFold array into single value

Generic List Operations

Generic lists are monomorphized at compile time. Replace T with your type (e.g., list_int_*).

FunctionSignatureDescription
list_T_newlist_T_new() -> List<T>Create empty list
list_T_pushlist_T_push(list, elem) -> voidAppend element
list_T_getlist_T_get(list, index) -> TGet element (bounds-checked)
list_T_lengthlist_T_length(list) -> intGet number of elements

**Example:**


let nums: List<int> = (list_int_new)
(list_int_push nums 42)
let val: int = (list_int_get nums 0)

OS Functions

FunctionSignatureDescription
getcwdgetcwd() -> stringGet current directory
getenvgetenv(string) -> stringGet environment variable
rangerange(start, end) -> iteratorCreate range for loops

Type Conversions

FunctionSignatureDescription
int_to_stringint_to_string(int) -> stringConvert int to string
string_to_intstring_to_int(string) -> intParse string to int
digit_valuedigit_value(int) -> intConvert '5' char to 5 int

I/O Functions

FunctionSignatureDescription
printprint(any) -> voidPrint without newline
printlnprintln(any) -> voidPrint with newline
assertassert(bool) -> voidRuntime assertion
read_lineread_line() -> stringRead line from stdin

B.3 Standard Library Overview

Core Utilities

Always available without imports:

  • **I/O**: print, println, assert
  • **Math**: +, -, *, /, %, abs, min, max, sqrt, pow
  • **Trig**: sin, cos, tan, floor, ceil, round
  • **Strings**: str_length, str_substring, char_at, + (concat)
  • **Arrays**: array_new, array_get, array_set, array_push
  • **OS**: getcwd, getenv, range

Collections


# Dynamic arrays (built-in)
let arr: array<int> = [1, 2, 3]
set arr (array_push arr 4)

# Generic lists
let nums: List<int> = (List_int_new)
(List_int_push nums 42)
let val: int = (List_int_get nums 0)

Filesystem

Import from modules/std/fs.nano:

  • read(path) -> string - Read file contents
  • write(path, content) -> void - Write to file
  • exists(path) -> bool - Check if file exists
  • walkdir(path) -> array<string> - List directory contents

System

Import from modules/std/env.nano or modules/std/process.nano:

  • getcwd() -> string - Get current directory
  • getenv(name) -> string - Get environment variable
  • run(command) -> int - Execute shell command

B.4 Module Index

Text Processing

ModulePurpose
modules/std/log/log.nanoStructured logging with levels
modules/std/collections/StringBuilder.nanoEfficient string building
stdlib/regex.nanoRegular expressions

Data Formats

ModulePurpose
modules/std/json/json.nanoJSON parsing and generation
modules/sqlite/sqlite.nanoSQLite database access

Web & Networking

ModulePurpose
modules/curl/curl.nanoHTTP client requests
modules/http_server/http_server.nanoHTTP server
modules/uv/uv.nanoAsync I/O (libuv)

Graphics

ModulePurpose
modules/sdl/sdl.nano2D graphics, windows, events
modules/sdl_mixer/sdl_mixer.nanoAudio playback
modules/sdl_ttf/sdl_ttf.nanoTrueType font rendering
modules/sdl_image/sdl_image.nanoImage loading
modules/glfw/glfw.nanoOpenGL windows and input
modules/opengl/opengl.nano3D graphics
modules/ncurses/ncurses.nanoTerminal UI

Testing

ModulePurpose
stdlib/coverage.nanoCode coverage tracking
modules/proptest/proptest.nanoProperty-based testing

B.5 Control Flow Cheat Sheet

Variables


let x: int = 42                    # Immutable
let mut counter: int = 0           # Mutable
set counter (+ counter 1)          # Assignment

Conditionals


# Expression (returns value) - use cond
let sign: int = (cond
    ((< x 0) -1)
    ((> x 0) 1)
    (else 0)
)

# Statement (side effects) - use if/else
if (< x 0) {
    (println "negative")
} else {
    (println "non-negative")
}

Loops


# While loop
while (< i 10) {
    set i (+ i 1)
}

# For loop
for (let i: int = 0) (< i 10) (set i (+ i 1)) {
    (println (int_to_string i))
}

Functions


fn add(a: int, b: int) -> int {
    return (+ a b)
}

shadow add {
    assert (== (add 2 3) 5)
}

Pattern Matching


match result {
    Ok(v) => { (println v.value) }
    Err(e) => { (println e.error) }
}

Unsafe Blocks and FFI

Use unsafe blocks for calling extern (C) functions:


# Declare external C function
extern fn getpid() -> int

fn get_process_id() -> int {
    let pid: int = 0
    unsafe {
        set pid (getpid)
    }
    return pid
}

**Key points:**

  • extern fn declares C functions
  • All extern calls must be inside unsafe { } blocks
  • Extern functions don't require shadow tests

B.6 Types Quick Reference

Primitive Types

TypeSizeDescription
int64-bitSigned integer
float64-bitIEEE 754 double
bool1-bittrue or false
stringptrUTF-8 text (null-terminated)
bstringptrBinary string (length-prefixed, UTF-8 aware)
void0No value (return type only)

Composite Types


# Struct
struct Point { x: int, y: int }
let p: Point = Point { x: 10, y: 20 }

# Enum
enum Status { Idle = 0, Running = 1, Done = 2 }
let s: Status = Status.Running

# Union (tagged union)
union Result { Ok { value: int }, Error { msg: string } }

# Tuple
let coord: (int, int) = (10, 20)
let x: int = coord.0

# Array
let arr: array<int> = [1, 2, 3]

# HashMap
let counts: HashMap<string, int> = (map_new)
(map_put counts "key" 42)

# Function type
let f: fn(int) -> int = double

---

**Previous:** Appendix A: Examples Gallery

**Next:** Appendix C: Troubleshooting Guide