Functions

How to declare, call, and close over functions

Function Declarations

Basic Function

function greet(name: string) {
  "Hello, {{name}}!"
}

greet(name: "Alice")

Functions are declared with the function keyword, followed by a name, parameters, and a body.

Function with No Parameters

function hello() {
  "Hello, world!"
}

hello()

Empty parentheses indicate no parameters required.

Function with Return Type

function add(a: number, b: number): number {
  return a + b
}

let result = add(a: 10, b: 5)
"10 + 5 = {{result}}"
Run in Browser No model needed

Specify return type after the parameter list with : type.

Parameters

Required Parameters

function createUser(name: string, email: string, age: number) {
  return {
    name: name,
    email: email,
    age: age
  }
}

createUser(name: "Alice", email: "alice@example.com", age: 30)

Required parameters must be provided when calling the function.

Optional Parameters

function greet(name?: string) {
  let displayName = name ?? "friend"
  let greeting = "Hello, {{displayName}}!"
  return greeting
}

// Both calls are valid
greet(name: "Alice")  // "Hello, Alice!"
greet()               // "Hello, friend!"

Mark parameters optional with ? after the name. Optional parameters can be omitted when calling.

(Note the let-then-return — templates in a bare return "..." are not rendered; see Returning Rendered Text.)

Important: Required parameters must come before optional parameters:

// ✓ Valid
function process(required: string, optional?: number) { }

// ✗ Invalid - required after optional:
// function process(optional?: number, required: string) { }

Default Values

function greet(name: string = "friend") {
  let greeting = "Hello, {{name}}!"
  return greeting
}

greet()              // "Hello, friend!"
greet(name: "Bob")   // "Hello, Bob!"
Run in Browser No model needed

Parameters with default values are automatically optional.

Default value expressions are evaluated inside the function's own (closed) scope — see Function Scope. They can use literals, expressions over literals, and the function's other parameters — but not variables from the caller or the definition site:

// ✓ Literals
function testA(count: number = 42) { "ok" }
function testB(flag: boolean = true) { "ok" }

// ✓ Expressions over literals
function testC(result: number = 10 + 5) { "ok" }

// ✓ Other parameters (param-local)
function testD(input: number, fallback: number = input) { "ok" }

// ✗ Outer-scope identifiers parse but FAIL at runtime
// (the function cannot see the caller's variables):
// function testE(value: number = defaultValue) { "..." }
// function testF(name: string = user.name) { "..." }
// function testG(mode: string = isProd ? "prod" : "dev") { "..." }

Parameter Types

Built-in types:

function handle(
  name: string,
  count: number,
  active: boolean,
  data: json,
  attachments: file[]
) {
  // Implementation
}

(There is no files type — use file[] for a list of files.)

Custom types:

type User = {
  name: string,
  email: string + { email: true }
}

function processUser(user: User) {
  "Processing {{user.name}}"
}

Array types:

function processNames(names: string[]) {
  return names.length
}

function processUsers(users: User[]) {
  // Process array of User objects
}

// Nested arrays
function processMatrix(matrix: number[][]) {
  // Process 2D array
}

Array types use TypeScript-style [] notation.

Parameter Syntax Variations

Named parameters (preferred):

function greet(name: string, age: number) {
  "Hello {{name}}, age {{age}}"
}

JSON-style parameters:

function greet({"name": string, "age": number}) {
  "Hello {{name}}, age {{age}}"
}

Braced named parameters:

function greet({name: string, age: number}) {
  "Hello {{name}}, age {{age}}"
}

All three styles are equivalent. Use named parameters for clarity.

Return Statements

Returning Values

function add(a: number, b: number): number {
  return a + b
}

Use return to exit a function and optionally return a value.

Return Expressions

Return supports full expressions:

// Arithmetic
function calculate(x: number, y: number): number {
  return x + y
}

// Ternary
function getDiscount(isPremium: boolean): number {
  return isPremium ? 0.2 : 0.1
}

// Comparison
function isHot(temp: number): boolean {
  return temp >= 30
}

