Syntax Reference
NAIDE uses indentation-based blocks, keyword-driven statements, and explicit type annotations. The first token on each line determines intent.
Variables
Variables are immutable by default (const). Use mut for mutable bindings (let).
str name = "hello" # immutable (const)
int count = 42
num price = 9.99
bool active = true
list items = [1, 2, 3]
map config = {host: "localhost"}
any data = null
mut int counter = 0 # mutable (let)
mut str label = "init"
Available Types
| Type | Description | JavaScript |
|---|---|---|
str | String | string |
int | Integer number | number |
num | Any number (accepts int) | number |
bigint | Arbitrary-precision integer | bigint |
bool | Boolean | boolean |
list | Array | Array |
map | Object / dictionary | Object |
any | Any type | (untyped) |
json | JSON-compatible value | (untyped) |
void | No return value | void |
Type Inference (auto)
Use auto to let the compiler infer the type from the assigned value:
auto name = "hello" # inferred as str
auto count = 42 # inferred as int
auto price = 9.99 # inferred as num
auto active = true # inferred as bool
auto items = [1, 2, 3] # inferred as list
auto config = {host: "localhost"} # inferred as map
mut auto counter = 0 # mutable with inferred type
Compiles to const (or let with mut) without explicit type annotations in the output.
Destructuring
Extract values from objects and arrays with destructuring syntax:
Object Destructuring
auto {name, age} = user
auto {name, age, ...rest} = user # with rest
str {first, last} = names # typed destructuring
Array Destructuring
auto [a, b] = items
auto [first, ...rest] = items # with rest
int [x, y, z] = coordinates # typed destructuring
Spread Operator
Spread arrays and objects with ...:
list merged = [...a, ...b] # merge arrays
map combined = {...defaults, ...overrides} # merge objects
map updated = {...user, name: "new"} # override a field
String Interpolation
Double-quoted strings with {expr} are automatically interpolated into template literals:
str greeting = "Hello {name}, you have {count} items"
Compiles to:
const greeting = `Hello ${name}, you have ${count} items`;
Functions
Functions use fn, with optional typed parameters and return type:
fn add(int a, int b) -> int:
ret a + b
fn greet(str name, str prefix = "Hello"):
log "{prefix}, {name}!"
Rest Parameters
fn sum(...int nums) -> int:
mut int total = 0
each n in nums:
total += n
ret total
Async Functions
fn.async fetchUser(str id) -> map:
any res = await fetch("/api/users/{id}")
ret await res.json()
Control Flow
If / Elif / Else
if count > 10:
log "many"
elif count > 5:
log "some"
else:
log "few"
Ternary Expression
str size = if count > 10 then "big" else "small"
Loops
each — Iterate Arrays
each item in items:
log item
each — Iterate Object Keys/Values
each key, val in config:
log "{key}: {val}"
for — Numeric Range
for i in 0..10:
log i
while
while active:
log "running"
active = false
Syntax Sugar
unless
Inverted if — runs the block when the condition is false:
unless active:
log "not active"
until
Inverted while — loops until the condition becomes true:
until done:
process()
done = check()
repeat
Loop a fixed number of times:
repeat 5:
log "hello"
is / isnt
Readable aliases for === and !==:
if status is "ok":
log "success"
if status isnt "error":
log "not an error"
swap
Swap two variables in one statement:
swap a, b
One-Line Functions
fn double(int x) -> int: ret x * 2
fn greet(str name): log "Hi {name}"
Alias for log:
print "hello world"
enum
Define enumerations:
enum Color: RED, GREEN, BLUE
log Color.RED # 0
Pattern Matching
match status:
"ok": log "success"
"error": log "failed"
_: log "unknown"
Compiles to a switch statement. Use _ for the default case.
Error Handling
try:
data = await fetchData(url)
fail e:
log.error e.message
ensure:
log "request completed"
fail is NAIDE's catch. ensure is NAIDE's finally — the block always runs whether the try succeeds or fails. Both fail and ensure are optional:
try:
conn = await openConnection()
ret await conn.query("SELECT 1")
ensure:
conn.close()
Type Checking
if typeof data == "string":
log "is string"
if err instanceof TypeError:
log "type error"
typeof returns the type as a string. instanceof checks if a value is an instance of a class or constructor.
Classes (model / schema)
Use model or schema to define classes with typed properties:
model User:
str name
str email
int age = 0
fn greet() -> str:
ret "Hi, I'm {self.name}"
self refers to the current instance (compiles to this).
Class Inheritance (extends)
Use extends with schema or model for class inheritance:
schema Animal:
str name
str sound
fn speak() -> str:
ret "{self.name} says {self.sound}"
schema Dog extends Animal:
init(str name):
self.name = name
self.sound = "woof"
fn fetch(str item) -> str:
ret "{self.name} fetches {item}"
The init keyword defines a constructor. Child classes inherit all properties and methods from the parent.
Admin Example
model Admin extends User:
str role = "admin"
fn permissions() -> list:
ret ["read", "write", "delete"]
Pipe Operator (|>)
Chain operations for readable data transformations:
list result = data
|> filter((x) => x.active)
|> map((x) => x.name)
|> sort()
list result = items
|> filter((x) => x > 0)
|> map((x) => x * 2)
|> unique()
|> sort()
Optional Chaining (?.)
Safely access nested properties without null checks:
str name = user?.profile?.name
str city = user?.address?.city
any result = obj?.method?.()
Returns undefined if any part of the chain is null or undefined.
Null Coalescing (??)
Provide a default value when the left-hand side is null or undefined:
str name = user?.name ?? "Anonymous"
int port = config?.port ?? 3000
str display = label ?? title ?? "Untitled"
Unlike ||, the ?? operator only falls through on null/undefined, not on 0, "", or false.
JavaScript Interoperability
Optional function calls and computed property access, native dynamic imports, strict equality, and JavaScript logical and compound assignment operators are available:
any first = items?.[0]
any result = callback?.("value")
any plugin = await import("./plugins/report.naide")
mut bool enabled = true
enabled &&= hasPermission
enabled = enabled && featureAvailable
bool same = value === other
Dynamic import remains a native ESM operation. Relative .naide import paths are rewritten to the generated .mjs path when building.
Additional JavaScript-compatible expressions and control flow
bigint exact = 9_007_199_254_740_993n
int mask = (5 << 1) | 1
str message = `value=${mask}`
bool matched = /value=\d+/i.test(message)
int selected = mask > 0 ? mask : 0
for item of [1, 2, 3]:
log item
do:
mask++
while mask < 20
fn.gen values():
yield 1
yield* [2, 3]
Also supported are radix/exponent/numeric-separator literals, regular-expression literals, exponentiation and bitwise/shift operators, prefix/postfix updates, and fn.async.gen. Expressions inside backtick ${...} interpolations use JavaScript expression syntax and are passed through unchanged. match is the NAIDE switch-like form and inserts case breaks automatically. These features compile for Node.js, Bun, TypeScript, and browser JavaScript output; they do not make NAIDE a parser for arbitrary JavaScript files. Direct JavaScript class/import/export syntax, decorators, and labeled loop control are not currently supported. Non-JavaScript output targets report an error for these JS-specific constructs.
Imports & Exports
Imports
use express
use {readFile, writeFile} from "fs/promises"
use axios from "axios"
use compiles to import. When importing between NAIDE files, extensions are automatically rewritten to .mjs:
use {handleUser} from "./routes.naide"
Exports
pub fn helper() -> str:
ret "exported"
pub str VERSION = "1.0.0"
pub marks functions and variables as exported (export).
Environment Variables
env:
PORT int default(3000)
JWT_SECRET str required
DB_URL str default("data/")
Variables become constants read from process.env. Missing required variables cause the process to exit with an error.
Built-in Functions (40+)
NAIDE includes 40+ built-in functions auto-imported from the runtime when used. No import required.
I/O & System
| Function | Description |
|---|---|
ask(prompt) | Read user input from stdin |
sleep(ms) | Pause execution for ms milliseconds |
exit(code?) | Exit the process with optional exit code |
read(path) | Read file contents as string |
write(path, data) | Write string data to a file |
fetch_json(url) | Fetch a URL and parse JSON response |
Collections
| Function | Description |
|---|---|
sort(list) | Sort a list |
reverse(list) | Reverse a list |
unique(list) | Remove duplicates |
len(val) | Length of string, list, or map |
range(start, end) | Generate a numeric range |
flat(list) | Flatten nested lists |
zip(a, b) | Zip two lists into pairs |
chunk(list, n) | Split list into chunks of size n |
random(min?, max?) | Random number (or random from list) |
Higher-Order Functions
| Function | Description |
|---|---|
map(list, fn) | Transform each element |
filter(list, fn) | Keep elements matching predicate |
reduce(list, fn, init) | Reduce to single value |
find(list, fn) | Find first matching element |
every(list, fn) | Check if all elements match |
some(list, fn) | Check if any element matches |
foreach(list, fn) | Execute function for each element |
String Functions
| Function | Description |
|---|---|
upper(str) | Convert to uppercase |
lower(str) | Convert to lowercase |
trim(str) | Remove leading/trailing whitespace |
split(str, sep) | Split string by separator |
join(list, sep) | Join list elements into string |
contains(str, sub) | Check if string contains substring |
replace(str, old, new) | Replace occurrences in string |
Object / Map Functions
| Function | Description |
|---|---|
keys(map) | Get list of keys |
values(map) | Get list of values |
entries(map) | Get list of [key, value] pairs |
Math Functions
| Function | Description |
|---|---|
abs(n) | Absolute value |
round(n) | Round to nearest integer |
ceil(n) | Round up |
floor(n) | Round down |
sqrt(n) | Square root |
pow(base, exp) | Exponentiation |
sum(list) | Sum of all numbers in list |
JSON & Time
| Function | Description |
|---|---|
json_parse(str) | Parse JSON string to object |
json_str(val) | Stringify value to JSON |
now() | Current ISO timestamp |
time() | Current Unix timestamp (ms) |
Security
str id = uuid() # UUID generation
str hashed = hash("password") # scrypt hash
bool ok = verify("password", hashed) # timing-safe verify
str token = sign({id: 1}) # JWT (uses auth secret)
str token = sign({id: 1}, "my-secret") # JWT (explicit secret)
All built-in functions are auto-imported from the NAIDE runtime when used.
HTTP Client
fn.async getUsers() -> any:
any users = await api.get("https://api.example.com/users")
ret users
fn.async createUser(map data) -> any:
any result = await api.post("https://api.example.com/users", data)
ret result
Available methods: api.get(url), api.post(url, body), api.put(url, body), api.del(url), api.raw(url, opts).
Plugin System
registerPlugin("logger", (opts) =>
ret {log: (msg) => log "[{opts.prefix}] {msg}"}
)
any logger = usePlugin("logger", {prefix: "APP"})
logger.log("started")
list names = listPlugins()
registerPlugin(name, setup) registers a plugin factory. usePlugin(name, opts?) initializes on first call and returns cached exports. listPlugins() returns registered plugin names.