Modules

Rook — 1.0 specification

import { readFileSync, writeFileSync as write } from "node:fs"
import * as path from "node:path"
import express from "express"
import "./setup.rk"

export func greet(name string) string {
    return `Hello, ${name}`
}
export const VERSION = "0.1.0"
export class User { ... }
export interface Point {
    x, y number
}

Imports and exports become ES modules one to one; export interface and export type disappear at compile time.

The runtime

const jobs = chan<number>(10)
jobs <- 1
import { $$channels } from 'rooklang/runtime'

const jobs = $$channels.make(10, 0)
await $$channels.send(jobs, 1)

What the code cannot do with JS alone, such as channels, goroutines, queues, defer inside a loop and the blocks of markup, is done by functions of a small library, the runtime: rooklang/runtime in the package. A module imports the ones its code uses, by their names, which start with $$ like all names of generated code; a module that needs none imports nothing. After $$ they start with a small letter ($$channels, $$deque), and the functions of components with a capital one ($$Card), so a component may have any name.

Types from TypeScript

The types of imports that are not .rk modules come from TypeScript declarations: packages with types in package.json or with @types/*, .ts files and Node modules (node:fs, node:http from @types/node). The typescript package reads them during type checking, along with the standard library. A module without declarations, such as a JS file without a .d.ts, stays any.

import { readFileSync } from "node:fs"
import { createServer, IncomingMessage, ServerResponse } from "node:http"

const text = readFileSync("a.txt", "utf8")      // string
const bytes = readFileSync("a.txt")             // Buffer

func handle(request IncomingMessage, response ServerResponse) {
    const url string = request.url              // error: url may be null (?string)
}

How TypeScript types become Rook types:

TypeScript Rook
boolean, string, number, literals, unions bool, string, number, literals, unions
T | undefined, T | null, x?: T ?T
T[], Array<T>; a tuple [A, B] T[]; (A | B)[]
void as a result a function without a result
an interface, an object type, an intersection an interface
a class a class: new, extends, instanceof
Box<T>, function first<T>(...) generics: Box<T>, inferred type arguments
overloads a call picks the first signature that fits
enum a union of literals
[key: string]: T unknown members have the type T
bigint; Uint8Array, Float64Array, ... bigint; byte[], float64[], the same types
unknown unknown
object, symbol any
conditional and mapped types TS did not reduce any

Declarations for TypeScript

rook build with type checking writes a .d.ts next to each .js, so TypeScript code imports a Rook module with types. With --no-check there are no declarations: without checking, the types are unknown.

The Vite plugin writes app.d.rk.ts next to app.rk for TypeScript imports. TypeScript uses allowArbitraryExtensions to resolve those imports.

export type Filter "all" | "active" | "done"

export func divide(a, b number) (number, error) { ... }

export class Stack<T> {
    private items T[]
    push(item T) { ... }
    pop() ?T { ... }
}
export type Filter = 'all' | 'active' | 'done'
export declare function divide(a: number, b: number): [number, Error | null]
export declare class Stack<T> {
  private items
  push(item: T): void
  pop(): T | null
}

Source maps

rook build writes a source map next to each .js, app.js.map (and app.worker.js.map for the worker module), and the .js ends with //# sourceMappingURL=app.js.map: stack traces in Node (node --enable-source-maps) and in browsers, and debuggers, show the lines of app.rk. --no-source-map writes none. rook run puts the map into the code it runs and runs it with --enable-source-maps, so the stack trace of an exception, in a goroutine too, points to the .rk file. The Vite plugin gives Vite the map of each module.

Debugging goroutines

On Node, rook run tracks pending channel operations. If the program is waiting on channels and its event loops are idle, it exits with status 1 and reports the wait sites in the .rk sources. Timers and I/O can still make progress while the check waits. With --trace an exit also prints the goroutines that remain live. Worker names come from the functions of go.

Markup

Markup and components are off by default, so that Rook can be the language of the logic of an app whose views are in React, Svelte or Vue. A package turns them on in its package.json:

{ "rook": { "markup": true } }

"markup": "html" makes markup strings of HTML and components those of a server, which return any value: see server.md.

A file takes the setting of the nearest package.json above it, and so do the language server of VS Code and the Vite plugin. rook build --markup and --no-markup set it for all files, and so does rook({ markup: true }) in Vite. Where it is off, markup, comp, dec and decorators are errors that say how to turn them on; state, ref and the like are keywords only inside a component anyway. The browser compiler takes it as an option, compile(source, null, { markup: true }).

Markup in code creates real DOM elements, with no virtual DOM:

const name = "to the home page"
const link = <a href="/" class="nav">Link {name}</a>     // HTMLAnchorElement
const link = document.createElement('a')
link.href = '/'
link.className = 'nav'
link.append('Link ', name)

Components

A component exists only at compile time: every use of it is replaced by its code.

comp Card(title string, kind string = "info", children Content) {
    return <section class={kind}>
        <h2>{title}</h2>
        {children}
    </section>
}

document.body.append(<Card title="Profile"><p>Text</p></Card>)

State. state declares a variable that the markup depends on. It is declared like let, but only at the top level of a component's body:

comp Counter(initialValue number) {
    state count = initialValue
    return <button onClick={count++}>Clicked {count} times</button>
}
let count = initialValue
const $$button3 = document.createElement('button')
$$button3.addEventListener('click', () => {
  count++
  $$text4.data = count
})
const $$text4 = document.createTextNode(count)
$$button3.append('Clicked ', $$text4, ' times')

Inside a component, {if ...}, {for ...} and {switch ...} that depend on state update too: a branch is created again only when the choice changes, and the blocks of a list are found by the array item itself and moved on changes, not created again.

State of a module. state at the top level of a module is state that its components share: the components that read it are updated when it changes anywhere in the module, in a function, a handler or a timer. Other modules import it, import { items } from "./cart.rk", and read it; changing it there is an error that says to call a function of its module. A component listens while it is on the page, so its module keeps a set of the updates of the components that read the state, $$listeners$items, and a change runs them (components.md).

Derived values. derived double = count * 2 at the top level of a component's body is a value computed from state and properties. It is read like a constant, and assigning it is an error. When what it reads changes, it is computed again, before the markup that reads it is updated:

comp Counter(initialValue number) {
    state count = initialValue
    derived double = count * 2
    return <button onClick={count++}>{count} × 2 = {double}</button>
}
let count = initialValue
let double = count * 2
// ...creating the nodes...
function $$updateCount2() {
  double = count * 2
  $$text5.data = count
  $$text6.data = double
}

A derived block. A value that takes several statements to compute is a block after the name, which ends with a return of the value. In JS the block becomes a function, called first and by the updates of what it reads:

comp Todos() {
    state todos Todo[] = []
    derived summary string {
        const done = todos.filter(todo => todo.done).length
        if done == 0 {
            return "Nothing done"
        }
        return `${done} of ${todos.length} done`
    }
    return <p>{summary}</p>
}
const $$computeSummary3 = () => {
  const done = todos.filter((todo) => todo.done).length
  if (done === 0) {
    return 'Nothing done'
  }
  return `${done} of ${todos.length} done`
}
let summary = $$computeSummary3()
// ...creating the nodes...
function $$updateTodos2() {
  summary = $$computeSummary3()
  $$text5.data = summary
}

Effects. effect { ... } at the top level of a component's body runs once the markup is created, and again after the updates whenever what it reads changes. What it reads is what its code reads while it runs: not in the functions it creates (setInterval(() => ...)) or in its defer, and not the variables it writes. It cleans up with defer: the deferred call runs before the effect runs again, and when {if}, {switch} or {for} removes the component.

comp Todos() {
    state todos string[] = load()
    // Saved again on every change of the list.
    effect {
        localStorage.setItem("todos", JSON.stringify(todos))
    }
    // ...
}

Two-way binding. bind:value={name} on <input>, <textarea> and <select> and bind:checked={done} on <input> show the variable's value and write what the user entered into it. Anything assignable can be bound: a variable or a field. The type is string, number (only for <input type="number"> and type="range") or bool for checked.

Mounting. mount { ... } at the top level of a component's body runs once its markup is on the page. What it defers with defer, as an effect does, runs when {if}, {switch}, {for} or a branch of ?: in markup removes the markup:

comp Clock() {
    state time = new Date().toLocaleTimeString()
    mount {
        const timer = setInterval(() => {
            time = new Date().toLocaleTimeString()
        }, 1000)
        defer clearInterval(timer)
    }
    return <p>It is {time}</p>
}
const $$cleanups3 = [];
$$mount(() => $$mountNode2, () => {
  const timer = setInterval(() => { ... }, 1000);
  $$cleanups3.push(() => clearInterval(timer));
}, $$cleanups3);

References. ref name at the top level of the body of a component or a decorator names an element of its markup, which ref={name} gives:

comp Search() {
    ref input
    mount {
        input.focus()
    }
    return <form class="search">
        <label for={input.id}>Find</label>
        <input id="query" ref={input} />
    </form>
}
const input = document.createElement('input')
input.id = 'query'
$$mount(
  () => $$mountNode2,
  () => {
    input.focus()
  },
)
// ...the markup fills the element in instead of creating it:
$$label3.htmlFor = input.id

Styles. style { ... } at the top level of the body of a component or a decorator is CSS for its own markup:

comp Badge(color string) {
    style {
        .badge { padding: 2px 8px; background: {color}; }
    }
    return <span class="badge">new</span>
}

CSS modules. import styles from "./button.module.css" reads the file at compile time. Its classes get names of their own, button_14zwdg2, and styles is an object of them: its type has a string field for each class, so styles.buton is a compile error, and styles[kind] with kind "primary" | "ghost" is checked too. Tags, :root and :global(...) stay global. The import becomes the object, and the module adds the CSS to the page with $$style; the file is not imported at runtime, so this works with rook build and with Vite. A class that the module never names is a warning, unless it reads styles with a key that is not known.

Web components. @html-tag before comp makes a component a custom element as well, so it works in plain HTML, in other frameworks and from JS. The tag is the component's name in kebab case, or the one given in the decorator:

@html-tag comp mainPage() { ... }               // <main-page>
@html-tag("app-card") comp Card(title string) { ... }   // <app-card>
class $$CardElement extends HTMLElement {
  static observedAttributes = ['title']
  connectedCallback() {
    /* $$Card(...) into this.shadowRoot */
  }
  disconnectedCallback() {
    /* the cleanup of mount */
  }
  attributeChangedCallback(name, old, value) {
    /* this.title = value ?? undefined */
  }
  set title(value) {
    /* updates the markup */
  }
}
customElements.define('app-card', $$CardElement)