// Member access
function getUserName(user: json): string {
  return user.name
}

// Logical operations
function canAccess(user: json): boolean {
  return user.isActive && user.hasPermission
}

// Null coalescing
function getName(user: json): string {
  return user.name ?? "Unknown"
}

// Nested ternary
function getGrade(score: number): string {
  return score >= 90 ? "A" : score >= 80 ? "B" : "C"
}

Returning Rendered Text

A string literal in a return renders its template, the same as a bare-string statement or a let initializer:

// ✓ Renders in the function's scope before returning
function greet(name: string) {
  return "Hello, {{name}}!"
}

// ✓ Equivalent: bind first, then return the variable
function greetViaLet(name: string) {
  let greeting = "Hello, {{name}}!"
  return greeting
}

Empty Return

function notify(message: string) {
  "Notification: {{message}}"
  return
}

Return without a value exits the function early — but it does not produce a value, not even null. If a caller assigns the result (let r = notify(message: "hi")), r is simply never set, and a later read of r fails with a missing-variable error. If callers will assign the result, return an explicit value on every path.

Return Type Annotations

type User = {
  name: string,
  age: number
}

function getUser(id: number): User {
  return {name: "Alice", age: 30}
}

Return type annotations are validated at runtime: a return value that doesn't conform to the declared type fails loud with a structured type error, just like parameter types and let annotations.

Closure Blocks

Closure blocks allow passing executable code blocks to functions, similar to Swift's trailing closures.

Basic Syntax

With arguments and closure:

myFunction(param: "value") {
  "Closure body"
}

Closure only (no arguments):

myFunction {
  "Closure body"
}

Empty closure:

myFunction() {
}

Closure Variable

Inside a function, the special _closure variable allows you to access and execute a closure passed to that function. This enables powerful patterns like retry logic, resource management, and custom control flow.

Basic Closure Execution

Check if a closure exists and execute it:

function withLogging() {
  "Starting operation..."

  // Check if closure was provided
  if (_closure) {
    "Calling closure..."
    let result = _closure()
    "Closure returned: {{result}}"
    return result
  }

  "No closure provided"
  return null
}

// Call with a closure
let output = withLogging {
  "Inside the closure!"
  let value = 42
  return value
}

"Final output: {{output}}"  // Prints: "Final output: 42"
Run in Browser No model needed

Passing Arguments to Closures

Closures can receive arguments from the function that calls them:

function processWithArgs(value: string) {
  "Starting with value: {{value}}"

  if (_closure) {
    // Pass arguments to the closure
    let closureResult = _closure(computedValue: "{{value}}_processed")
    "Closure returned: {{closureResult}}"
    return closureResult
  }

  "Done with processing"
}

// Closure receives the argument
let result = processWithArgs(value: "test") {
  "Received: {{computedValue}}"
  return "success"
}

"Final result: {{result}}"  // Prints: "Final result: success"

Retry Pattern

For plain retry-on-failure, prefer the declarative #retryCount annotation (#retryCount:3 let data = fetchFromAPI()) — it retries thrown errors, rolls back failed-attempt chat, and supports #retryDelay. Reach for a closure when the retry CONDITION is custom (e.g. retry on an unsatisfying-but-valid result):

function withRetry(maxAttempts: number = 3) {
  let attempts = 0

  while attempts < maxAttempts {
    attempts = attempts + 1

    if (_closure) {
      let result = _closure()
      if (result) {
        return result
      }
    }
  }

  return null
}

// Call with trailing closure
let data = withRetry(maxAttempts: 5) {
  let result = fetchFromAPI()
  return result
}

Checking Closure Existence

Always check if _closure exists before calling it:

function checkClosure() {
  // Safely check if closure was provided
  if (_closure) {
    "Closure was passed!"
    return "success"
  }

  "No closure"
  return "failed"
}

// With closure
let result1 = checkClosure {
  "This is the closure"
}  // Returns: "success"

// Without closure
let result2 = checkClosure()  // Returns: "failed"

Important: The _closure variable is a callable reference to the closure block. It is null if no closure was provided to the function.

