Kaya Syntax Reference
The complete Kaya syntax specification
Program Structure
A Kaya program consists of a sequence of statements. Statements are executed sequentially unless control flow statements alter the execution order.
// A simple Kaya program
let name = "Alice"
"Hello, {{name}}"Later examples illustrate individual constructs and may need surrounding variables, functions or resources. Model calls additionally need admitted deployment aliases and grants; see native model setup.
Entry Point and Inputs
A program executes top to bottom. There is no main function:
functions run only when called, so a program whose top level only
declares functions does nothing.
Launch inputs arrive as typed free roots bound before the first statement:
// task is provided at launch, e.g. --set task='{"instruction": "..."}'
let instruction = task.instruction
"{{instruction}}"kaya run program.kaya --set k=vparsesvas JSON when valid, else binds it as a string. Pass a JSON string literal to force a string that would otherwise parse:--set k='"123"'binds"123".kaya run program.kaya --input-file k=path.jsonreads a large value from a file (same JSON-when-valid rule). A missing or unreadable file fails the launch before the first statement.- A key passed through both
--setand--input-fileis a launch error; pass it once.
File Extensions
.kaya- Kaya source files
Encoding
- UTF-8 encoding
- Unix (LF) or Windows (CRLF) line endings. A lone carriage return is not a line break and is rejected.
- Source is read as Unicode throughout: identifiers, strings, and comments may all contain non-ASCII text.
Source Positions
Every statement the parser emits carries a sourceLocation, and it records
the same span twice so that both kinds of host can use it directly:
| Field | Units |
|---|---|
startLine, startColumn, endLine, endColumn | 1-based UTF-16 code units, end inclusive — the units a JavaScript editor or language server works in |
startByteOffset, endByteOffset | 0-based UTF-8 byte offsets, end exclusive — source[startByteOffset..endByteOffset] is the node's exact text |
The two always describe the same span. The distinction only becomes visible
outside ASCII: in let a = "café" the statement is 14 UTF-16 code units but
15 UTF-8 bytes, and a single emoji is 2 code units but 4 bytes. A non-JavaScript
host should read the byte offsets and never re-derive code-unit
indices; an editor integration should read the line/column pair.
The byte offsets were added in node-IR v0.3.2 and are optional, so a consumer of an IR document produced by an older parser still reads it.
Differences from JavaScript
Kaya's expression syntax looks like TypeScript but diverges in a few load-bearing ways:
==/!=only — loose (coercing) equality for scalars, but deep structural value equality for objects and arrays.===/!==do not exist and are parse errors.??mixes freely with&&/||— no parentheses required;??binds loosest.- Nested ternaries need no parentheses — right-associative
(
a ? b : c ? d : eisa ? b : (c ? d : e)). - Out-of-bounds / negative array indexing throws; missing object
properties return
undefined. "…"/'…'strings are single-line — use backticks for multiline.- All calls use named arguments —
f(name: "x"), never positionalf("x"). - No
undefinedliteral — writingundefinedis an ordinary identifier (missing-variable error at runtime). - Bare expression statements are invalid —
5 + 3alone doesn't parse. Standalone statements are echo strings, function calls, and assignments. - No
mainfunction — the top level is the entry point and runs top to bottom; launch inputs arrive as typed free roots (see Entry Point and Inputs), never asmainarguments. - Division by zero throws rather than producing
Infinity/NaN. - Calls in expressions evaluate once, before the statement —
f(x: 1) + 1,text.split(value: ",")[0], andif check(x: 1) {all work. A call in a short-circuit position (the right side of&&/||/??, or a ternary branch) runs only when that side is reached:let player = face ?? asset(path: "player.html")reads the asset only whenfaceis null. Calls are rejected (with an explanatory parse error) where running them once would change semantics:while/do-whileandelse ifconditions,range()bounds, and template interpolations ({{f(x: 1)}}— compute into a variable first, then interpolate).
Comments
Single-Line Comments
// This is a single-line comment
let x = 42 // Comment after statementSyntax:
- Starts with
// - Continues to end of line
Block Comments
/* This is a block comment */
/*
Multi-line block comment
spanning several lines
*/
let x = 5 /* inline comment */ + 3Syntax:
- Starts with
/* - Ends with
*/ - Can span multiple lines
- Can appear inline within a statement
Note: Block comments do not nest — the first */ closes the comment, and
anything after it is parsed as code. A /* that is never closed is a lexer
error (LEXER_INVALID_TOKEN) naming the unterminated comment, not a cascade of
unexpected-token errors further down the file.
Statements
Variable Declaration (let)
Declares a mutable variable.
Syntax:
let <identifier> = <expression>
let <identifier>: <type> = <expression>Examples:
let x = 42
let name = "Alice"
let items = ["a", "b", "c"]
let user = {name: "Bob", age: 30}
// With type annotation
let count: number = 0
let names: string[] = ["Alice", "Bob"]
let config: json = {debug: true}Rules:
- Variable name must be a valid identifier
- Variables can be reassigned
- Optional type annotation after identifier
- Expression evaluated and assigned to variable
String initializers for number declarations and omitted numeric function
defaults use JavaScript's Number.parseFloat prefix coercion: "42px" becomes
42. Leading ECMAScript whitespace, including U+FEFF (BOM), is skipped; U+0085
(NEXT LINE) is not. This differs from full-string numeric expression coercion.
The resulting value must still pass the declared type and finite-number checks.
Constant Declaration (const)
Declares an immutable variable.
Syntax:
const <identifier> = <expression>
const <identifier>: <type> = <expression>Examples:
const PI = 3.14159
const MAX_RETRIES = 5
const CONFIG: json = {version: "1.0"}Rules:
- Same as
letbut variable cannot be reassigned - Must be initialized at declaration
- Attempting to reassign causes an error
Tuple Destructuring (error handling)
Captures a function call's result and error in one statement instead of letting the error throw.
Syntax:
let <value>, <error> = <function-call>Example:
let data, err = fetchData(url: "https://example.com")
if err {
"Fetch failed: {{err.message}}"
} else {
"Got: {{data}}"
}Rules:
- The right-hand side must be a function call — literals and other expressions are a parse error
- Not supported with
const(parse error) - Not supported with
map(parse error) - Type annotations on the bindings are not supported (parse error)
- On success the result variable holds the return value and the error variable
is
null; on failure the error variable holds the error object and execution continues instead of throwing - Native caught Program failures retain their exact
messageplus owner metadata indetails(code,errorName, available source and guidance, and approved provider fields). The top-levelError.coderemains an optional string. See structured errors. - Retries precede catch. Internal failures and cancellation remain uncaught.
- Native value/error tuples require a user-defined function call. Direct builtin tuples return a structured admission refusal before execution. Wrap the builtin in a function to capture its result or Program failure.
Variable Assignment and Scoping
Kaya implements precise lexical block-scoping on its execution stack. There is a clear distinction between declaring/shadowing a variable and reassigning an existing variable:
1. Declaration & Shadowing (let)
Using let always declares a new variable in the current local block scope (such as inside an if block, for loop, while loop, or function). If a variable with the same name exists in an outer scope, the inner let shadows it. Changes to the shadowed variable are isolated to that block and do not affect the outer variable.
2. Reassignment (=)
To update or reassign an existing variable in the current or any parent/outer scope, use a bare assignment statement without the let keyword.
Syntax:
<identifier> = <expression>
<member-expression> = <expression>Examples:
let content = "outer value"
if true {
// Shadowing: creates a new 'content' variable inside the block
let content = "inner value"
}
// content is still "outer value"
if true {
// Reassignment: modifies the 'content' variable in the outer scope
content = "new outer value"
}
// content is now "new outer value"Rules:
- Reassignment looks up the stack to find the nearest declared variable. If the variable does not exist anywhere in the stack, a runtime error is thrown.
- Reassignment to a variable declared with
constis prohibited and results in a runtime error. - String literals containing
{{template placeholders are dynamically rendered upon assignment.
Echo Statement
Outputs a value to the chat/console.
Syntax:
"<string>"
[<speaker>] "<string>"Examples:
"Hello, world!"
"The value is {{x}}"
[alice] "Hello from Alice"
[system] "System message"Rules:
- String can contain template interpolation
{{...}} - Optional speaker in square brackets before string
- Speaker must be a valid identifier; reserved role names (
[system],[user],[assistant]) select the message role, whereas any other[Name]resolvesNameto anActorin scope (using itsnameoridand stamping itsSessionIdentityontofrom), or instantiates{ id: "Name", kind: "agent", handle: "Name", name: "Name" }on the fly and bindsNamein the current scope when not yet declared
Type Definition
Defines a custom type.
Syntax:
type <TypeName> = <type-expression>Examples:
// Primitive types
type Email = string
type Temp = number
type IsActive = boolean
// String with validation
type Username = string + { min: 3, max: 20 }
type Email = string + { email: true }
// Object types
type User = {
name: string,
email: string + { email: true },
age: number + { int: true, min: 0 }
}
// Array types
type Names = string[]
type Numbers = number[]
// Union types
type StringOrNumber = string | number
// Literal types (enums)
type Status = "active" | "pending" | "inactive"
// Optional/Nullable types — T? accepts the value, undefined, AND null.
// (`null` is not a valid type or union member; `number | null` is a parse error.)
type MaybeString = string?
// Type references
type Address = { street: string, city: string }
type Person = { name: string, address: Address }
// Semantic constraints
type PositiveMessage = string + { is: "a message expressing positive sentiment" }
type ValidConfig = { host: string } + { is: "a valid server configuration" }See also: Type System Reference
Function Call
Calls a function or standard library function.
Syntax:
<identifier>(<arguments>)
<identifier> { <closure-block> }
<identifier>(<arguments>) { <closure-block> }
<object>.<method>(<arguments>)
let <identifier> = <function-call>Examples:
// Empty arguments
myFunction()
myFunction({})
// Named arguments
greet(name: "Alice", age: 30)
// JSON-style arguments
process({"input": "data", "mode": "fast"})
// Method call syntax (stdlib functions)
let best = items.pick(criteria: "highest rated")
// Closure block only
withRetry {
fetchData()
}
// Arguments and closure
withRetry(maxAttempts: 3) {
fetchData()
}
// Assigned to variable
let result = compute(x: 10, y: 20)
// Standard library call
let text = generate(message: "Hello")See also: Functions, Method Calls, Annotations
Import Statement
Imports functions and types from another file or library. See Imports and Exports for the full syntax (multiple imports, aliases, wildcards, type imports) and the supported path schemes.
import greet from "./helpers.kaya"
import tellStory from "../storytelling/"Jump Statement (removed)
jump was removed from Kaya (2026-08) and is no longer reserved (2026-09):
it is an ordinary identifier, so let jump = 1 and jump(x: 1) are normal
code. Only the removed statement's own shape — jump target at the head of a
statement — still raises the migration error, whose suggestion is to call the
function and use its return value (let out = mainMenu()).
Return Statement
Returns from a function with an optional value.
Syntax:
return
return <expression>Examples:
return
return 42
return x + y
return user.name
return temp >= 30
return isPremium ? 0.2 : 0.1
return items[0]Rules:
- Meaningful only inside functions (including inside loops within a function)
- Expression can be any valid expression
- Exits the function immediately
- Empty
returndoes NOT returnnull— the caller's output variable is simply never set, and using it later fails. Return an explicit value if the caller needs one. - A
returnat the top level of a program ends the program, with the returned value as the program's output; later statements never run - A string-literal return renders its template in the function's scope
(
return "Hi {{name}}"returnsHi World), same as aletinitializer - The return value is validated against the function's declared return type, failing loud on mismatch
Break Statement
Exits the current loop immediately.
Syntax:
breakExamples:
while true {
if done {
break
}
"Processing..."
}
for item in items {
if item == "stop" {
break
}
"Item: {{item}}"
}Rules:
- Meaningful only inside loops; exits the innermost enclosing loop
- Outside a loop it is a compile error (
break-outside-loop)
Continue Statement
Skips to the next iteration of the current loop.
Syntax:
continueExamples:
for i in range(10) {
if i % 2 == 0 {
continue // Skip even numbers
}
"Odd: {{i}}"
}
while processing {
if shouldSkip {
continue
}
"Process item"
}Rules:
- Meaningful only inside loops
- Skips remaining statements in current iteration
- Continues with next iteration
- Outside a loop it is a compile error (
continue-outside-loop)
Throw Statement
Raises a runtime error and aborts execution (unless captured with tuple destructuring at a call boundary).
Syntax:
throw
throw()
throw(message: "<string>")
throw "<string>"Examples:
if err {
throw(message: "Fetch failed: {{err.message}}")
}
throw "validation failed for {{item}}" // sugar for throw(message: ...)Rules:
messageis the only supported parameter and must be a string literal (it may contain{{...}}interpolation)throw "text"is sugar forthrow(message: "text")— both forms unescape the message with the one string-escape rule above
Pause Statement
Suspends execution of the program at this point. The session resumes when a
NEW user message or external event arrives — arrivals that happened before
the pause do not count, and internal wakeups never resume it. This makes
pause a reliable "wait for the outside world" point: pair it with
consumeEvent() for an event-driven polling loop.
Syntax:
pauseExample:
"Waiting for review before continuing."
pause
"Resumed."Assert Statements
Assertion statements for testing. A failed assertion aborts the program with the assertion's message.
Syntax:
assert <expression> [, "<comment>"]
assertTrue <expression> [, "<comment>"]
assertFalse <expression> [, "<comment>"]
assertEqual <actual>, <expected> [, "<comment>"]Examples:
assert count > 0, "count must be positive"
assertTrue isValid
assertFalse hasError, "no errors expected"
assertEqual result, "expected output", "result should match"Rules:
- These are statements (no parentheses), with operands separated by commas
- The trailing comment must be a string literal
assertpasses when the expression is truthy;assertTruerequires exactlytrueandassertFalseexactlyfalse(not just truthy/falsy);assertEqualuses deep (JSON) equality
Expressions
Expressions evaluate to values and can be used in assignments, conditions, and arguments.
Literals
Numbers:
let a = 42 // integer
let b = 3.14 // floating point
let c = -10 // negative
let d = +5 // positive (explicit)
let e = 1_000_000 // `_` separators, allowed between digits
let f = 6.02e+23 // exponentA separator must sit BETWEEN digits: 1_000 and 1_0.5_5 are numbers, 1_ is
the number 1 followed by the identifier _. Kaya has no octal literals, so a
leading zero (007) is a LEXER_INVALID_NUMBER error — write 7, or quote the
value ("007") when the zeros are part of a code.
Strings:
"hello" // double quotes (strictly single-line)
'hello' // single quotes (strictly single-line)
`hello` // backticks (supports multiline)
"Hello {{name}}" // with interpolationEscapes — one rule for every quote style, and for throw:
| Escape | Result |
|---|---|
\n \t \r | newline, tab, carriage return |
\\ | a literal backslash |
\" \' \` | the quote character |
\uXXXX | the Unicode code point (a surrogate PAIR, \ud83d\ude00, writes a non-BMP character) |
let quoted = "he said \"hi\""
let path = "C:\\Users\\me" // a literal backslash is written \\
let cafe = "caf\u00e9" // caféAny other escape is a LEXER_INVALID_ESCAPE error rather than a silent
passthrough: "caf\u00e9" is café, and "C:\path" is refused because \p
is not an escape Kaya knows. Non-ASCII characters may of course also be written
directly.
Booleans:
let yes = true
let no = falseNull:
let empty = nullNo undefined literal: writing undefined parses as an ordinary
identifier and fails at runtime as a missing variable. undefined values
arise from missing object properties, ?., and optional parameters; test for
them with ??.
Arrays:
let empty = []
let nums = [1, 2, 3]
let strs = ["a", "b", "c"]
let nested = [[1, 2], [3, 4]]Objects:
let obj = {}
let user1 = {name: "Alice"}
let user2 = {"name": "Alice"} // quoted keys
let user3 = {name: "Alice", age: 30}
let wrapper = {user: {id: 1}} // nested
let event = {type: "click", from: "left"} // keywords are fine as keysKeywords are CONTEXTUAL (2026-09): a reserved word is a keyword only where the
construct it heads is still possible. Everywhere a plain name is expected —
including at the head of a statement — type, from, in, map, … are
ordinary names, and a name bound to one is usable, not just bindable:
let type = "cookbook" // binding name
for from in senders { } // loop binding
function label(map: string) { } // parameter name
let event = {type: "click"} // object key
send(type: "click") // argument name
event.type // property access
type = "recipe" // reassignment
type.trim() // method call on a keyword-named value
rows.map() // keyword-named method
function type() { } // declaration, then type() calls it
let out = map rows type(x: 1) // map over a keyword-named functionThe exceptions are the words that begin or continue an EXPRESSION and stay
reserved everywhere: true, false, null, the word operators is and
as, and forever (see below). Object SHORTHAND ({type}) is still
rejected, because the key and the value would disagree about which one the
word is.
Two statement heads deliberately keep the keyword reading, because the name reading would swallow a better diagnostic:
let = 5andconst = 5are malformed bindings ("Expected variable name"), never assignments to variables namedlet/const.function (…)is a declaration missing its name, never a call to a function namedfunction.
Identifiers
Variable and function names.
Rules:
- Start with an underscore or a Unicode
XID_Startcharacter (which includes every ASCII letter) - Continue with underscores and Unicode
XID_Continuecharacters (which include ASCII letters and digits) - Case-sensitive
- Cannot be keywords
Examples:
x
userName
_private
item2
café
变量Member Access
Dot notation:
let userName = user.name
let city = user.address.cityBracket notation:
let first = items[0]
let nth = items[i]
let value = data["key"]
let name = users[0].nameOptional chaining:
let name = user?.name // undefined if user is null/undefined
let deep = obj?.prop?.nested // chain ?. at every potentially-missing stepMethod Calls
Method call syntax provides a concise and chainable way to invoke standard library functions on values.
Syntax:
<object>.<method>(<arguments>)How it works:
- Method calls are syntactic sugar for standard library function calls
- The object becomes the
itemsparameter of the underlying function - Parser transforms:
obj.method(args)→method(items: obj, ...args)
Examples:
// Select best item from array using LLM
let foods = ["pizza", "ice cream", "potato"]
let dessert = foods.pick(criteria: "dessert")
// With additional parameters
let best = items.pick(
criteria: "most popular",
model: "claude-sonnet-4.5",
systemPrompt: "You are a data analyst"
)
// Using variable criteria
let myCriteria = "healthiest option"
let healthy = foods.pick(criteria: myCriteria)
// A call result can be bound before reading its properties:
let best2 = users.pick(criteria: "most experienced")
let bestName = best2.name
// Member access can also follow an eagerly evaluated call:
let first = "red,green".split(value: ",")[0]Available methods:
array.pick(criteria: string, ...)- Select best item using LLMvalue.is(description: string, ...)- Semantic matching- Built-in string and array methods (
split,trim,toUpperCase,includes,append,push,pop, …) — see the Standard Library Reference
.length — property vs method: both forms work on arrays and strings.
items.length resolves as a plain property; items.length() calls the
built-in method. They return the same number.
let items = ["a", "b", "c"]
let n1 = items.length // 3 (property)
let n2 = items.length() // 3 (method)Benefits:
- More intuitive syntax for operating on collections
- Clear visual indication that method operates on the object
- All parameters from underlying stdlib function are supported
Comparison:
// Method syntax (recommended for readability)
let result1 = items.pick(criteria: "best")
// Function syntax (equivalent, more explicit)
let result2 = pick(items: items, criteria: "best")Both syntaxes are fully supported and produce identical behavior. Method syntax is recommended when the operation is conceptually acting "on" the object.
Binary Operators
See Operators Reference for complete operator details.
Arithmetic:
let sum = x + y // addition
let diff = x - y // subtraction
let product = x * y // multiplication
let quotient = x / y // division (division by zero throws)
let remainder = x % y // moduloComparison:
let gt = x > y // greater than
let gte = x >= y // greater than or equal
let lt = x < y // less than
let lte = x <= y // less than or equal
let eq = x == y // equality (loose, coercing — there is no ===)
let neq = x != y // inequality (loose, coercing — there is no !==)Logical:
let both = x && y // logical AND
let either = x || y // logical OR
let fallback = x ?? y // null coalescingUnary Operators
let neg = -x // negation
let num = +x // unary plus
let not = !x // logical NOTNumeric string coercion uses ECMAScript boundary whitespace, including U+FEFF
(BOM), not the Unicode White_Space set. U+0085 (NEXT LINE) is preserved and
makes a numeric string invalid. Non-finite expression results cannot be stored
as top-level variable values.
Binary (0b), octal (0o), and hexadecimal (0x) strings convert their full
integer value with nearest, ties-to-even rounding. Values beyond the finite
number range become Infinity.
Ternary Operator
Syntax:
<condition> ? <true-value> : <false-value>Examples:
let weather = temp >= 30 ? "hot" : "cold"
let discount = isPremium ? 0.2 : 0.1
let payout = score > 50 ? bonus * 2 : bonus * 0.5
// Nested ternary (right-associative)
let grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C'Parenthesized Expressions
let scaled = (x + y) * 2
let combined = (a && b) || cTemplating
String literals containing {{...}} are rendered as templates. A {{...}}
block is either a plain Liquid path (variable, property path, indexing,
optionally with | filters) or a kaya expression, which is evaluated by
the same expression engine as let initializers:
let greeting = "Hello {{name}}" // variable (Liquid path)
let line = "User: {{user.name}}" // property path
let pretty = "Data: {{config | json}}" // filters (Liquid)
let next = "Attempt {{attempt + 1}}" // kaya expression
let who = "Hi {{user.first ?? \"friend\"}}" // ?? and ternary work
let listing = "{% for r in recipes %}- {{r.title}}\n{% endfor %}" // tagsExpression blocks follow normal kaya expression semantics (coercion, ??,
ternary, member/index access — undefined ROOTS fail loud, pinpointed at the
variable). A | filter chain may follow the expression and applies to its
result — {{user.first ?? user.last | upcase}} — and || is always the
logical-or operator, never a filter pipe.
Evaluated values are inert at every sink
Only an authored string literal is a template. Any evaluated value —
a variable, member/index access, concatenation, call result, function
parameter, or loaded/generated text — passes through every sink verbatim,
including log/time:
let marker = "{" + "{name}}" // "{{name}}" assembled at runtime
log.info(message: marker) // logs the literal text {{name}}Runtime text becomes a template through these explicit surfaces:
render(template:), save/load with template: true, and
renderPdf(inputFile:) or renderEbook(inputFile:). String leaves nested inside
object/array literals are likewise inert. Native semantic analysis emits a
non-aborting nested-template-literal warning (code 3016) when an authored
leaf contains {{ or {%. The warning points to the quoted literal and suggests
explicit render(template: ...); the marker text itself creates no variable
read or template dependency.
The reserved env capability is keyed-only
env exposes live host environment reads one key at a time; it is not an
object or other first-class value. Dot access, literal bracket access, and a
computed bracket key are supported in expressions and templates:
let home = env.HOME
let sameHome = env["HOME"]
let requestedKey = "HOME"
let dynamicHome = env[requestedKey]
let rendered = "Home: {{env[requestedKey]}}"A computed access resolves its key first and authorizes only that exact key. Every access reads the running engine process's environment when it evaluates, so it is not implicitly persisted and can change between renders. Assigning a selected value to an ordinary variable deliberately creates ordinary program state; that copied string may then be persisted, passed, filtered, or serialized.
Bare env is always an error. It cannot be copied or passed as a value,
filtered or serialized, assigned to a Liquid alias, or iterated with a Liquid
tag:
let invalid = env // ERROR
let alsoInvalid = "{{env | json}}" // ERROR
let stillInvalid = "{% for pair in env %}{{pair}}{% endfor %}" // ERRORReading a missing selected key fails loudly and names the key. Handle expected
absence explicitly with ?? in a Kaya expression or | default in a plain
Liquid path:
let expressionFallback = env.REGION ?? "us-east-1"
let templateExpressionFallback = "{{env.REGION ?? \"us-east-1\"}}"
let liquidFallback = "{{env.REGION | default: 'us-east-1'}}"?? handles only an absent selected key and preserves a present empty string.
Liquid's default filter requires an explicit fallback argument and also
replaces a present empty string. Neither form turns the namespace into a value
or suppresses unrelated errors.
Liquid file-partial tags ({% include %}, {% render %}, and {% layout %})
are rejected in context-backed Kaya templates. They would implicitly carry
reserved capability roots into another file outside the validated template.
Use Kaya imports for program composition, or an explicit
render(template: nestedTemplate) call for an ordinary nested template string.
Recursive render filters are outside the native template vocabulary.
Function calls are NOT allowed inside {{...}}. Templates render
synchronously while a node executes, so there is no statement to run the
call before (at statement level, calls in expressions work by being hoisted
into preceding statements). Both the compiler (template-call diagnostic)
and the renderer reject them with the fix:
// ❌ "{{calculate(a, b)}}"
// ✅ Compute the value first, then interpolate:
let result = calculate(a: a, b: b)
let msg = "Total: {{result}}"Undefined variables (strict mode)
Rendering throws on undefined variables (strictVariables) — a typo'd or
missing variable in a prompt is a silent-poison footgun, so it fails loud. A
variable that exists with a null value renders as "" — null is a real
value; "never set" is the bug.
For ordinary template variables (as opposed to a missing keyed env access
above), the two sanctioned ways to touch a possibly-undefined variable are:
// 1. Lenient {% if %} — existence check does not throw
let section = "{% if subtitle %}Subtitle: {{subtitle}}{% endif %}"
// 2. | default — explicit fallback
let title = "{{ bookTitle | default: 'Untitled' }}"Any other reference to an undefined variable throws at render time.
Bracket access with a computed index — {{items[i + 1]}} — is a Kaya
expression and evaluates correctly. (Only plain keys — items[0],
items[key], o["k"] — stay on the Liquid path.)
Filters
Native Kaya supports this bounded filter vocabulary:
| Filter | Behavior |
|---|---|
json | JSON-serialize an ordinary value with JavaScript-compatible formatting; bare capability namespaces such as env are rejected before filters run |
slug | URL/filename-safe slug: accents stripped, lowercased, hyphenated, capped at 80 chars |
size | Array length or string length in UTF-16 code units; other values return 0 |
plus | Numeric addition |
remove | Remove matching text |
strip | Trim surrounding whitespace |
upcase / downcase | Upper/lowercase (null-safe → "") |
times | Numeric multiply: {{n | times: 3}} |
default | Fallback for undefined, null, false, or empty strings/arrays; takes one positional fallback value, with no named options |
first | First array item |
join | Join array items with a separator |
Other Liquid filters, including capitalize and recursive render, are not
part of this native vocabulary. Use the explicit render(template: ...)
function when text should be evaluated as a Kaya template.
Unknown filter names are a render-time error. {{title | upper}} (a typo
for | upcase) used to silently render the value unchanged; now it throws
Unknown filter "upper" with the registered names suggested — the same
fail-loud doctrine as undefined variables.
Interpolating objects and arrays (the [object Object] guard)
Kaya's JavaScript-compatible coercion can turn an ordinary object into
"[object Object]" when it is interpolated as {{var}}. The native runtime
detects this marker and throws at render time. Serialize or iterate explicitly:
let summary = "Recipes: {{recipes | json}}" // serialize
let list = "{% for r in recipes %}- {{r.title}}\n{% endfor %}" // iterateThe | image filter
{{photo | image}} in an echo statement embeds the file as an image part
of a multi-part chat message. It is implemented as echo-node pre-processing,
not a Liquid filter: it must be the sole filter in its placeholder
(chains like {{photo | image | something}} are not recognized). See
Chat & Output for multi-part messages.
Type Annotations
Simple Types
let x: number = 42
let name: string = "Alice"
let active: boolean = true
let data: json = {key: "value"}Note on file: a file value is an object
({path, filename, mimeType, size, sha256?, url?}), not a path string —
let d: file = "report.pdf" fails validation. file values come from stdlib
calls like generateImage() or load(). In templates, unpublished files stringify
to path, while published file roots with a .url stringify directly to their public URL.
See Built-in Types.
Array Types
let names: string[] = ["Alice", "Bob"]
let numbers: number[] = [1, 2, 3]
let matrix: number[][] = [[1, 2], [3, 4]]
let items: json[] = [{id: 1}, {id: 2}]Custom Types
type User = {name: string}
let user: User = {name: "Alice"}
let users: User[] = [{name: "Alice"}, {name: "Bob"}]Type Subtypes
Subtypes provide additional semantic meaning to base types.
Syntax:
<base-type>/<subtype>Examples:
let content: string/markdown = "# Hello"
let config: string/json = "{}"
// In function parameters
function render(doc: string/markdown) { }
// In type definitions
type Markdown = string/markdown
type PDFFile = file/pdfCommon subtypes:
string/markdown,string/json,string/xml,string/yamlstring/html,string/csvfile/pdf,file/png,file/svg,file/jpg(remember:filevalues are objects from stdlib calls, not path strings)number/percentage
Subtypes are open-ended semantic metadata — any base/word parses; they are
not a closed, validated set.
Functions
Function Definition
Syntax:
function <name>(<parameters>) { <body> }
function <name>(<parameters>): <return-type> { <body> }Parameters:
// Named parameters
name: type
// Optional parameters
name?: type
name: type = defaultValue
// Multiple parameters
(a: number, b: number, c?: string)Examples:
// Simple function
function greet(name: string) {
"Hello, {{name}}!"
}
// With return type
function add(a: number, b: number): number {
return a + b
}
// With optional parameters
function log(message: string, level?: string) {
let levelStr = level ?? "info"
"{{levelStr}}: {{message}}"
}
// With default parameters
function multiply(a: number, b: number = 2) {
return a * b
}
// With array parameters
function processItems(items: string[]): number {
return items.length
}
// Complex return
function calculate(x: number): json {
return {result: x * 2, timestamp: 123}
}Function Scope
Functions are closed-scope by default: the body sees only its parameters
(plus stdlib and runtime-provided _-variables), not the caller's variables.
Pass everything a function needs as parameters. The #openScope annotation on
a call opts back into the legacy open scoping. Default parameter values may
only be literals or other parameters — they cannot reference outer variables.
See the Functions guide and
Annotations for details.
Function Calls
Arguments:
All arguments to function calls are passed by name (or via the legacy first-argument JSON object). Named argument values can be any Kaya expression:
// Named arguments with literals
greet(name: "Alice")
add(a: 10, b: 20)
// Named arguments with expressions
add(a: x + 1, b: items[0] * 2)
filter(items: [img1, img2], limit: count - 1)
// Legacy JSON-style first argument
process({"input": "data", "count": 5})Closure Blocks
Functions can accept a trailing closure block.
Syntax:
<function>() { <closure-body> }
<function> { <closure-body> }
<function>(<arguments>) { <closure-body> }Examples:
// Closure only
withRetry {
let data = fetchData()
return data
}
// With arguments and closure
withRetry(maxAttempts: 5) {
let result = apiCall()
return result
}
// Assigned to variable
let result = withLogging(operation: "process") {
let data = loadData()
let processed = transform(input: data)
return processed
}The _closure Variable:
Inside a function, use the special _closure variable to access and execute a closure passed to that function.
function withRetry(maxAttempts: number) {
// Check if closure exists
if (_closure) {
// Execute closure without arguments
let result = _closure()
return result
}
}
function processWithArgs(value: string) {
// Execute closure with named arguments
if (_closure) {
let result = _closure(computedValue: "{{value}}_processed")
return result
}
}Key Points:
_closureisnullif no closure was provided- Always check
if (_closure)before calling - Can call without arguments:
_closure() - Can pass named arguments:
_closure(arg1: value1, arg2: value2) - Return value from closure is returned to the caller
See Functions Guide - Closure Variable for detailed examples.
Control Flow
If Statement
Syntax:
if <condition> { <body> }
if <condition> { <body> } else { <body> }
if <condition> { <body> } else if <condition> { <body> }
if <condition> { <body> } else if <condition> { <body> } else { <body> }Conditions:
- Expression:
if temp >= 30 - Parentheses optional:
if (x > 10) - Semantic match:
if feedback is "asking about pricing"— one explicit LLM call that answers true/false. Seeis. - Boolean coercion:
if answer as boolean— deterministically converts a boolean-like value. Unrecognized text errors; useisfor a model judgment. - Quoted string:
if "{{temp}} >= 30"— ❌ parse error. This form used to silently send the rendered text to an LLM to judge true/false — an invisible model round-trip, one character away from a free deterministic comparison. Write the expression directly (if temp >= 30), useisfor semantic checks, or make the LLM judgment explicit withgenerate:// Inline (first condition only; pass model: to route to a fast model) if generate(message: "Is it hot today in {{city}}?") as boolean { "Stay hydrated" } // Bound — works in else-if too, since calls can't run conditionally let isHot: boolean = generate(message: "Is it hot today in {{city}}?") if isHot { "Stay hydrated" } - A function or method call can be the first
ifcondition and runs once before the branch:if check(x: 1) { }. Calls remain invalid inelse if,whileanddo-whileconditions because eager evaluation would change when they run. Use a bound result in those positions.
Examples:
if temp >= 30 {
"Hot"
}
if score > 90 {
"Excellent"
} else {
"Good"
}
if x > 10 {
"High"
} else if x > 5 {
"Medium"
} else {
"Low"
}
// With function call
if shouldProcess {
processData()
}
// Nested
if hasPermission {
if isAdmin {
"Full access"
} else {
"Limited access"
}
}For Loop
Syntax:
for <item> in <iterable> { <body> }
for <item> in range(<count>) { <body> }
for <item> in range(<start>, <end>) { <body> }The iterable must evaluate to an array. An empty array runs zero iterations;
null, missing values, strings, numbers, booleans, and objects fail before the
loop body runs. Falsy values inside an array, such as [null, false, 0, ""],
are valid items. Use for item in items ?? [] { ... } when a null or missing
list should mean an empty array.
Examples:
Note: range() bounds can be number literals or any numeric expression
(range(count), range(start, start + batch)). Function calls are not
allowed inside a bound — assign the result to a variable first.
range(start, end) iterates start..end-1 (the named variable carries the
offset value; _index stays 0-based); a backwards range (range(5, 2))
fails loudly at runtime, and range(n, n) runs zero times.
// Range loop
for i in range(5) {
"Iteration {{i}}"
}
// Two-argument range: i = 3,4,5,6,7; {{_index}} = 0..4
for i in range(3, 8) {
"Value {{i}}"
}
// Array loop
for item in items {
"Item: {{item}}"
}
// With break
for i in range(100) {
if i == 10 {
break
}
"{{i}}"
}
// With continue
for item in items {
if item == "skip" {
continue
}
"Processing: {{item}}"
}
// Calling function in loop
for i in range(3) {
processItem(index: i)
}Special variables:
_item- current item value_index- current iteration index (0-based)
While Loop
Syntax:
while <condition> { <body> }Examples:
let x = 0
while x < 10 {
x = x + 1
}
while !done {
"Processing..."
}
let count = 0
while count < max && !error {
count = count + 1
}
// With break
while true {
if done {
break
}
"Working..."
}⚠️ Loop counters must use bare assignment. let x = x + 1 inside a loop
body declares a fresh block-scoped shadow that is discarded every iteration —
the outer x never changes and the loop never terminates. Use x = x + 1.
Do-While Loop
Syntax:
do { <body> } while <condition>Examples:
let x = 1
do {
x = x * 2
} while x < 100
do {
"At least once"
} while false
do {
let result = attempt()
if result {
break
}
} while tries < maxTriesDifference from while:
- Body executes at least once before condition is checked
- The same bare-assignment rule applies:
let x = x * 2in the body would shadow rather than updatex
Forever Loop
Infinite loop construct — equivalent in intent to while true, but explicit.
Syntax:
forever { <body> }Example:
forever {
let event = awaitEvent(query: subscription)
if event.done {
break
}
"Got: {{event.payload}}"
}Rules:
- Exit with
breakorreturn(inside a function) continueskips to the next iterationforeverintroduces a loop and nothing else. In expression position it is a syntax error — it used to lex as the boolean literaltrue, sowhile forever { }quietly meantwhile true { }. Writeforever { }.
Map Operation
Maps a function over an array. As with for, null, missing, and other non-array
sources fail before any iteration. An empty array produces an empty result;
falsy elements inside an array are preserved.
Syntax:
let <result> = map <collection> <function>(<arguments>)Examples:
import process from "processor"
// Map over array
let results = map items process({mode: "fast"})
// With template in arguments
let transformed = map data transform({input: "{{_item | json}}"})Special variables:
_item- current item being processed_index- current iteration index
Imports and Exports
Import
Import statements allow you to use functions and types defined in other Kaya files.
Syntax:
// Single named import
import <identifier> from "<path>"
// Multiple named imports
import <identifier1>, <identifier2>, ... from "<path>"
// Import with alias
import <identifier> as <alias> from "<path>"
// Multiple imports with mixed aliases
import <id1> as <alias1>, <id2>, <id3> as <alias3> from "<path>"
// Wildcard import (import all)
import * from "<path>"Examples:
// Single function import
import greet from "./helpers.kaya"
let msg = greet(name: "Alice")
// Multiple functions from same file
import add, subtract, multiply from "./math.kaya"
let result = add(a: 5, b: 3)
// Import with alias (rename on import)
import greet as sayHello from "./helpers.kaya"
let msg = sayHello(name: "Bob")
// Mixed: some with aliases, some without
import greet as sayHello, farewell from "./helpers.kaya"
// Wildcard: import all functions from file
import * from "./helpers.kaya"
// All functions (greet, farewell, etc.) now available
// Relative paths
import utils from "../utils/helpers"
// Absolute paths
import processor from "/path/to/processor"
// A package: a folder with a kaya.json
import tellStory from "../storytelling/"
// A package by URL, pinned in kaya.lock
import playEpisode from "https://example.com/packages/pickleworths/"Rules:
- Selective imports: Only imported functions are available in the current scope
- Wildcard imports (
import *): Makes all functions from the file available - Aliases: Rename functions during import to avoid naming conflicts
- File and registry-backed imports may omit the
.kayaextension, though it is recommended for clarity. Exact first-party built-in URIs do not take a file extension.
Import references:
| Reference | Example | Resolution |
|---|---|---|
| Relative path | ./helpers.kaya, ../utils/helpers | A module, from the importing file's directory |
| Absolute path | /path/to/processor | A module at that filesystem path |
Folder ending in / | ../storytelling/ | A folder package: imports the main module its kaya.json names. See Package Imports. |
https:// URL ending in / | https://example.com/packages/storytelling/ | A URL package: the same, from the package folder's URL, with every file it reads pinned in kaya.lock |
http:// URL ending in / on this machine | http://localhost:8000/storytelling/ | A URL package on localhost or a name under it, or at a loopback address such as 127.0.0.1 or [::1]. Plain http:// to a host that is not this machine is refused. |
lib://kaya/<module> | lib://kaya/agent-loop-v1 | Exact first-party module embedded with the runtime, for coding-profile sessions. The kaya namespace is reserved, cannot be shadowed by program paths, and rejects unknown module names. |
ref://<name> | Internal reference to a function already registered in the current session (used by the runtime; rarely written by hand) | |
http(s):// URL not ending in / | https://example.com/packages/storytelling/main.kaya | Refused before the run: only a package, which has a kaya.json to name it, can be imported by URL. Import its folder URL. |
| Any other scheme | file://…, lib://<name>, test://… | Refused before the run |
Import Behavior:
- Only functions explicitly imported (or all with
*) are added to scope - Import public custom types explicitly with
typewhen an imported function's signature uses them; mixed function/type imports are supported - Importing the same file multiple times reuses the already-loaded module
- Circular imports are allowed but may cause runtime errors if not carefully managed
Function name resolution: a call resolves in the file whose code makes the call. A trailing closure counts as code of the file that wrote it, even when another file's function runs it. The lookup order is:
- a function the file itself defines;
- a function the file imports by name (
import f,import g as f); - a function a wildcard import (
import * from ...) of the file provides.
Two files can therefore each keep a private helper with the same name. A
function another file defines is not in scope just because that file is
loaded: calling it without importing it fails with Undefined function.
Some name conflicts are refused when the file loads, and the error names both sides:
- a file defines a function and also imports a different function under the
same name (
import f, orimport g as fin a file that definesf); - two named imports bind one name to different functions.
A file's own definitions shadow functions its wildcard imports provide. A name that two wildcard imports provide fails as ambiguous when it is called; import the one you mean by name, or under an alias.
Package Imports
A reference ending in / imports a package: a folder with a kaya.json
naming the package (name), its version, and its main module (default
main.kaya). The folder is named by its path or by its URL. The imported names
are functions the main module defines.
import tellStory from "../storytelling/"
import playEpisode from "https://example.com/packages/pickleworths/"Rules:
- A package module's identity is its package's name and version plus its path in the package, never the folder's location or URL.
- A package's modules may import its own modules (
./scenes.kaya) and other packages (../storytelling/). A path that leaves the package is refused before the run. - A package declares the files it uses with
resource "<file>"(noas,inorfrom), and its code reads them withasset(path:). In the session they live under.packages/<name>@<version>/. - One program uses one copy of each package version. The same
name@versionfrom two places, whether two folders, two URLs, or a folder and a URL, is refused. - A URL package's address is
https://(http://only for this machine), with no user name, password, query or fragment. Its relative references resolve against its URL. It never imports a local folder, afile://path or alib://library, and a package from the public internet never imports one on this machine. - Every file a program reads from a URL package is pinned in
kaya.lockbeside the program on first use, and checked against its pin before later runs. A redirect, a status other than 200, an HTML page in place of a file, or a file that no longer matches its pin is refused before the run. - A session copies the files of every package its program imports, and those of the packages they depend on, when it is created. Its run, and a resumed session, read only those copies, and never fetch a URL package again. If the session began with packages, a package import it was not created with is refused; a URL package import it was not created with is refused either way.
See Packages for a complete example, and
Packages from a URL for addresses,
kaya.lock, limits and errors.
Type Imports
NEW: Kaya now supports importing type definitions from other files using explicit type keyword syntax (inspired by TypeScript).
Syntax:
// Single type import
import type <TypeName> from "<path>"
// Multiple type imports
import type <Type1>, type <Type2>, ... from "<path>"
// Type import with alias
import type <TypeName> as <Alias> from "<path>"
// Mixed: functions and types
import type <Type>, <function>, type <Type2> from "<path>"
// Wildcard (imports ALL - both functions and types)
import * from "<path>"Examples:
// Types file (types.kaya)
type Person = {
name: string,
age: number
}
type Address = {
street: string,
city: string
}
// Main file - Import single type
import type Person from "./types"
let user: Person = {
name: "Alice",
age: 30
}
// Import multiple types
import type Person, type Address from "./types"
let user: Person = { name: "Bob", age: 25 }
let location: Address = { street: "123 Main St", city: "Boston" }
// Import type with alias
import type Person as User from "./types"
let admin: User = { name: "Charlie", age: 40 }
// Mixed imports (both types and functions)
import type Greeting, greet from "./helpers"
let msg = greet(name: "Diana")
let greeting: Greeting = {
message: msg,
timestamp: 1234567890
}
// Wildcard imports ALL (both functions and types)
import * from "./types"
let user: Person = { name: "Eve", age: 35 }
let location: Address = { street: "456 Oak", city: "Portland" }Rules:
- Explicit is better: Must use
typekeyword before each type import- ✅ Correct:
import type Recipe, type User from "types" - ❌ Wrong:
import Recipe, User from "types"(will look for functions, not types)
- ✅ Correct:
- Mixed imports: Can import both types and functions in one statement
import type Recipe, generateRecipe, type ColorScheme from "lib"
- Wildcard includes types:
import *imports both all functions AND all types - Type names must match: Import name must match the type definition name
- Aliases work: Can rename types during import to avoid conflicts
Why use type keyword?
- Clarity: Makes it immediately obvious what's being imported (type vs function)
- No ambiguity: Parser doesn't need to guess or check the target file
- TypeScript-inspired: Familiar syntax for TypeScript developers
- Future-proof: Leaves room for type-only files and other features
Error Messages:
// Importing non-existent type
import type NonExistent from "./types"
// ❌ Error: Cannot import type 'NonExistent' from ./types.kaya: type not found
// Available types: Person, AddressSkill Imports
NEW: A Skill is a first-class, typed capability — "how to do X, and how
to check X" — loaded with import skill and bound in scope as a value your
program can hold and hand to an agent loop. A skill is distinct from a tool
(a function the LLM calls mid-generation) and a resource (raw bytes staged
into a sandbox): it carries method prose plus an optional consumes/produces
contract and the checks that gate its output.
Syntax:
// Single skill — the ref IS the skill manifest
import skill <name> from "<ref>"
// Alias
import skill <name> as <alias> from "<ref>"
// Multiple — the ref is a DIRECTORY; each name is <ref>/<name>
import skill <name1>, <name2> as <alias2> from "<ref>"A skill is authored as a <name>.skill.md manifest: a YAML frontmatter
block (the Skill fields) followed by the method body.
---
name: write-piece
description: Write a short piece from a source dossier, in a house voice.
consumes: Dossier
produces: article
checks:
- quote-in-dossier
- within-length
---
Lead with the sharpest claim, ground every assertion in the dossier, and never
invent a quote.// Single skill from the filesystem (resolves ./skills/write-piece.skill.md)
import skill writePiece from "./skills/write-piece"
// With an alias (resolves ./skills/review.skill.md)
import skill review as rv from "./skills/review"
// Multiple skills from a directory (./editing/critique.skill.md, …)
import skill critique, rewrite as rw from "./editing"
// The bound value carries the manifest fields
"{{writePiece.name}} produces {{writePiece.produces}}" // write-piece produces articleRules:
- Ref resolution: a relative ref resolves from the importing file's
directory, and an absolute one is a filesystem path. A bare ref gets a
.skill.mdextension; a ref already ending in.md/.mdxis used as-is. Afile://URL names the manifest file exactly, with no extension added. The runtimes refuse a ref with any other scheme,http(s)://included, before the run: skills are not imported by URL. - Single vs. multiple: one name treats the ref as the manifest itself;
multiple names treat the ref as a directory and resolve each name to
<ref>/<name>. - Binding name: the skill is bound under its alias (or name) — independent
of the manifest's own
namefield. - Typed contract: if a skill declares
consumes/produces, each must name a known type — a built-in (string,json, …), atype Xdefined in the importing program, or animport type X. An unknown type name is rejected at import (so a typo'd contract can't slip through). - Fails loud: a manifest missing its frontmatter, its
name, or its method body is rejected at import time.
Sandbox staging. Importing a skill also stages it into the sandbox
filesystem so an agent running inside a sandbox (its working directory is the
VFS root) can read it. The method is written to /.skills/<name>/SKILL.md and
any declared assets land alongside it at /.skills/<name>/<asset>. This
mirrors how resource stages files; the dot-prefixed .skills/ namespace keeps
skills clear of your own staged content. Point your agent at .skills/ to
discover them.
Auto-Import
Some statements automatically create imports:
Historically jump "workflow.kaya" auto-imported its target. jump is gone;
call the imported function instead.
Operator Precedence
This is the authoritative precedence table (verified against the parser). From highest to lowest:
| Precedence | Operators | Description |
|---|---|---|
| 1 (highest) | () [] . ?. | Grouping, member access |
| 2 | as | AI type cast (binds to the immediately preceding operand) |
| 3 | - + ! (unary) | Unary operators |
| 4 | * / % | Multiplicative |
| 5 | + - | Additive |
| 6 | > >= < <= | Relational |
| 7 | == != is | Equality, semantic match |
| 8 | && | Logical AND |
| 9 | ` | |
| 10 | ?? | Null coalescing |
| 11 (lowest) | ? : | Ternary conditional |
There are no === / !== operators.
Associativity:
- Most binary operators: left-to-right
- Ternary (
? :): right-to-left - Unary operators: right-to-left
Notes:
asbinds tighter than everything but member access:a + b as numbercasts onlyb;-y as numbernegates the cast result. After a type name,+starts a constraint block, sox as string + "suffix"is a parse error — parenthesize(x as string) + "suffix".isparses at the equality level (a == b is "desc"matches the result ofa == b), but combiningiswith&&/||is a parse error; with? :or??it parses but fails at runtime. Standalone bindings (let r = x is "desc") and directif/whileconditions are the supported forms. See Operators.??binds looser than||/&&and may be mixed with them without parentheses (unlike JavaScript).
Reserved Keywords
The following identifiers are reserved and cannot be used as variable or function names:
as assert assertEqual assertFalse assertTrue
break const continue do else
false for forever from function
if import in is let
map null pause range resource
resources return throw true type
whileThese are reserved only where the construct they head is still possible; the
Literals section above shows where the same words are ordinary names. true, false, null, is, as, and
forever are reserved in expression position too.
The list is generated from the lexer into
packages/kaya-conformance/keywords/keywords.json
(cargo run -p kaya-core --bin keywords); the tree-sitter grammar, the
TextMate grammar, and the shared token highlighter are held to that file by a
drift test.
Naming Conventions
Identifiers
Identifiers accept Unicode, so a non-English program can name things in its own language. The conventions below are recommendations, not rules.
-
Variables/Functions:
camelCase(recommended)let userName = "Alice" function calculateTotal() { } -
Types:
PascalCase(recommended)type UserProfile = { name: string } -
Constants:
UPPER_SNAKE_CASE(optional)const MAX_RETRIES = 5
Special Variables
Variables starting with underscore are reserved for special runtime-provided values:
-
_item- Current item inforloops andmapoperationsfor item in items { "Processing: {{_item}}" } -
_index- Current index (0-based) inforloops andmapoperationsfor item in items { "Item {{_index}}: {{_item}}" } -
_closure- Closure block passed to a function (callable reference)function withRetry() { if (_closure) { let result = _closure() // Execute the closure return result } }See Closure Blocks for details.
-
_annotations- Annotations on the current node (advanced)#debug let result = generate(message: "Hello") // _annotations contains {debug: true}
Whitespace and Formatting
Significant Whitespace
- Newlines separate statements
- Indentation is not significant (but recommended for readability)
Line Continuation
Long statements can span multiple lines:
let result = calculate(
a: 10,
b: 20,
c: 30
)
let config = {
name: "app",
version: "1.0",
debug: true
}Statement Separators
- Newline ends a statement
- No semicolons required
- Semicolons not supported
File Organization
Recommended file structure:
// 1. Imports
import utils from "./utils"
import process from "../processors/main"
// 2. Type definitions
type User = {
name: string,
email: string
}
// 3. Constants
const MAX_ITEMS = 100
// 4. Function definitions
function processUser(user: User) {
// Function body
}
// 5. Main program logic
let users = loadUsers()
for user in users {
processUser(user: user)
}Grammar Summary
Formal Syntax Notation
Program ::= Statement*
Statement ::=
| "let" Identifier [":" Type] "=" Expression
| "let" Identifier "," Identifier "=" FunctionCall
| "const" Identifier [":" Type] "=" Expression
| Identifier "=" Expression
| String
| "[" Identifier "]" String
| "type" Identifier "=" TypeExpression
| FunctionCall
| "import" Identifier "from" String
| "return" [Expression]
| "break"
| "continue"
| "pause"
| "throw" ["(" ["message" ":" String] ")"]
| ("assert" | "assertTrue" | "assertFalse") Expression ["," String]
| "assertEqual" Expression "," Expression ["," String]
| IfStatement
| ForLoop
| WhileLoop
| DoWhileLoop
| ForeverLoop
| MapStatement
| FunctionDefinition
Expression ::=
| Literal
| Identifier
| BinaryExpression
| UnaryExpression
| ConditionalExpression
| MemberExpression
| MethodCall
| ParenthesizedExpression
MethodCall ::=
Identifier "." Identifier "(" Arguments ")"
FunctionDefinition ::=
"function" Identifier "(" Parameters ")" [":" Type] "{" Statement* "}"
IfStatement ::=
"if" Condition "{" Statement* "}"
("else" "if" Condition "{" Statement* "}")*
["else" "{" Statement* "}"]
ForLoop ::=
"for" Identifier "in" (Identifier | "range" "(" Expression ["," Expression] ")") "{" Statement* "}"
WhileLoop ::=
"while" Condition "{" Statement* "}"
DoWhileLoop ::=
"do" "{" Statement* "}" "while" Condition
ForeverLoop ::=
"forever" "{" Statement* "}"See Also
- Operators Reference - Complete operator details
- Built-in Types Reference - Type system documentation
- Annotations Reference - Annotation system
- Standard Library Reference - Built-in functions