Decorators. dec name(parameters) { ... } declares logic that is added to the components it is applied to: state, functions, mount and a wrapper around what the component returns. A decorator is applied with @name(arguments) before comp; like a component, it exists only at compile time, and its code is inlined into each component.

dec counter(start number = 0) {
    public state count = start
    let clicks = 0

    public func add() {
        count++
        clicks++
    }

    mount {
        console.log("counting from", start)
    }
}

@counter(5)
comp Clicker(label string) {
    return <button onClick={@counter.add()}>{label}: {@counter.count}</button>
}
dec notFound() {
    state missing = false

    public func show() {
        missing = true
    }

    return (page Element) => <div class="page">{missing ? <NotFoundPage /> : page}</div>
}

In JS the decorator's code goes into the component's block, with its names prefixed. A wrapper is inlined where the component returns: its markup is created first, in the variable of the parameter ($$notFound$page), then the wrapper's markup around it.

const $$counter$start = 5
let $$counter$count = $$counter$start
let $$counter$clicks = 0
function $$counter$add() {
  $$counter$count++
  $$updateCounter$count2()
  $$counter$clicks++
}

The full design, reactivity included, is in docs/components.md.

Stores and context

store Cart() { ... } in a browser module declares both the type Cart and the factory Cart(). The body declares state, derived, local variables and functions. public exposes readable fields and callable methods. export store exports the type and factory. Each factory call has its own state. Reading its reactive fields in markup, derived or effect subscribes the dependent update to that instance.

A read of @cartScope.cart resolves the closest @cartScope in the component creation chain. Read public members as @cartScope.cart. The compiler checks known trees and calls through a component value check their context at runtime. See stores and context.

Hooks

A component can reuse logic from a module-local hook useCounter(initial number) { ... }. A call takes the form const counter = useCounter(initial) at the top level of a component or another hook. Each call gets its own local bindings and takes positional arguments.

The declaration ends with a record of members, such as return { count, doubled, reset }. Each field names a local value or a member of a nested hook, and may give it another name, such as return { count: inner.value }. Reads and writes through counter.count access the underlying binding. State can be written and derived values are read-only. Use direct member access and pass individual members to functions. The compiler inlines the body at the call site and resolves the member record at compile time. Use distinct names for component bindings and module names referenced by the hook.

In the browser, arguments follow their reactive sources and each state initializer runs once. mount, effect and their defer belong to the calling component. See the component design for an example.

On the server, hooks follow the async body of the calling component. Use let and const, await for data loading, and defer for cleanup at the end of the component. See hooks on the server.

Markdown source on GitHub