Closure Block Content

Closures can contain any statements:

processData {
  // Variable declarations
  let x = 10
  let y = 20

  // Control flow
  if x > 5 {
    "Large x"
  }

  // Loops
  for i in range(3) {
    "Iteration {{i}}"
  }

  // Function calls
  helper(value: x)

  // Return
  return x + y
}

Nested Closures

outer {
  "Outer closure"
  inner {
    "Nested closure"
  }
}

Closures can be nested to any depth.

Assignment with Closures

// Set with closure
let result = compute() {
  return 42
}

// Const with closure
const result = compute {
  return 100
}

The function's return value is assigned to the variable.

Function Calls

Named Arguments

function greet(name: string, age: number) {
  "Hello {{name}}, you are {{age}}"
}

// Named arguments (order doesn't matter)
greet(name: "Alice", age: 30)
greet(age: 30, name: "Alice")  // Same result

All function calls use named arguments for clarity.

Variable References in Arguments

let userName = "Alice"
let userAge = 30

// Pass variables as arguments
greet(name: userName, age: userAge)

Bare identifiers in arguments are automatically treated as variable references.

Special variables in loops:

for item in items {
  process(
    item: _item,      // Current item
    index: _index     // Current index
  )
}

Mixed Argument Types

myFunc(
  a: userName,        // Variable reference
  b: "literal",       // String literal
  c: 42,              // Number literal
  d: true,            // Boolean literal
  e: null,            // Null literal
  f: _item            // Special variable
)

The parser automatically distinguishes between literals and variable references.

Empty Arguments

// With empty parens
myFunc()

// With empty braces
myFunc({})

Both forms call the function with no arguments.

Function Scope

Functions are closed by default: a function body sees its parameters (plus special variables like _closure and _annotations) and nothing else. It cannot read the caller's variables, and any variables it writes do not propagate back out. Arguments are the only way in; the return value is the only way out.

let projectName = "Atlas"

function describe() {
  // ✗ projectName is NOT visible here — using it is an
  //   undefined-variable error:
  // let summary = "Working on {{projectName}}"
  return "functions cannot see outer variables"
}

// ✓ Pass what the function needs as an argument
function describeProject(name: string) {
  let summary = "Working on {{name}}"
  return summary
}

let summary = describeProject(name: projectName)

Because the scope is closed, reads of undeclared variables inside a function can be flagged at compile time instead of failing mid-run.

Opting Out with #openScope

The #openScope annotation on the call site opens the scope completely for that call: the function reads and writes the invoking frame's variables.

let counter = 0

#openScope
function bump() {
  counter = counter + 1
}

#openScope bump()
"counter is now {{counter}}"  // 1

Note the annotation in two places: the call-site #openScope is what opens the scope at runtime; the definition-site #openScope tells the compile-time checker that the function intentionally reads outer variables (otherwise counter inside bump is flagged as undefined).

#writeIsolated (call site) is the middle setting: the function can read the caller's variables, but its writes don't propagate. Use both sparingly — open-scope functions lose compile-time undefined-variable checking and can depend on (or mutate) caller state invisibly. See the Annotations Reference.

Closures Execute Against the Invoking Frame

A closure block does not capture variables from where it is written — there is no lexical capture. When a function invokes _closure(), the closure body executes against that function's frame: it sees the invoking function's parameters and locals, loop variables like _item, and any arguments passed via _closure(name: value) — but not variables from the closure's definition site.

function eachUser(users: json[]) {
  for user in users {
    if (_closure) {
      _closure()
    }
  }
}

let label = "ACTIVE"

eachUser(users: users) {
  // ✓ _item comes from eachUser's loop frame
  "Processing {{_item.name}}"

  // ✗ label lives at the definition site, which closures
  //   do not capture — using it here fails:
  // "{{label}}: {{_item.name}}"
}

To use a definition-site value inside a closure, pass it into the function as an argument and have the function forward it: _closure(label: label).

Consequences for Default Values

Default parameter expressions evaluate inside the function's closed frame, so they can reference literals and the function's other parameters — never caller or definition-site variables. See Default Values.

