# Rook Detailed documentation for the Rook language, shared memory, browser markup and server components. Each chapter can be read on its own. # Rook — 1.0 specification **English** · [Русский](ru/reference/language/index.md) Rook is a language with the semantics of JavaScript, Go-style syntax and static types. Its main feature is goroutines: `go f(x)` runs a function as a goroutine, on another processor, and channels and `select` connect goroutines, as in Go (section 5). It compiles to readable JavaScript (ES modules), and the types are erased at compile time. ## Chapters - [Compatibility in 1.x](reference/language/compatibility/index.md): Rook follows Semantic Versioning. A 1.x minor release can add backward-compatible features. A patch release can fix bugs. Changes that break the public… - [Principles](reference/language/principles/index.md): Principles. Syntax, runtime behavior and examples in the Rook technical reference. - [Lexical structure](reference/language/lexical-structure/index.md): // to the end of the line and / block /. - [Variables](reference/language/variables/index.md): A const cannot be reassigned; the compiler checks that. - [Types](reference/language/types/index.md): The type goes after the name, without a colon: x number, xs string[], cb func(number) bool, user ?User. - [Functions](reference/language/functions/index.md): Adjacent parameters of the same type can be grouped: a, b number is the same as a number, b number. - [Concurrency](reference/language/concurrency/index.md): JavaScript runs a program in one thread. Rook keeps that thread for waiting and gives the work that keeps a processor busy to other threads, with the means… - [Conditions and loops](reference/language/control-flow/index.md): No parentheses around the condition, braces are required. The condition must be a bool: unlike JS, there is no truthy/falsy. if count { is an error, write if… - [Errors](reference/language/errors/index.md): Expected errors (wrong input, a file not found) are returned as the last value, of type error: - [Classes](reference/language/classes/index.md): Classes as in JS and TypeScript, with Go-style types. Methods are declared without func, like methods of JS classes. - [Interfaces](reference/language/interfaces/index.md): An interface describes the shape of a value: its fields and methods. As in TS, it exists only at compile time. - [Modules](reference/language/modules/index.md): Imports and exports become ES modules one to one; export interface and export type disappear at compile time. - [Operators: differences from JS](reference/language/operators/index.md): The rest is as in JS: arithmetic, comparisons, bitwise operations, , ??, ?., ? :, typeof, instanceof, new, spread ..., indexing xs[i]. - [Type checking](reference/language/type-checking/index.md): The compiler checks types before generating JS; a program with type errors does not compile (rook build --no-check skips the check). - [Example](reference/language/hello-world/index.md): examples/hello.rk - [After 1.0](reference/language/future/index.md): Planned next, around goroutines and what the browser has: --- # Compatibility in 1.x Rook follows [Semantic Versioning](https://semver.org/). A 1.x minor release can add backward-compatible features. A patch release can fix bugs. Changes that break the public contract require a new major version. See the [changelog](https://github.com/QWERN-9876r/RookLang/blob/HEAD/CHANGELOG.md#upgrading-from-080) for the move from 0.8.0. - **Language.** The syntax and behavior in this specification and the [component design](https://github.com/QWERN-9876r/RookLang/blob/HEAD/docs/components.md) are stable where they describe implemented features and carry no experimental label. This includes `struct` values, [sharing structures across threads](reference/language/classes/index.md#shared-structures-in-goroutines), mutexes and `Struct` snapshots. Experimental features can change in 1.x. They include [server markup and components](reference/server/index.md), `rooklang/server` and the strict shared-access check. - **Tools.** The commands `rook build`, `rook check`, `rook run`, `rook fmt` and `rook init`, their documented options and the exit statuses for success and failure are public, except for experimental features. Diagnostic wording, formatting, debug dumps from `rook ast` and `rook tokens`, and the trace event format can evolve. - **Package.** The public APIs are the exports and TypeScript signatures of `rooklang`, `rooklang/browser`, `rooklang/vite`, `rooklang/bun` and `rooklang/bun/register`, except for options specific to experimental features. `RookError` and `Struct` are public exports of `rooklang/runtime`. The helpers prefixed with `$$` and the entry point `rooklang/runtime/flatbuffers` are compiler implementation details. - **Build output.** Keep the compiler and runtime on the same package version and rebuild all Rook modules, including generated workers and declarations, when upgrading. The emitted JavaScript, generated `.fbs` schemas, the layout of shared memory and the worker protocol are implementation details and can change between releases. --- # Principles 1. **JS semantics.** The same values, objects, classes, closures, modules and standard library (`console`, `Math`, `JSON`, methods of arrays and strings). 2. **Go syntax where it is more convenient:** `func`, the type after the name, multiple results, `defer`, zero values, conditions without parentheses, a single `for` loop, `switch` without `break`, no semicolons. 3. **Concurrency as in Go.** `go f(x)` runs a function as a goroutine, on another processor, and channels and `select` pass values between goroutines. The compiler checks that what goes between threads can be copied. 4. **Static types with null safety.** The compiler finds type errors; `null` can only be assigned to a type that explicitly allows it. JS code has no types. 5. **Compatibility with JS.** Rook can import any JS module, and a compiled module can be used from JS. --- # Lexical structure ### Comments `// to the end of the line` and `/* block */`. The compiler copies code comments to JavaScript near the statements they describe. Comments inside expressions or attached to erased declarations may move to a nearby generated line. File headers also appear in worker modules, along with comments on the declarations they copy. ### Semicolons They are written only to separate several statements on one line. Otherwise the lexer inserts them by Go's rule: at the end of a line if its last token is - an identifier or a literal (a number, a string, `true`, `false`, `null`); - `this`, `return`, `break` or `continue`; - `++`, `--`, `)`, `]`, `}`. Hence, as in Go: - the opening `{` is on the same line as `if`, `for`, `func`, `class`; - when a long expression is split, the binary operator stays at the end of the line; - no semicolon is needed before `}`: `if ok { return x }`. **Unlike Go**, no semicolon is inserted if the next line starts - with `.` or `?.`, so the familiar chains of calls work; - with `?` or `:`, so a conditional expression can be split before its operators; - with a closing `)`, `]` or `}`, so a comma after the last item of a multi-line list is optional. A line may end with `>` too: after the type arguments of a declaration, `votes Map`, the line break ends it, while `a >` with a value on the next line goes on, as other operators do. A line that ends with `x!` (see "null and null safety") ends there too. ```go const names = users .filter(u => u.active) .map(u => u.name) const point = { x: 1, y: 2 } const label = count == 0 ? "empty" : `${count} items` ``` ### Literals - Numbers as in JS: `42`, `3.14`, `1e3`, `0xff`, `1_000_000`; a bigint ends with `n`: `10n`, `0xffn`. - Strings: `"..."`, `'...'` and template strings `` `Hello, ${name}` ``. - `true`, `false`, `null`. - Regular expressions as in JS: `/ab+c/gi`, a `RegExp`. Where a value cannot end, `/` starts one, and after a value it divides: `a / b / c`. The compiler checks the pattern and the flags, as JS does when the module loads, so `/(/` is a compile error. - Arrays `[1, 2, ...rest]` and objects `{ name: "Ann", age, "content-type": t, ...defaults }` (the shorthand `age` and spread are as in JS). A method is written in an object as in a class, `{ fetch(req Request) Response { ... } }`, with the types of a `func` literal, and is a method in JS. Its `this` would be the object, not the class around it, so it cannot be used there. - A tagged template, `` sql`select * from users where id = ${id}` ``, calls the function before it with the strings, a `TemplateStringsArray`, and the values, as in JS: the values are checked as the arguments after the strings, `func sql(parts TemplateStringsArray, ...values any[])`. The tag is on the same line as the template. ### Keywords ``` func comp return let const interface class extends new this super if else for in break continue switch case default defer try catch finally throw import export async await go chan null true false typeof instanceof ``` Inside a class declaration `static`, `private`, `protected`, `public`, `readonly`, `abstract` and `implements` are keywords too, and so are `get` and `set` before the name of a method; at the start of a statement before a name `type` declares a type, `type Id string`, and elsewhere it is a name, `const type = blob.type`; before `class` so are `data` and `abstract`, in `import` and `export` so is `from`, at the start of a statement in a component's body `state`, `derived`, `ref`, `style`, `mount` and `effect`, at the start of a top-level declaration `dec`, after its parameters `needs` and `includes`, in a decorator's body `public`, before `{` at the start of a statement `select`, and `queue` in a type before the type of its values and before the `<` that makes a queue. Elsewhere they are ordinary names. Decorators are written before `comp`: `@html-tag` (see "Web components") and those declared with `dec` (see "Decorators"). After `.` and in object keys, keywords can be used as ordinary names: `xs.map(f)`, `event.type`, `{ default: 1 }`. Predeclared identifiers (not keywords, they can be redeclared): the types `number`, `string`, `bool`, `any`, `error`, `void`, `never` and the functions `error()`, `close()` (of channels) and the others of goroutines and channels: `transfer()`, `after()`, `tick()`, `cancel()` and `stream()`. Names that start with `$$` are reserved for generated code (`$$defer`, `$$0`). Names that are valid in Rook but not in JS (`delete`, `static`, `function`…) get a `$` suffix in the output: `delete` → `delete$`. --- # Variables ```go let count = 0 // the type is inferred: number let name string = "Ann" let total number // the zero value: 0 const PI = 3.14 let a, b = 1, 2 ``` ```js let count = 0 let name = 'Ann' let total = 0 const PI = 3.14 let a = 1, b = 2 ``` A `const` cannot be reassigned; the compiler checks that. Multiple assignment, as in Go: ```go a, b = b, a // → [a, b] = [b, a]; ``` The fields of an object go into variables as in JS, one level deep, in `const` and `let`: ```go const { name, size: bytes, ...rest } = file // rest has the other fields const { "content-type": mime } = headers ``` Each variable has the type of its field, and a field that the object does not have is an error. A method is not taken: without its object it would lose `this`. Arrays are unpacked with several values instead, `const first, second = pair()`. ### Zero values A variable or a class field without an initial value gets the zero value of its type, as in Go: | Type | Zero value | | --------------------------- | -------------------------------------- | | `number` | `0` | | `bigint` | `0n` | | `string` | `""` | | `bool` | `false` | | `T[]` | `[]` (a new array each time) | | `byte[]`, `float64[]`, ... | an empty typed array | | `queue T` | an empty queue (a new one) | | `chan T`, `topic T` | `Channel.EMPTY`, `Topic.EMPTY`: closed | | `?T`, `error`, `any` | `null` | | classes, interfaces, `func` | none: the value must be given | ```go let u User // error: User has no zero value let u ?User // fine: u == null ``` ### A variable in its own initializer A variable exists from the start of its declaration, as in JS. A function in its initializer runs after the initializer, so it can use the variable: ```go const timer = setInterval(() => { if done() { clearInterval(timer) } }, 1000) const fact = func(n number) number { return n <= 1 ? 1 : n * fact(n - 1) } ``` The same holds for event handlers in markup: `const close =