Annotations on Functions

Description Annotation

#description:"Search for flights between cities"
function searchFlights(origin: string, destination: string, date: string) {
  // Implementation
}

Add descriptions for AI tool calling or documentation. (Note: from is a reserved keyword — it can't be used as a parameter name.)

Multiple Annotations

#debug #retryCount:3 let user = fetchUser(id: 42)

Annotations combine freely on a statement. Note that behavior-changing annotations like #debug and #retryCount take effect at the call site — on a function definition they are merely visible to the callee via _annotations. See the Annotations Reference for details.

Go-Style Error Handling

Kaya does not use traditional try-catch-finally blocks. Instead, it features an explicit, modern, Go-style error handling pattern via tuple destructuring during function calls. This design forces developer clarity, prevents nested catch-block fatigue, and integrates perfectly with AI generation flows.

How Error Catching Works

When you invoke a user-defined function, you can choose how to assign its output:

  1. Standard Assignment (let result = call()): If an exception occurs during execution, the error propagates up the stack, immediately halting execution unless intercepted by a frame higher up.

  2. Tuple-Destructuring Assignment (let result, err = call()): If an exception is raised inside the function (or propagates through it), the Kaya runtime intercepts it, sets the first variable (result) to null, and populates the second variable (err) with a structured error object. If the function succeeds, the return value goes into result and err is set to null.

// 1. Uncaught propagation (halts execution on division by zero)
let outcome = divide(a: 10, b: 0)

// 2. Go-style caught propagation (continues execution gracefully)
let outcome, err = divide(a: 10, b: 0)
if err != null {
  "Failed to divide: {{err.message}}"
}
Run in Browser No model needed

The Structured Error Object

The built-in Error type accepts message: string, optional code: string, and optional details: any. Native tuple catch keeps the owner's message and places its structured diagnostic fields inside details:

{
  "message": "Value does not match type \"number\"",
  "details": {
    "code": 4003,
    "errorName": "TypeValidationError",
    "suggestion": "Check the declared type and pass a value that matches it."
  }
}

details.code is the runtime owner's numeric code; it does not replace the optional string Error.code. filename and range appear in details when the owner has real authored source. suggestion and additionalDetails retain their supplied values, including empty strings or JSON null; missing values stay absent. Catch does not invent guidance.

Provider failures can additionally include details.providerError and details.providerFailure. The former follows the public diagnostic's original provider error selection; the latter retains the exact original envelope. No envelope, {}, and { "error": {} } have different meanings. Original provider codes remain separate from the runtime code and any effective additionalDetails.providerCode. Provider text does not establish Kaya source or host authority.

An Error variable or return retains these fields. A narrower variable such as {message: string} projects away details; current native parameter and return validation retains the supplied object. Already-bound caught values in older checkpoints replay unchanged. Retries happen before tuple catch, and Internal failures and cancellation still propagate to the session's terminal diagnostic rather than being caught.

Critical Limitation: Wrapping Standard Library Calls

Important: Standard library functions (like renderHtml, readFile, fetch, etc.) are direct runtime instructions and do not push user frames onto the execution stack. As a result, bare calls like let result, err = renderHtml(...) cannot intercept errors.

To catch standard library exceptions, you must wrap the call inside a user-defined function. This creates the necessary stack frame for the tuple-destructuring boundary to catch the error.

// ✗ INVALID - Cannot catch errors on bare stdlib calls
let html, err = renderHtml(componentResource: "bad-file.tsx", props: {})

// ✓ VALID - Wrap in a user-defined function to intercept the error
function tryRender(component: string) {
  let html = renderHtml(componentResource: component, props: {})
  return html
}

let html, err = tryRender(component: "bad-file.tsx")
if err != null {
  "Caught render exception: {{err.message}}"
}

Error Handling Philosophy

Kaya's Go-style error handling is a conscious linguistic choice built around three key pillars:

1. Robustness for AI and LLMs

Traditional try-catch structures create deep block-scoping nesting and complex control-flow trees. LLMs are notoriously prone to generating incorrect scoping, leaking variables outside of catch blocks, or ignoring edge cases when faced with implicit throwing semantics. Go-style destructuring makes error states and variables explicit first-class values. The AI is forced to see that a function returns a potential failure state, prompting it to write the subsequent if err != null handling block immediately.

2. Reduced Control Flow Nesting

Deeply nested try-catch trees make code incredibly difficult to read and maintain. Destructuring allows a clean, top-to-bottom procedural flow where failure paths are checked and exited early (guard clauses), leaving the happy path unindented.

3. Clear Exception Boundaries

By treating functions as the primary exception boundary, Kaya makes it transparent where errors originate and where they are resolved. It ensures that critical runtime operations are insulated from catastrophic failures while keeping the code highly performant and predictable.


Common Patterns

Now that we understand Go-style error handling, let's see how standard wrapper patterns are implemented in Kaya.

Retry Logic (with Closures)

We can leverage closures and tuple destructuring to implement robust, reusable retry wrappers:

function withRetry(maxAttempts: number = 3) {
  let attempts = 0
  while attempts < maxAttempts {
    attempts = attempts + 1
    
    // Execute closure inside a tuple-destructuring boundary
    let result, err = _closure()
    if err == null {
      return result
    }
    
    if attempts >= maxAttempts {
      throw(message: "Max retries exceeded after {{attempts}} attempts. Last error: {{err.message}}")
    }
  }
}

// Call with a closure block
let data, err = withRetry(maxAttempts: 5) {
  let response = fetchFromAPI()
  return response
}

if err != null {
  "API failure: {{err.message}}"
}

Logging Wrapper

Closures can wrap execution paths to provide clean, centralized diagnostics:

function withLogging(operation: string) {
  "Starting: {{operation}}"

  let result, err = _closure()

  if err != null {
    "Failed: {{operation}}. Error: {{err.message}}"
    throw(message: "{{operation}} failed: {{err.message}}")
  }

  "Completed: {{operation}}"
  return result
}

let processed = withLogging(operation: "data-processing") {
  let data = loadData()
  let result = processData(input: data)
  return result
}

ForEach Pattern

function forEach(items: json[]) {
  for item in items {
    if (_closure) {
      _closure()  // Closure has access to loop variables
    }
  }
}

forEach(items: users) {
  "Processing: {{_item.name}}"
  updateUser(user: _item)
}

Conditional Execution

function when(condition: boolean) {
  if condition {
    if (_closure) {
      let result = _closure()
      return result
    }
  }
}

when(condition: isDebugMode) {
  "Debug: Processing started"
  logDetails()
}

Advanced Features

Function as Tools

Functions can be exposed to LLMs as tools:

#description:"Calculate the area of a rectangle"
function calculateArea(width: number, height: number): number {
  return width * height
}

let result = generate(
  message: "What's the area of a 5x10 rectangle?",
  tools: [{"function": "calculateArea"}]
)

The LLM can call calculateArea during generation.

Type-Safe Parameters

type Rectangle = {
  width: number + { min: 0 },
  height: number + { min: 0 }
}

function getArea(rect: Rectangle): number {
  return rect.width * rect.height
}

// ✓ Valid
getArea(rect: {width: 5, height: 10})

// ✗ Invalid - negative width
getArea(rect: {width: -5, height: 10})

Custom types ensure parameters meet validation rules.

Default Value Patterns

// Configuration with defaults
function configure(
  host: string = "localhost",
  port: number = 8080,
  timeout: number = 30000
) {
  return {host: host, port: port, timeout: timeout}
}

// Only override what's needed
configure(port: 3000)

Best Practices

  1. Use named arguments: Always call functions with named arguments for clarity
  2. Type your parameters: Add type annotations to catch errors early
  3. Document with descriptions: Use #description for functions exposed as tools
  4. Prefer optional over defaults: Use ? when no sensible default exists
  5. Keep functions focused: Each function should do one thing well
  6. Use closures for control flow: Leverage closure blocks for elegant patterns
  7. Return typed values: Specify return types for important functions

Next Steps