Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

Restrict is a WebAssembly-oriented programming language built around object-subject-verb calls, affine ownership, and explicit release boundaries. The current documentation distinguishes the v0.0.1 release surface—what is implemented and intended for public use—from what is intentionally rejected or remains reserved design space.

What Restrict Is Today

Restrict is a statically checked language that compiles source programs to WebAssembly text and binary output. Its current stable-facing shape is compact:

  • OSV-only calls such as value |> function, (left, right) combine, and () start
  • immutable val bindings and mutable mut val bindings
  • affine ownership for heap-backed values and function values
  • built-in List, Array, Option, Result, and Range<Int32> support
  • record declarations and record values inside Restrict programs
  • closed, non-generic, non-recursive user enums with qualified variants and exhaustive matching
  • method-only forms, concrete record adoptions, and statically resolved of bounds
  • Display-polymorphic display, print, and println
  • scalar monomorphic WebAssembly exports for the host boundary

Some keywords and design documents describe future work. Temporal Affine Types, generic or recursive forms and user enums, associated types, default form methods, conditional or generic adoptions, dynamic dispatch, and exported generic or composite host ABIs remain outside the current compiler surface. User enums may be used inside Result<T, CustomError>, but the ? propagation operator is not implemented yet.

WebAssembly is the only Restrict code-generation target. Native WASI runtimes, browsers, cloud/edge platforms, and container runtimes are different hosts for that output, not separate JavaScript or native language backends. A host may currently require generated JavaScript glue, but Restrict application logic still compiles to Wasm. The WebAssembly Integration page separates the current executable surface from planned WASI, Component Model, Web, and edge adapters.

Why OSV

Restrict calls keep the data first and the operation last. This makes pipeline shape visible without switching back to function-first syntax:

fun add_bonus: (score: Int32, bonus: Int32) -> Int32 = {
    score + bonus
}

fun clamp_score: (score: Int32) -> Int32 = {
    score > 100 then {
        100
    } else {
        score
    }
}

fun main: () -> Int32 = {
    (96, 7) add_bonus |> clamp_score
}

Traditional calls such as add_bonus(96, 7) are not Restrict syntax. The compiler keeps that rule strict so examples, diagnostics, and generated code all use the same word order.

Ownership Model

Restrict uses affine ownership: a binding may be used at most once unless the value is copyable or the binding is explicitly mutable. This keeps ownership visible in source code and makes deterministic WebAssembly lowering easier.

fun choose_label: (passing: Boolean) -> String = {
    passing then {
        "ready"
    } else {
        "blocked"
    }
}

fun main: () -> String = {
    val passing = true;
    passing |> choose_label
}

Copyable primitives such as Int32, Int64, Float64, Boolean, Char, and () may be reused. Strings, lists, records, and function values follow the affine path unless the compiler has an explicit copy rule for the operation.

WebAssembly Boundary

Restrict programs can compute with composite values internally, but the v0.0.1 host ABI is intentionally narrow. Public host-visible functions should be monomorphic and scalar:

export fun exported_score: () -> Int32 = {
    42
}

The executable source entry point is zero-argument main. During code generation, main: () -> ... is called by a host _start wrapper. If main returns a value, the wrapper drops it for program-style execution; expose host-callable scalar results through a separate pub fun or export fun.

Documentation Map

Start with the Quick Start, then read the Language Guide. The Type Inference page explains the current bidirectional inference surface, and the v0.0.1 Release Surface page records the public boundary used by tests and examples.

The GitHub Pages site also hosts the online compiler at ../compiler/ from the site root. Code blocks in this book that define fun main can be opened in that browser compiler through the “Try in Playground” button.

Installation

The v0.0.1 release is distributed through GitHub Releases and can also be built from source. The package registry, stable Homebrew formula, and VS Code Marketplace channel remain outside this release.

Install the Release Binary

The shell installer supports x86-64 Linux plus Intel and Apple Silicon macOS. It downloads both the compiler and Warder, then verifies the archive against the release SHA-256 manifest.

curl --proto '=https' --tlsv1.2 -fsSL \
  https://raw.githubusercontent.com/Ischca/restrict_lang/main/install.sh | bash

Add the reported $HOME/.restrict-lang/bin directory to PATH. Windows users can download and verify the zip archive from the GitHub release.

Requirements

  • Rust toolchain
  • Git
  • mise for the repository toolchain
  • Wasmtime or Wasmer when using warder run

Build From Source

Clone the repository:

git clone https://github.com/Ischca/restrict_lang.git
cd restrict_lang

Build the compiler and Warder from the workspace:

mise exec -- cargo build --release

The workspace build writes binaries under:

target/release/

Add the workspace release directory to your shell PATH:

export PATH="$PWD/target/release:$PATH"

The Cargo workspace uses the root target directory for both binaries.

Verify Installation

restrict_lang --version
warder --version
warder doctor

warder doctor reports whether the compiler is visible and whether a WASM runtime is available.

WASM Runtime

warder run executes the generated .wasm through Wasmtime first, then Wasmer when Wasmtime is not available.

Install one runtime using its upstream instructions, then verify it is on your PATH:

wasmtime --version
# or
wasmer --version

Project Commands

Create and build a project:

warder new hello-world
cd hello-world
warder build
warder run
warder test

The default build outputs are:

dist/hello-world-0.1.0.wat
dist/hello-world-0.1.0.wasm
dist/hello-world-0.1.0.rgc

The output stem is <package-name>-<package-version> from the repository-root warder.toml.

Language Server

The compiler can start the language server over stdio:

restrict_lang --lsp

Configure editors that support LSP to start that command as a stdio language server.

Troubleshooting

Command not found

Check that the release binary directory from your source build is on PATH. For workspace builds this is target/release.

Warder cannot find the compiler

Set RESTRICT_LANG_BIN or add the compiler binary directory to PATH:

export RESTRICT_LANG_BIN="$PWD/target/release/restrict_lang"

Program does not run

Install Wasmtime or Wasmer, then rerun:

warder doctor
warder run

Next Steps

Quick Start Guide

This guide uses the v0.0.1 Warder CLI surface: new, init, add, remove, build, run, test, publish, wrap, unwrap, and doctor.

Verify Tools

After installing or building from source, check that both binaries are on your PATH:

restrict_lang --version
warder --version

When using a local workspace build, both binaries are under target/release.

Create A Project

warder new hello-world
cd hello-world

This creates:

hello-world/
├── warder.toml
├── src/
│   └── main.rl
├── tests/
│   └── main_test.rl
├── README.md
└── .gitignore

The generated src/main.rl uses current Restrict syntax:

fun main: () -> () = {
    "Hello, World!" |> println
}

Check The Repository Configuration

The root warder.toml is the repository’s only authored Warder configuration. It controls the entry point, dependency table, and build output:

[package]
name = "hello-world"
version = "0.1.0"
description = "A first Restrict package"
authors = ["Your Name <you@example.com>"]
entry = "src/main.rl"
edition = "2025"

[dependencies]

[build]
target = "wasm32"
optimize = true
output = "dist/"

Build And Run

warder build
warder run
warder test

The default build writes:

dist/hello-world-0.1.0.wat
dist/hello-world-0.1.0.wasm
dist/hello-world-0.1.0.rgc

warder run builds first, then runs the generated .wasm with Wasmtime or Wasmer when one is installed. warder test compiles and executes public zero-argument Boolean functions under tests/; v0.0.1 does not add a separate test declaration syntax.

Add A Small Pipeline

Replace src/main.rl with:

fun add_bonus: (base: Int32, bonus: Int32) -> Int32 = {
    base + bonus
}

fun main: () -> () = {
    val total = (21, 4) add_bonus;
    total |> print_int
}

Run it:

warder run

Host networking and file or stream I/O are outside the v0.0.1 quick-start runnable path. Keep quick-start programs limited to the compiler-registered surface such as println and print_int.

Dependencies

warder add local_utils --path ../local-utils
warder remove local_utils

The dependency directory needs only src/lib.rl; it has no leaf Warder configuration or lock. The alias local_utils is also its source namespace, so an exported score function from the library root is imported with:

import local_utils.{score}

Submodules follow the same mapping: import local_utils.numbers.{double} loads ../local-utils/src/numbers.rl. Aliases must be non-keyword Restrict identifiers, std is reserved, and hyphens are not converted automatically.

warder build generates one repository-root warder.lock. It records only nondeterministic external dependency resolutions, not direct local source packages. Registry, Git, foreign WASM, and transitive resolution fail explicitly in the current slice, so a local-only lock has no resolved package entries. warder test uses the same local package roots.

The current implementation has one publishable root package. A future multi-publish workspace graph will extend the same root warder.toml without leaf manifests; public package identity will not be inferred from directory placement.

Builds compile immutable application and dependency snapshots. Concurrent builds of one project are serialized, and the generated WAT, WASM, Cage, and lock file replace the previous set only after the full build succeeds.

Local Cage Files

warder build creates a local cage file at dist/<name>-<version>.rgc; there is no separate packaging subcommand.

For external WASM files:

warder wrap module.wasm --name module-name --version 0.1.0
warder unwrap module-name-0.1.0.rgc

Foreign WASM wrapping is experimental in v0.0.1 and is intended for local evaluation.

Diagnostics

warder doctor

warder doctor checks the root configuration, entry source path, root lock integrity when present, required compiler, and available WASM runtime.

Next Steps

Hello World

This tutorial builds a small Restrict program with the current v0.0.1 surface: Warder project creation, OSV calls, scalar output, a smoke-test file, and one record-based extension.

Create A Project

warder new hello-world
cd hello-world

Warder creates a project like this:

hello-world/
├── warder.toml
├── src/
│   └── main.rl
├── tests/
│   └── main_test.rl
└── README.md

Open src/main.rl.

Write The First Program

Use fun for functions and val for immutable bindings:

fun main: () -> () = {
    "Hello, World!" |> println
}

The important pieces are:

  • fun main: () -> () = { ... } defines the source entry point.
  • "Hello, World!" is a String value.
  • |> is the single-argument OSV pipe.
  • println consumes the string and prints a line.

Function-first calls are not Restrict syntax. Write "Hello" |> println, not println("Hello").

Build And Run

Build the project:

warder build

The default output goes under dist/:

dist/hello-world-0.1.0.wat
dist/hello-world-0.1.0.wasm
dist/hello-world-0.1.0.rgc

Run it:

warder run

You should see:

Hello, World!

warder run requires Wasmtime or Wasmer on your PATH. If it cannot find a runtime, run:

warder doctor

Add A Function

Replace src/main.rl with a scalar pipeline:

fun add_bonus: (base: Int32, bonus: Int32) -> Int32 = {
    base + bonus
}

fun main: () -> () = {
    val total = (21, 4) add_bonus;
    total |> print_int
}

Multiple arguments use grouped OSV syntax: (21, 4) add_bonus.

Run again:

warder run

Add A Smoke Test

Warder test files use ordinary Restrict functions. Edit tests/main_test.rl:

import project.main.{add_bonus}

pub fun test_add_bonus: () -> Boolean = {
    (21, 4) add_bonus == 25
}

Run:

warder test

Warder compiles this public, zero-argument Boolean function to Core Wasm and executes it. A true result passes and false fails. There is no separate test "name" { ... } declaration syntax.

Add A Record

Records use : in both declarations and literals:

record Score {
    base: Int32,
    bonus: Int32
}

fun total_score: (score: Score) -> Int32 = {
    val Score { base, bonus } = score;
    base + bonus
}

fun main: () -> () = {
    val score = Score { base: 21, bonus: 4 }
    val total = score |> total_score;
    total |> print_int
}

Destructuring the record once is the clearest way to use multiple fields under affine ownership.

Try Type Inference

Local bindings and local return types can often be inferred:

fun double: (value: Int32) = {
    value * 2
}

fun main: () -> () = {
    val total = 21 |> double;
    total |> print_int
}

Keep public or exported host-visible functions explicit when the boundary matters.

Common Mistakes

Use current syntax:

val value = 42
mut val counter = 0
value |> function
(left, right) combine
RecordName { field: value }

Avoid removed or unsupported forms:

let value = 42
val mut counter = 0
function(value)
RecordName { field = value }

What Is Outside This Tutorial

The first runnable path avoids APIs that are not part of the v0.0.1 compiler-registered standard-library surface:

  • stdin and interactive prompts
  • file-system and network I/O
  • direct host ABI for strings, records, lists, Option, or Result
  • Temporal Affine Types
  • generic or recursive user enums and direct host enum ABI

The v0.0.1 compiler does support closed, non-generic, non-recursive enums inside Restrict programs. See Types and Pattern Matching after completing this first path.

Use the Quick Start for a shorter command reference, then continue with OSV Word Order, Type Inference, and WebAssembly Integration.

Language Guide Overview

Welcome to the Restrict Language guide. These pages describe the current v0.0.1 release-facing syntax, including its closed enum and static form slices, and mark future boundaries where they matter.

What You’ll Learn

Quick Example

record ReleaseSignal {
    score: Int32,
    passing: Boolean
}

fun summarize_release: (signal: ReleaseSignal) -> String = {
    signal match {
        ReleaseSignal { passing: true, score } => {
            "ready"
        }
        ReleaseSignal { passing: false, ..._ } => {
            "blocked"
        }
    }
}

fun main: () -> String = {
    val signal = ReleaseSignal { score: 92, passing: true };
    signal |> summarize_release
}

Key Concepts

OSV Syntax

Restrict uses Object-Subject-Verb call order. Arguments come first: value |> function, (left, right) function, and () function.

Affine Types

Heap-backed values such as strings, lists, records, and function values are affine by default. Copyable primitives such as Int32, Boolean, Float64, Char, and () can be reused.

Type-Directed Impl Functions

impl blocks define functions selected by the receiver type, but calls remain OSV. Use (receiver, args...) function_name, not object-style method calls.

Static Forms

Method-only forms express reusable requirements. Concrete records adopt a form with takes, and generic functions list bounds with <T of Form>. The compiler selects and monomorphizes every method call without runtime form objects.

Pattern Matching

match is also OSV: the value being matched appears before the match keyword, and each branch body is wrapped in braces. Closed user enums use qualified Type::Variant patterns and must be matched exhaustively.

Zero GC

Restrict targets deterministic memory management through compile-time checks and WASM-friendly data layouts.

OSV Word Order

Restrict Language uses Object-Subject-Verb (OSV) word order for calls. The value being transformed comes first, then the function that receives it. This keeps data flow visible and avoids function-first call syntax.

Supported Call Forms

value |> function
(left, right) combine
() make_default

Function-first calls are not part of the v0.0.1 surface.

Pipe Operator

The pipe operator passes the value on the left as the first argument to the function on the right.

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun main: () -> Int32 = {
    21 |> double
}

Pipelines read left to right:

fun score: (value: Int32) -> Int32 = {
    value + 1
}

fun main: () -> Int32 = {
    41
        |> score
        |> double
}

Multiple Arguments

Functions with multiple arguments use a tuple before the function name.

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

fun main: () -> Int32 = {
    (10, 32) add
}

The same rule applies inside larger expressions:

fun clamp_min: (value: Int32, minimum: Int32) -> Int32 = {
    value < minimum then {
        minimum
    } else {
        value
    }
}

fun main: () -> Int32 = {
    val raw = 7
    (raw, 10) clamp_min
}

Scoped Verb Clauses

A higher-order verb can open its final function argument as a typed scope. The ordinary object stays before the verb, while the complete clause becomes the object of the next verb.

fun main: () -> Int32 = {
    val numbers: List<Int32> = [1, 2, 3, 4]
    val doubled = numbers map {
        it * 2
    } filter {
        it > 2
    }
    (doubled, 0) fold { |total, number|
        total + number
    }
}

An unheaded scope receives one contextual it binding. Use the existing lambda binder syntax in the scope header when a name is clearer or the callback has multiple parameters:

values map { |value|
    value + 1
}

The compiler checks these scopes exactly like ordinary lambdas. Nested implicit it scopes are rejected; name at least one binder so ownership and capture intent remain visible.

Pattern Matching

match keeps the matched value first.

fun score_or_zero: (score: Option<Int32>) -> Int32 = {
    score match {
        Some(value) => { value }
        None => { 0 }
    }
}

Impl Functions

impl blocks define functions that are selected by the receiver type. They do not introduce object-style method calls; the call still places the receiver in the argument position.

record Score {
    value: Int32
}

record Penalty {
    value: Int32
}

impl Score {
    fun amount: (self: Score) -> Int32 = {
        self.value
    }
}

impl Penalty {
    fun amount: (self: Penalty) -> Int32 = {
        0 - self.value
    }
}

fun main: () -> Int32 = {
    val score = Score { value: 11 }
    (score) amount
}

When the same function name exists for multiple record types, the receiver type chooses the implementation.

Record Values

Record literals use : field initializers, and field access is separate from function calls.

record Point {
    x: Int32,
    y: Int32
}

fun sum_point: (point: Point) -> Int32 = {
    point.x + point.y
}

fun main: () -> Int32 = {
    val point = Point { x: 10, y: 20 };
    point |> sum_point
}

Best Practices

  1. Keep pipelines short enough to scan.
  2. Name functions by the transformation they perform.
  3. Put side-effecting functions at the end of a pipeline.
  4. Use val for intermediate names when it makes ownership transfer clearer.

Summary

OSV makes ownership and data flow explicit: values move from left to right, multi-argument calls use tuples, and impl functions are still called through OSV syntax.

For the complete callback model and the current map, filter, and fold surface, continue to Higher-Order Functions and Collection Transforms.

Syntax Reference

This page summarizes the v0.0.1 syntax surface. The authoritative source is LANGUAGE_SPECIFICATION.md; this guide keeps examples practical and release oriented while identifying features that remain outside the release.

Temporal Affine Types are experimental and outside the default v0.0.1 gate. The v0.0.1 compiler supports the closed user enum slice described below.

Comments

// Single-line comment

/*
   Multi-line comment
*/

Literals

Literal forms follow the language specification. Use () for Unit values and the Unit type; Unit is not a supported type name.

val decimal: Int32 = 42
val hex: Int32 = 0xFF
val grouped: Int32 = 1_000_000

val ratio: Float64 = 3.14
val exponent: Float64 = 1.5e10
val negative_exponent: Float64 = 3.14E-2

val message: String = "ready\nnext"
val quote: String = "say \"ready\""
val mark: Char = 'a'
val newline: Char = '\n'

val enabled: Boolean = true
val disabled: Boolean = false
val done: () = ()

Bindings

Use val for immutable bindings:

val score = 42
val label: String = "ready"
val reading: Float64 = 21.5

Mutable bindings use mut val, with mut before val:

mut val counter = 0;
counter = counter + 1

Patterns can bind structured values:

record Point {
    x: Int32,
    y: Int32
}

fun sum_point: (point: Point) -> Int32 = {
    val Point { x, y } = point;
    x + y
}

Expression Boundaries

Line breaks are whitespace, so a direct OSV expression may continue on the next line. Values that cannot act as verbs naturally begin a new expression:

"first" println
"second" println

Use ; when a local binding is followed by an identifier-started expression that must not become another verb in the binding value:

val message = "ready";
message println

For a name used only inside a higher-order transformation, a scoped verb clause usually keeps the flow clearer and semicolon-free:

values map { |value|
    value + 1
}

Functions

Functions use fun name: (...) -> Type = { ... }.

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

fun identity: <T>(value: T) -> T = {
    value
}

fun main: () -> Int32 = {
    (20, 22) add
}

Return types can be inferred for local functions when the body is clear:

fun double: (value: Int32) = {
    value * 2
}

Public Declarations

Use pub to expose a supported top-level declaration from a source module:

pub fun public_score: (value: Int32) -> Int32 = {
    value + 1
}

pub val release_bias: Int32 = 3
pub val no_payload: () = ()

pub enum exposes an enum type namespace to other Restrict source modules. It does not create a host-visible WebAssembly enum export.

For v0.0.1, top-level constants are limited to literal Int32, Int64, Float64, Boolean, Char, and () values. Exported String, records, lists, Option, Result, and user enum values require a composite host ABI or runtime allocation and are rejected by release-surface validation; create them inside functions instead.

OSV Calls

Restrict uses object-subject-verb call order. Arguments come before the function.

42 |> double
(10, 20) add
() make_default

Function-first calls such as add(10, 20) are not supported.

Lambdas

Lambda parameters are inferred from the expected function type:

fun apply_int: (f: Int32 -> Int32, value: Int32) -> Int32 = {
    value |> f
}

fun main: () -> Int32 = {
    (|x| x + 1, 41) apply_int
}

Standalone lambdas can provide parameter context with annotations:

fun main: () -> Int32 = {
    val bump = |value: Int32| value + 1
    41 |> bump
}

Scoped Verb Clauses

A callable whose final remaining parameter is a function can open that function as a scope:

val shifted = values map {
    it + 1
}

val total = (shifted, 0) fold { |sum, value|
    sum + value
}

The unheaded form introduces one contextual it binding. Explicit scope headers reuse lambda binders. A complete scoped clause is evaluated before a following clause or pipe.

See Higher-Order Functions and Collection Transforms for callback forms, collection behavior, inference, and affine captures.

Expressions

Supported operators include arithmetic, comparison, equality, and boolean operators:

val total = 1 + 2 * 3
val ready = total >= 7 && total != 0
val inverted = !ready

Conditionals use then:

score >= 80 then {
    "pass"
} else {
    "retry"
}

Pattern matching follows the value:

maybe_score match {
    Some(score) => { score }
    None => { 0 }
}

Records

Record declarations and literals use : for fields:

record Reading {
    celsius: Float64,
    ok: Boolean
}

fun main: () -> Float64 = {
    val reading = Reading { celsius: 21.5, ok: true };
    reading.celsius
}

Record updates use .clone { ... }:

fun mark_ok: (reading: Reading) -> Reading = {
    reading.clone { ok: true }
}

freeze is available for prototype-style immutable copies:

fun frozen_reading: (reading: Reading) -> Reading = {
    reading freeze
}

User-Defined Enums

The v0.0.1 slice supports closed, non-generic, non-recursive enums. Each variant has either no payload or one payload:

pub enum ParseError {
    Empty
    Message(String)
}

Constructors are qualified direct OSV call targets. Pass () to a payload-free variant and pipe the declared payload into a payload variant:

val empty = () ParseError::Empty
val invalid = "invalid input" |> ParseError::Message

Patterns are qualified too, and a match must cover every variant:

fun error_code: (error: ParseError) -> Int32 = {
    error match {
        ParseError::Empty => { 1 }
        ParseError::Message(message) => { 2 }
    }
}

Generic and recursive user enums, variants with more than one direct payload, first-class constructors, and a host enum ABI remain outside this slice.

Lists, Option, And Result

fun count_scores: () -> Int32 = {
    val numbers: List<Int32> = [1, 2, 3];
    val maybe_score: Option<Int32> = 42 Option::Some;
    val no_score: Option<Int32> = () Option::None;
    val success: Result<Int32, String> = 42 Result::Ok;
    val failure: Result<Int32, String> = "invalid" Result::Err;
    numbers |> list_count
}

Empty [] and () Option::None need context from an annotation, expected return type, or neighboring generic argument.

The example above uses local bindings. In v0.0.1, list, Option, and Result literals are not supported as top-level constants.

Context Blocks

Context declarations define available fields, and with Context { ... } { ... } binds values for a body:

context Policy {
    minimum_score: Int32
}

fun main: () -> Int32 = {
    with Policy { minimum_score: 80 } {
        minimum_score
    }
}

Imports

Imports use dotted source-module paths. Named and wildcard imports are current v0.0.1 syntax; string paths and aliases are reserved for a later module-design pass.

import release.policy.{score}
import release.policy.*

Precedence

The practical precedence order is:

  1. Qualified variant names such as ParseError::Message, field access, clone/freeze postfix forms, grouped OSV calls, and scoped verb clauses
  2. Unary - and !
  3. *, /, %
  4. +, -
  5. <, <=, >, >=
  6. ==, !=
  7. &&
  8. ||
  9. OSV calls and pipes
  10. Assignment in mutable bindings

Prefer parentheses when combining OSV calls with arithmetic or nested function values.

Type System

Restrict combines static typing, affine ownership, local type inference, and WASM-friendly data layouts. This page distinguishes the supported v0.0.1 type surface from future design space. TAT is experimental and excluded from the default release gate.

Built-In Types

The current primitive types are:

  • Int32
  • Int64
  • Float64
  • Boolean
  • Char
  • String
  • () for unit
val count: Int32 = 42
val large: Int64 = 9_000_000_000
val ratio: Float64 = 0.75
val ready: Boolean = true
val marker: Char = 'A'
val label: String = "release"
val unit: () = ()

Int32, Boolean, Float64, Char, and () are copyable. String, records, collections, function values, and other heap-backed values follow affine ownership.

Affine Ownership

Affine values may be used at most once unless they are copyable or mutable.

fun consume: (message: String) -> Int32 = {
    1
}

fun main: () -> Int32 = {
    val message = "hello";
    message |> consume
}

Copyable primitives can be used repeatedly:

fun main: () -> Int32 = {
    val score = 40;
    score + score
}

Mutable bindings are declared with mut val:

fun main: () -> Int32 = {
    mut val counter = 0;
    counter = counter + 1;
    counter
}

Function Types

Function types use ->. Multi-parameter function types use parentheses.

Int32 -> Int32
(Int32, Float64) -> Boolean
Int32 -> ()
() -> ()

Values of function type can be passed through OSV calls:

fun apply_int: (f: Int32 -> Int32, value: Int32) -> Int32 = {
    value |> f
}

fun main: () -> Int32 = {
    (|x| x + 1, 41) apply_int
}

Unit-returning function values also use explicit expected function types:

fun record_event: (code: Int32) -> () = {
    ()
}

fun run_event: (handler: Int32 -> (), code: Int32) -> () = {
    code |> handler
}

fun main: () -> () = {
    (record_event, 7) run_event
}

Generic and Built-In Collection Types

The built-in generic and collection type forms are:

List<T>
Array<T, N>
Option<T>
Result<T, E>
Range<Int32>

Common examples:

val numbers: List<Int32> = [1, 2, 3]
val fixed: Array<Int32, 3> = [1, 2, 3]
val indexes: Range<Int32> = [1..10]
val maybe_score: Option<Int32> = 42 Option::Some
val no_score: Option<Int32> = () Option::None
val success: Result<Int32, String> = 42 Result::Ok
val failure: Result<Int32, String> = "missing" Result::Err

Collection literals use [ ... ] for both lists and fixed arrays. Without an expected type, [1, 2, 3] is a List<Int32>. In an expected Array<T, N> context, the same literal is checked as an array and its length must match N. The old bracket-bar array literal syntax is not supported.

Range literals use [start..end] and currently support Range<Int32> only. The literal stores the two endpoints; iteration behavior and non-Int32 endpoint types are intentionally not part of the v0.0.1 surface yet.

These built-ins are part of the v0.0.1 support surface. They do not imply that user-defined generic ADTs or exported generic ABIs are complete.

Empty collection literals need context:

fun main: () -> List<Int32> = {
    val values: List<Int32> = [];
    values
}

The empty literal [] is intentionally ambiguous without an expected List<T> or Array<T, N> type. A sibling element, branch, argument, or return context can supply that type; otherwise add an annotation.

Generic Functions

Generic functions use type parameters before the parameter list.

fun identity: <T>(value: T) -> T = {
    value
}

fun choose_first: <T>(value: T, fallback: T) -> T = {
    value
}

fun main: () -> Int32 = {
    (42, 0) choose_first
}

Generic function values need an expected function type. This keeps inference local and avoids hidden global guessing:

fun main: () -> List<Int32> = {
    val numbers: List<Int32> = [1, 2, 3]
    (numbers, identity) map
}

Records

Records group named fields. Field declarations and literals use :.

record Reading {
    celsius: Float64,
    threshold: Float64
}

fun above_threshold: (reading: Reading) -> Boolean = {
    reading.celsius > reading.threshold
}

Record values are affine. Use destructuring when multiple fields are needed:

fun delta: (reading: Reading) -> Float64 = {
    val Reading { celsius, threshold } = reading;
    celsius - threshold
}

Record updates use .clone { ... }:

fun lower_threshold: (reading: Reading) -> Reading = {
    reading.clone { threshold: 18.0 }
}

Generic records are supported inside Restrict programs:

record Box<T> {
    value: T
}

fun unwrap: <T>(box: Box<T>) -> T = {
    box.value
}

fun main: () -> Int32 = {
    Box { value: 1 } |> unwrap
}

Generic record literals infer their type arguments from fields, expected parameter types, or explicit annotations. Exporting records across the WebAssembly host ABI is still outside the v0.0.1 release surface. Exported records are source-level module metadata only and do not emit direct host-visible Wasm exports.

Forms And Static Polymorphism

The v0.0.1 compiler supports non-generic, method-only forms. Generic functions can require one or more forms with of; the compiler checks each concrete call and monomorphizes it to a direct adoption method call.

pub form Labelled {
    fun label: (self: Self) -> String
}

record Badge {
    text: String
}

Badge takes Labelled {
    fun label: (self: Badge) -> String = {
        self.text
    }
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}

Multiple bounds use +, as in <T of Labelled + Comparable>. Form methods must have complete parameter and return types. An adoption targets one concrete, non-generic record and supplies every method body. pub form is importable by other Restrict source modules; a takes declaration itself is not public.

Because self is an ordinary affine parameter, calling a form method consumes a non-Copy receiver unless the method returns a replacement value. This initial slice has no associated types, generic forms, default method bodies, conditional or generic adoptions, enum adoptions, or dynamic dispatch. See Forms and Static Polymorphism for the complete boundary.

Option And Result

Option and Result are built-in generic sum types with constructor and pattern syntax.

fun score_or_zero: (score: Option<Int32>) -> Int32 = {
    score match {
        Some(value) => { value }
        None => { 0 }
    }
}

fun result_or_zero: (score: Result<Int32, String>) -> Int32 = {
    score match {
        Ok(value) => { value }
        Err(message) => { 0 }
    }
}

The qualified constructors value Option::Some, value Result::Ok, and error Result::Err carry payload types, but Result::Ok and Result::Err still need the full expected Result<T, E> shape to fill the opposite side. Option::None carries no payload, so it needs an expected Option<T> unless a sibling Some or branch supplies the type.

fun choose_result: (flag: Boolean) -> Result<Int32, String> = {
    flag then {
        42 Result::Ok
    } else {
        "missing" Result::Err
    }
}

fun choose_option: (flag: Boolean) -> Option<Int32> = {
    flag then {
        () Option::None
    } else {
        42 Option::Some
    }
}

User-Defined Enums

The v0.0.1 compiler supports closed, non-generic, non-recursive user enums. Each variant has zero or one payload and is named through its enum namespace:

enum DecodeError {
    Empty
    Invalid(String)
}

fun fail: (message: String) -> Result<Int32, DecodeError> = {
    (message |> DecodeError::Invalid) Result::Err
}

Use () DecodeError::Empty for a payload-free constructor. A payload variant moves an affine payload into the enum; an enum is Copy only when every payload type is Copy. Matching consumes the enum once and must cover every declared variant.

== and != are not defined for user enum values in this initial slice. Use match on qualified variants; the compiler rejects enum equality instead of comparing internal allocation addresses.

pub enum makes the type namespace available across Restrict source modules, but enum tags and payload layouts are compiler-internal and have no direct host WebAssembly ABI. Generic and recursive enums, multiple direct payloads, and ergonomic ? propagation remain future work; handle Result explicitly with match today.

Type Inference

Restrict infers local bindings, function returns, generic call sites, and lambda parameters when there is enough local context.

fun main: () -> Int32 = {
    val add_one = |value: Int32| value + 1
    41 |> add_one
}

A contextless local lambda can infer a concrete function type when local constraints are enough to finish it. Body constraints such as |value| value + 1 can contribute, and a later direct OSV call can supply remaining parameter context.

Unconstrained lambdas such as |value| value are rejected unless an expected function type or a later local direct use supplies the parameter type.

If the compiler cannot infer an empty collection, Result::Ok, Result::Err, Option::None, or a lambda parameter, add a type annotation at the nearest useful boundary.

Current Boundaries

These remain outside the current compiler surface:

  • Temporal Affine Type inference
  • Generic or recursive user enums and variants with more than one direct payload
  • Direct host WebAssembly ABI for user enum values
  • Ergonomic ? propagation
  • Direct WebAssembly ABI for exported generic functions and host-visible record values
  • Associated types, generic forms, default form methods, conditional or generic adoptions, enum adoptions, and dynamic dispatch
  • Borrowed slices/references
  • Traditional function-first calls

Reserved words remain reserved so the syntax can grow without breaking source compatibility. Exported generic functions and host-visible record values require concrete host ABI decisions before they become a WebAssembly codegen feature.

Type Inference

Restrict uses local, bidirectional type inference around explicit program boundaries. Function parameters, exported APIs, and record fields should keep clear types. Function bodies, local bindings, generic call sites, and lambdas can then use inference without drifting away from OSV syntax.

This page documents the v0.0.1 inference surface and its deliberate boundaries. The current user-defined enum slice is closed, non-generic, and non-recursive. Constructors and patterns use qualified Type::Variant names; a constructor payload is checked against its declared type. Temporal Affine Types (TAT) remain outside the default v0.0.1 gate. Exported records and pub enum declarations are source-level module metadata only and emit no direct host-visible Wasm export, so user enums have no host-visible enum ABI. Built-in Option and Result remain supported, including Result<T, CustomError> with a closed user enum; postfix ? propagation remains future work.

Local Bindings

Use val for immutable bindings. The initializer supplies the binding type:

fun adjust_score: (score: Int32) -> Int32 = {
    val bonus = 2;
    score + bonus
}

fun main: () -> Int32 = {
    40 |> adjust_score
}

Mutable bindings use mut val. The initializer is inferred the same way:

fun seed_counter: () -> Int32 = {
    mut val count = 0;
    count
}

Function Returns

Return types can be inferred for local functions when the body has a clear type. Keep public and exported function signatures explicit when the boundary matters. Exported generic functions are still rejected by v0.0.1 release-surface validation until Restrict has a stable concrete WebAssembly ABI for them.

fun risk_bonus: (risk: Int32) = {
    risk * 2
}

fun final_score: (base: Int32, risk: Int32) -> Int32 = {
    base + (risk |> risk_bonus)
}

Generic Calls

Generic parameters are inferred from OSV arguments:

fun identity_local: <T>(value: T) -> T = {
    value
}

fun choose_first: <T>(value: T, fallback: T) -> T = {
    value
}

fun main: () -> String = {
    val chosen = ("primary", "fallback") choose_first;
    chosen |> identity_local
}

When a generic function is used as a value, it needs an expected function type from the surrounding expression:

fun main: () -> List<Int32> = {
    val numbers: List<Int32> = [1, 2, 3]
    (numbers, identity) map
}

Do not rely on standalone generic function values without an expected type in v0.0.1.

Lambda Context

Lambda parameters are inferred from the expected function type. That expected type usually comes from a function parameter or a prelude combinator:

fun apply_int: (f: Int32 -> Int32, value: Int32) -> Int32 = {
    value |> f
}

fun apply_predicate: (f: Int32 -> Boolean, value: Int32) -> Boolean = {
    value |> f
}

fun main: () -> Int32 = {
    val incremented = (|x| x + 1, 41) apply_int
    val positive = (|x| x > 0, incremented) apply_predicate;

    positive match {
        true => { incremented }
        false => { 0 }
    }
}

Typed lambda parameters can supply that parameter context when no expected function type is available:

fun main: () -> Int32 = {
    val bump = |value: Int32| { value + 1 }
    41 |> bump
}

When a lambda has no expected function type, annotate each parameter that cannot come from context. The lambda return type is still checked from its body or from the surrounding expected return type.

A contextless local lambda can still infer a concrete function type when local constraints are strong enough. Body constraints, such as numeric operators, can contribute to that type, and a later direct OSV call can supply any remaining parameter context:

fun main: () -> Int32 = {
    val add = |left, right| left + right
    (20, 22) add
}

The compiler does not treat an unconstrained contextless lambda as a generic function value. If no later direct use or expected type supplies the missing parameter type, the binding is rejected:

fun main: () -> Int32 = {
    val identity = |value| value
    41
}

Local lambdas are allowed to be deferred until a later direct use supplies the missing type:

fun main: () -> Int32 = {
    val choose_left = |left, right| left
    (41, 0) choose_left
}

then and match branches can also produce a local callable when each branch ends in a lambda. The callable can be stored first and resolved later from a pipe, grouped OSV call, or container operation:

fun add_int: (total: Int32, value: Int32) -> Int32 = {
    total + value
}

fun main: (urgent: Boolean, bonus: Option<Int32>) -> Int32 = {
    val adjust = urgent then {
        val boost = 2;
        |score| score + boost
    } else {
        val factor = 2;
        |score| score * factor
    }
    val normalize = bonus match {
        Some(value) => {
            val doubled = value * 2;
            |score| score + doubled
        }
        None => {
            val doubled = 0;
            |score| score + doubled
        }
    }
    val scores = [10, 20]
    val adjusted = (scores, adjust) map
    val normalized = (adjusted, normalize) map

    (normalized, 0, add_int) fold
}

Branch callable prefixes are intentionally conservative in v0.0.1. They may use simple immutable val bindings whose values are replay-safe and Copy-typed. Mutable bindings, complex patterns, and non-Copy values such as String, records, lists, and functions are rejected in these prefixes.

Unit-Returning Function Values

Function types can return (), such as () -> () or Int32 -> (). Keep these types explicit at the parameter or binding that receives the function value, because () carries no payload for inference to recover later.

Unit-returning named functions can be passed as runtime function values when an expected function type is present:

fun record_event: (code: Int32) -> () = {
    ()
}

fun run_event: (handler: Int32 -> (), code: Int32) -> () = {
    code |> handler
}

fun main: () -> () = {
    val handler: Int32 -> () = record_event
    (handler, 7) run_event
}

Containers

Collection literals, Ok, Err, None, and higher-order container operations can infer their generic types from explicit result types, sibling arguments, sibling branches, or the surrounding expected type.

Built-in map and filter use compiler-internal Container behavior. The v0.0.1 compiler also supports method-only forms, concrete record takes declarations, and generic of bounds. Form-bounded calls are resolved statically and monomorphized; associated types, generic forms or adoptions, conditional adoptions, default methods, enum adoptions, and dynamic dispatch remain future design work.

form Labelled {
    fun label: (self: Self) -> String
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}
fun choose_list: <T>(value: List<T>, fallback: List<T>) -> List<T> = {
    value
}

fun choose_option: <T>(value: Option<T>, fallback: Option<T>) -> Option<T> = {
    value
}

fun main: () -> List<Int32> = {
    val numbers = ([], [1, 2, 3]) choose_list
    val maybe_limit = (() Option::None, 10 Option::Some) choose_option;

    maybe_limit match {
        Some(limit) => { (numbers, |n| n + limit) map }
        None => { numbers }
    }
}

The ambiguous forms value Result::Ok, error Result::Err, () Option::None, and [] require one of those sources of context. Used alone in a local binding, they are rejected because the compiler will not guess the missing generic type:

fun main: () -> Int32 = {
    val result = 1 Result::Ok
    0
}

Sibling branches can provide the missing type:

fun choose_result: (flag: Boolean) -> Result<Int32, String> = {
    flag then {
        1 Result::Ok
    } else {
        "missing" Result::Err
    }
}

Records

Record fields use : in both declarations and literals. Field access preserves the field type from the record declaration.

record Score {
    value: Int32,
    risk: Int32
}

fun score_total: (score: Score) -> Int32 = {
    score.value
}

fun main: () -> Int32 = {
    val score = Score { value: 10, risk: 3 };
    score |> score_total
}

Records are supported inside Restrict programs. Exported records are supported as source-level module metadata, but they do not emit direct host-visible Wasm exports in v0.0.1.

Syntax Hygiene

Current Restrict examples should use:

  • val for immutable bindings
  • mut val, never val mut
  • OSV calls such as value |> transform and (left, right) combine
  • fun name: (...) -> Type = { ... }
  • record fields written with :
  • no function-first call style
  • semicolons only where a following callable-shaped value could otherwise extend the same OSV expression; line breaks alone do not terminate calls

Scope Lifetimes and Affine Use

Every execution of a function, block, or callable body is a lifetime unit. This is the development implementation following v0.1.0; installing v0.1.0 alone does not provide these new guarantees.

Temporary Data and Returned Data

Temporary allocations end with the execution that created them. A returned value survives in the enclosing execution, including its nested strings, records, lists, arrays, variants, and closure captures. Data passed in from an outer execution retains its existing storage lifetime.

fun make_message: () -> String = {
    val temporary = [1, 2, 3];
    temporary |> list_count;
    "scope" + " result"
}

fun main: () -> Boolean = {
    val message = () make_message;
    message == "scope result"
}

The temporary list ends with make_message; the returned text remains valid in main. Ordinary blocks and with Arena use the same rule:

fun make_values: () -> List<Int32> = {
    with Arena { [1, 2, 3] }
}

No explicit arena or lifetime annotation is needed for ordinary values. The compiler shares physical storage between scopes and reclaims temporary data at exit. A fixed arena is not reserved for every pair of braces.

Invocation, Definition, and Repetition

Defining a lambda stores its captures; it does not execute its body. Each call has its own lifetime, including recursive calls and repeated map callbacks. A returned closure preserves its captured data until the enclosing execution ends. Scope chaining passes a valid result to the next scope.

Each while iteration and fold reduction reclaims obsolete replacement state. Assigning a new heap value to an enclosing mut val preserves the new value; repeated replacements do not retain every previous allocation. The same preservation applies to a new heap-backed element stored in an outer array, including arrays reached through enclosing records. A growing live value still uses growing storage and can exhaust the arena.

Affine Use Is A Separate Rule

Affine checking controls how often a binding may be used. It does not determine which executing scope retains storage. Primitive Copy bindings can be read again; ordinary immutable affine bindings can be referenced at most once. Mutable bindings keep their existing reassignment rules.

This change does not introduce Rust ownership, borrowing rules, or user-written lifetime annotations. Component Model own and borrow remain host ABI contracts, with their existing synchronous resource cleanup rules.

Runtime Limits

The current backend compacts reachable new data at scope exit using bounded, reusable scratch storage. It conservatively keeps active enclosing bindings until their containing scope ends; it does not promise reclamation after the last expression that uses a binding. Internal addresses may change and must not be retained by hosts. Use the explicit Component ABI for composite values.

An uncaught Wasm trap skips normal epilogues. Inspect diagnostics and discard the instance. Result::Err is an ordinary value and receives normal cleanup. return, break, continue, and ?? return/?? break/?? continue reclaim the scope they leave before they branch: return keeps only its value, and continue and break keep only what outlives the loop. Postfix ?, async suspension, and cancellation are future features.

Experimental TAT constraints remain separate. Ordinary values in a temporal block use the same lifetime rule, but the old experimental File/Database/ Transaction cleanup stubs fail closed: they are not validated host resource destruction. Synchronous B1 resources continue through their Component adapters.

Functions

Functions are first-class values in Restrict Language. Arguments come before the function name, so calls read in OSV order and compose naturally with |>.

Function Definition

Basic function syntax:

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

Functions without parameters use ():

fun get_answer: () -> Int32 = {
    42
}

Return types can be inferred when the body has enough information:

fun double: (value: Int32) = {
    value * 2
}

OSV Calls

Restrict supports OSV calls only. The object value or argument tuple comes first, then the function name.

val sum = (5, 10) add
val doubled = 21 |> double
val answer = () get_answer

Traditional calls such as add(5, 10) and get_answer() are rejected by the parser.

Function Composition

Chain small functions by passing each result to the next call:

fun increment: (value: Int32) -> Int32 = {
    value + 1
}

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun square: (value: Int32) -> Int32 = {
    value * value
}

fun main: () -> Int32 = {
    val stepped = 5 |> increment
    val doubled = stepped |> double;
    doubled |> square
}

The pipe operator is equivalent for single-argument calls:

fun main: () -> Int32 = {
    5 |> increment |> double |> square
}

Higher-Order Functions

Functions can accept and return other functions:

fun apply_twice: (value: Int32, f: Int32 -> Int32) -> Int32 = {
    value |> f |> f
}

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun main: () -> Int32 = {
    (5, double) apply_twice
}

For collection callbacks, scoped verb clauses, map, filter, and fold, see Higher-Order Functions and Collection Transforms.

Generic Functions

Generic parameters appear between the function name and parameter list:

fun identity: <T>(value: T) -> T = {
    value
}

fun keep_some: <T>(value: T) -> Option<T> = {
    value Option::Some
}

Function Values

Lambdas can be stored in variables. Add parameter annotations when there is no expected type from a surrounding function signature, return type, or call site.

val add_five: Int32 -> Int32 = |value: Int32| value + 5
val multiply: (Int32, Int32) -> Int32 = |left: Int32, right: Int32| left * right

val result = 10 |> add_five
val product = (3, 4) multiply

Recursive Functions

Recursive functions use the same OSV call form:

fun factorial: (value: Int32) -> Int32 = {
    value <= 1 then {
        1
    } else {
        val next = value - 1;
        value * (next |> factorial)
    }
}

fun fibonacci: (value: Int32) -> Int32 = {
    value match {
        0 => { 0 }
        1 => { 1 }
        _ => {
            val one_back = value - 1
            val two_back = value - 2
            (one_back |> fibonacci) + (two_back |> fibonacci)
        }
    }
}

Impl Methods

impl blocks attach functions to a record type, but calls still use OSV form.

record Point {
    x: Int32
    y: Int32
}

impl Point {
    fun squared_distance: (self: Point, other: Point) -> Int32 = {
        val Point { x: x1, y: y1 } = self
        val Point { x: x2, y: y2 } = other
        val dx = x1 - x2
        val dy = y1 - y2
        (dx * dx) + (dy * dy)
    }
}

fun main: () -> Int32 = {
    val p1 = Point { x: 0, y: 0 }
    val p2 = Point { x: 3, y: 4 }
    (p1, p2) squared_distance
}

Traditional dot calls such as p1.squared_distance(p2) are not part of the language.

Function Type Annotations

Explicit function type syntax:

val double_fn: Int32 -> Int32 = |value: Int32| value * 2
val add_fn: (Int32, Int32) -> Int32 = |left: Int32, right: Int32| left + right

val result = 10 |> double_fn
val sum = (3, 4) add_fn

Common Patterns

Wrapping Arguments

Use a lambda to bind one argument and keep the resulting value callable:

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

val add_five: Int32 -> Int32 = |right: Int32| (5, right) add
val result = 10 |> add_five

Option Mapping

Higher-order functions work naturally with match:

fun map_option: <T, U>(value: Option<T>, f: T -> U) -> Option<U> = {
    value match {
        Some(inner) => { inner |> f |> Option::Some }
        None => { () Option::None }
    }
}

Best Practices

  1. Use OSV calls consistently - They are the only supported function call form
  2. Annotate public boundaries - Return and parameter annotations make contracts clear
  3. Let local returns infer - Omit return annotations only when the body is obvious
  4. Keep affine values moving - Destructure records when multiple fields are needed
  5. Use lambdas for adapters - Wrap fixed arguments or expected callback shapes explicitly

See Also

Higher-Order Functions and Collection Transforms

Higher-order functions receive or return function values. In Restrict, they still follow OSV order: ordinary values and function values appear before the function being called.

Collection transforms add one more useful reading. A higher-order verb can open its final function parameter as a lexical scope, so the callback body can follow the verb without turning Restrict into function-first syntax.

Function Values Are Ordinary Arguments

A named function or lambda can be passed as an ordinary argument:

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun apply_twice: (value: Int32, transform: Int32 -> Int32) -> Int32 = {
    value |> transform |> transform
}

fun main: () -> Int32 = {
    (5, double) apply_twice
}

An inline lambda uses the same grouped OSV call:

fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3];
    (numbers, |value| value * 2) map
}

The container, callback, and any earlier arguments are objects of the call; they therefore remain before map, filter, or fold.

Current Collection Operations

The v0.0.1 compiler registers these higher-order operations in the prelude:

OperationCurrent inputCallbackResult
mapList<T>T -> UList<U>
mapOption<T>T -> UOption<U>
filterList<T>T -> BooleanList<T>
filterOption<T>T -> BooleanOption<T>
foldList<T> plus an initial U(U, T) -> UU

map transforms every list item, or the payload of Some. None remains None. filter keeps list items for which its predicate is true. For an Option, it keeps a matching Some or produces None. fold visits a list from left to right, passing the accumulated value and current item to its reducer.

Array and Result do not implement the compiler’s current container behavior. fold is List-only. The internal Container.Item and Container.Mapped<U> machinery is not a source-visible form and cannot yet be adopted by user-defined types.

Scoped Verb Clauses

When the final remaining parameter has a function type, the verb may open that function body as a trailing scope:

fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3];
    numbers map {
        it * 2
    }
}

The unheaded block introduces one contextual binding named it. The compiler uses the container item type as its expected parameter type and elaborates the clause through an ordinary lambda:

numbers map { it * 2 }
// Equivalent callback model:
(numbers, |it| { it * 2 }) map

This form is not special syntax hard-coded only for collections. Any callable whose final remaining argument is a function can open a scope:

fun apply: (value: Int32, transform: Int32 -> Int32) -> Int32 = {
    value |> transform
}

fun main: () -> Int32 = {
    41 apply {
        it + 1
    }
}

The complete 41 apply { ... } clause produces a value just like any other OSV call.

Implicit and Explicit Binders

Use the implicit it form for a short unary callback:

values filter {
    it > 0
}

Name the parameter explicitly when the body is longer or the name carries meaning:

values map { |value|
    val shifted = value + 1;
    shifted * 2
}

Callbacks with multiple parameters require explicit binders. A fold reducer receives the accumulator first and the current item second:

(values, 0) fold { |total, value|
    total + value
}

A zero-parameter scope uses an explicit empty header, { || ... }. It is useful for higher-order functions whose final parameter has type () -> T, but does not apply to map, filter, or fold.

Chaining Complete Clauses

Scoped verb clauses associate from left to right. Each complete clause becomes the object of the next verb:

fun main: () -> Int32 = {
    val values = [1, 2, 3]
    val selected = values map {
        it + 1
    } filter {
        it > 2
    }
    (selected, 0) fold { |total, value|
        total + value
    }
}

The program is read as:

  1. map [1, 2, 3] to [2, 3, 4];
  2. filter the complete mapped result to [3, 4];
  3. fold that result to 7.

A following pipe also receives the complete clause result:

values map { it + 1 } |> list_count

Type Inference

Higher-order calls provide type information in both directions:

  • the container type determines the callback item type;
  • the map body determines the mapped item type;
  • a declared result type can constrain the callback result;
  • filter requires a Boolean result;
  • the initial value and reducer result determine the fold accumulator type;
  • named generic functions such as identity can specialize from the expected callback type.
fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3]
    (numbers, identity) map
}

Empty collections and absent options can still need an annotation or another concrete use. Restrict reports an unresolved type instead of choosing a fallback type.

Option Transforms

The same scoped form works for the current Option container behavior:

fun increment_if_present: (value: Option<Int32>) -> Option<Int32> = {
    value map {
        it + 1
    }
}

fun keep_positive: (value: Option<Int32>) -> Option<Int32> = {
    value filter {
        it > 0
    }
}

This is container mapping and filtering, not a separate option_map API. fold remains List-only in v0.0.1.

Affine Values and Captures

Scoped callbacks use the same affine rules as ordinary lambdas and calls:

  • passing a non-Copy collection binding to map, filter, or fold uses that binding in the call;
  • callback parameters and captured bindings keep their normal Copy or affine behavior;
  • braces do not grant captured affine values extra uses;
  • a callback body may run zero, one, or many times according to the receiving function’s contract.

Two nested implicit scopes would both call their focus it, so Restrict rejects that form. Name at least one binder:

groups map { |group|
    group map {
        it + 1
    }
}

The explicit outer group makes both the data flow and capture intent clear.

Choosing a Form

Use an ordinary function argument when the callback already has a useful name or is selected as a value:

(numbers, normalize) map

Use a scoped verb clause when the callback is local to one transformation:

numbers map {
    it + 1
}

Use explicit scoped binders for multiple parameters, nested scopes, or longer bodies:

(numbers, 0) fold { |total, number|
    total + number
}

All three are the same higher-order function model. The forms differ only in how the callback is introduced and how clearly the local data flow reads.

See Also

Forms and Static Polymorphism

Forms are Restrict’s explicit behavioral contracts. They let a generic function require named behavior while preserving OSV calls, affine ownership, and direct WebAssembly calls.

The v0.0.1 slice is intentionally small:

  • a form is non-generic and contains required method signatures only;
  • every method is fully typed and starts with self: Self;
  • a concrete, non-generic record adopts a form with takes;
  • generic type parameters list requirements with <T of A + B>; and
  • the compiler monomorphizes every resolved call without a vtable or runtime form dictionary.

Declare and adopt a form

pub form Labelled {
    fun label: (self: Self) -> String
}

record Badge {
    text: String
}

Badge takes Labelled {
    fun label: (self: Badge) -> String = {
        self.text
    }
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}

fun main: () -> () = {
    Badge { text: "release candidate" } |> read_label |> println
}

Conformance is explicit. A record with an ordinary impl method named label does not satisfy Labelled until it has a matching takes declaration. A takes block must provide exactly the form’s methods with the same positional parameter and return types, replacing Self with the record type. Parameter names may differ from the contract.

pub form makes the contract importable by another Restrict source module. The takes declaration itself cannot be marked pub; export the form and nominal record instead.

Multiple bounds

+ means that the concrete type must satisfy every listed form:

fun inspect: <T of Display + Labelled>(value: T) -> String = { ... }

Ordinary impl methods and form adoptions for one concrete type share one selector namespace in this initial slice, so a type cannot expose the same selector through two declarations. Multiple generic bounds that expose the same selector are also ambiguous. The compiler reports an error instead of assigning a priority.

Affine receivers

A form method is an ordinary affine function. Passing a non-Copy record as self consumes it. Resolution is part of type inference and does not borrow, copy, or replay the expression.

fun consume_badge: (badge: Badge) -> String = {
    badge |> label
}

Copy scalars remain reusable according to the existing structural Copy rules. Adopting a form never makes a type Copy.

Display and output

The compiler provides the following form:

pub form Display {
    fun display: (self: Self) -> String
}

String, Int32, Int64, Float64, Boolean, Char, and () have compiler-provided Display adoptions. Records opt in explicitly:

record Notice {
    text: String
}

Notice takes Display {
    fun display: (self: Notice) -> String = {
        self.text
    }
}

fun main: () -> () = {
    42 |> print
    " · " |> print
    Notice { text: "records too" } |> println
}

print and println accept any Display value. eprint and eprintln remain String-only; print_int and print_float remain compatibility helpers. display, print, and println are compiler-reserved direct call targets; they cannot be declared as top-level source functions or ordinary/custom-form method selectors. The builtins themselves cannot yet be captured as first-class function values. The display method inside RecordName takes Display is the one method-name exception.

Deliberate limits

The initial slice does not include associated types, generic forms, generic or conditional takes, default methods, enum adoptions, negative bounds, selective adoption imports, existential form values, or dynamic dispatch. The compiler-internal Container projections used by collection builtins do not make Container or associated-type syntax source-visible.

Records and Prototypes

Records group named fields. In v0.0.1 they are fully useful inside Restrict programs and source modules, while direct host-visible record exports remain outside the stable ABI.

Record Definitions

Record declarations list fields with explicit types:

record Point {
    x: Int32,
    y: Int32
}

record Person {
    name: String,
    age: Int32,
    email: String
}

Record Literals

Record literals use : field initializers:

fun origin: () -> Point = {
    Point { x: 0, y: 0 }
}

fun default_person: () -> Person = {
    Person {
        name: "Alice",
        age: 30,
        email: "alice@example.com"
    }
}

Do not use field = value inside record literals.

Field Access And Destructuring

Access a single field with dot notation:

fun x_coordinate: (point: Point) -> Int32 = {
    point.x
}

When multiple fields are needed from the same affine record, destructure once:

fun sum_point: (point: Point) -> Int32 = {
    val Point { x, y } = point;
    x + y
}

Destructuring also lets explicit field names bind to different local names:

fun distance_like: (point: Point) -> Int32 = {
    val Point { x: px, y: py } = point
    (px * px) + (py * py)
}

Pattern Matching

Records can be matched by shape:

fun classify_point: (point: Point) -> String = {
    point match {
        Point { x: 0, y: 0 } => { "origin" }
        Point { x: 0, y } => { "on y-axis" }
        Point { x, y: 0 } => { "on x-axis" }
        Point { x, y } => { "somewhere else" }
    }
}

Branch bodies are expressions. If a branch needs multiple fields for calculation, bind them in the pattern and use the bindings inside the branch.

Clone Updates

Use .clone { ... } to create a modified record value:

fun move_x: (point: Point, next_x: Int32) -> Point = {
    point.clone { x: next_x }
}

The original record value is consumed by the update. The result is a new record value with the changed fields.

Freeze

freeze creates an immutable prototype-style value:

fun freeze_point: (point: Point) -> Point = {
    point freeze
}

Do not model record updates as direct field assignment such as point.x = 15. Use .clone { ... } for persistent updates, or a mutable binding assignment when replacing the entire binding value.

Impl Functions

impl blocks attach type-directed functions to a record. Calls remain OSV; dot method calls are not part of Restrict.

impl Point {
    fun squared_distance: (self: Point) -> Int32 = {
        val Point { x, y } = self
        (x * x) + (y * y)
    }

    fun translate: (self: Point, dx: Int32, dy: Int32) -> Point = {
        val Point { x, y } = self
        Point { x: x + dx, y: y + dy }
    }
}

fun main: () -> Int32 = {
    val point = Point { x: 3, y: 4 }
    (point) squared_distance
}

For multiple arguments, keep the receiver first:

fun moved_x: () -> Int32 = {
    val point = Point { x: 3, y: 4 }
    val moved = (point, 1, 2) translate;
    moved.x
}

Nested Records

Records can contain other records:

record Address {
    street: String,
    city: String,
    country: String
}

record Employee {
    name: String,
    age: Int32,
    address: Address
}

fun employee_city: (employee: Employee) -> String = {
    val Employee { name, age, address } = employee
    val Address { street, city, country } = address;
    city
}

If only one nested field is needed, direct field access is fine. If several fields are needed, destructure the outer and inner records once.

Host Boundary

Records are not directly exported as host-visible WebAssembly values in v0.0.1. Export scalar wrappers instead:

export fun exported_distance: () -> Int32 = {
    val point = Point { x: 3, y: 4 }
    (point) squared_distance
}

See the v0.0.1 Release Surface for the host ABI boundary.

Pattern Matching

Pattern matching destructures values and checks that every possible case is handled. Restrict keeps the matched value first: value match { ... }.

Basic Syntax

value match {
    pattern_one => { result_one }
    pattern_two => { result_two }
    _ => { default_result }
}

Each branch body is a block expression.

Literal Patterns

fun describe_number: (number: Int32) -> String = {
    number match {
        0 => { "zero" }
        1 => { "one" }
        42 => { "the answer" }
        _ => { "other" }
    }
}

Boolean patterns use Boolean values:

fun describe_flag: (enabled: Boolean) -> String = {
    enabled match {
        true => { "enabled" }
        false => { "disabled" }
    }
}

Variable Binding

A bare identifier binds the matched value.

fun double_any: (value: Int32) -> Int32 = {
    value match {
        x => { x * 2 }
    }
}

Option Patterns

fun value_or_zero: (maybe: Option<Int32>) -> Int32 = {
    maybe match {
        Some(value) => { value }
        None => { 0 }
    }
}

fun main: () -> Int32 = {
    val maybe: Option<Int32> = 42 Option::Some;
    maybe |> value_or_zero
}

() Option::None needs type context from an annotation, expected return type, sibling branch, or argument position.

User-Defined Enum Patterns

User enum patterns always use a qualified Type::Variant name. Payload-free variants have no nested pattern; payload variants take exactly one:

enum DecodeError {
    Empty
    Invalid(String)
}

fun error_code: (error: DecodeError) -> Int32 = {
    error match {
        DecodeError::Empty => { 1 }
        DecodeError::Invalid(message) => { 2 }
    }
}

All declared variants must be covered unless a wildcard handles the remainder. Variant patterns are refutable, so they are valid in match arms but not as a standalone val binding pattern. Heap-backed payload bindings remain affine.

List Patterns

fun list_score: (numbers: List<Int32>) -> Int32 = {
    numbers match {
        [] => { 0 }
        [single] => { single }
        [first, second] => { first + second }
        [head | tail] => { head }
    }
}

The [head | tail] pattern handles non-empty lists beyond the exact-length patterns listed before it.

Record Patterns

Record patterns use the same : field spelling as record declarations and literals.

record Point {
    x: Int32,
    y: Int32
}

fun point_score: (point: Point) -> Int32 = {
    point match {
        Point { x: 0, y: 0 } => { 0 }
        Point { x, y } => { x + y }
    }
}

Fields can be rebound to different local names:

fun point_product: (point: Point) -> Int32 = {
    point match {
        Point { x: px, y: py } => { px * py }
    }
}

Nested Patterns

record Person {
    name: String,
    age: Int32
}

record Company {
    name: String,
    employees: List<Person>
}

fun first_employee_name: (company: Company) -> String = {
    company match {
        Company { employees: [], ..._ } => {
            "No employees"
        }
        Company { employees: [Person { name, ..._ } | rest], ..._ } => {
            name
        }
    }
}

Nested patterns consume only the branch bindings they use. Unneeded fields can be ignored with ..._.

Exhaustiveness

The type checker rejects non-exhaustive matches. Cover all known cases or add a wildcard branch.

fun exhaustive_option: (score: Option<Int32>) -> Int32 = {
    score match {
        Some(value) => { value }
        None => { 0 }
    }
}

For infinite domains such as Int32 or String, include _ unless every possible value is represented by another pattern.

Important Notes

  • Branch bodies must be wrapped in { }.
  • The matched expression comes before match.
  • Int32, Boolean, Float64, Char, and () are copyable in patterns.
  • Heap-backed branch bindings such as String, List<T>, records, and function values remain affine.
  • Closed user enums use qualified variants and exhaustive matching. Generic and recursive enums, a host enum ABI, and ? propagation remain future work.
  • Pattern guards and tuple patterns are outside the v0.0.1 guide surface.

Warder

Warder is the project tool for Restrict Language v0.0.1. It creates project layouts, edits the repository-root warder.toml, builds Restrict source through the compiler, creates local cage files, and runs basic project checks.

Commands

The v0.0.1 CLI exposes these subcommands:

CommandDescription
warder new <name>Create a project directory
warder initInitialize the current directory
warder add <alias> --path <dir>Add a direct local path dependency
warder remove <name>Remove a dependency
warder buildBuild the package
warder run [args...]Build, then run the generated WASM
warder test [filter]Compile and execute Boolean tests under tests/
warder publishRun publish preflight checks
warder wrap <wasm>Wrap a WASM file into an experimental cage
warder unwrap <cage>Extract a cage
warder doctorCheck project structure and tools

The table above is the complete v0.0.1 subcommand surface.

Every subcommand accepts the global --project <dir> option. This makes it possible to build or test a project from a script without changing the caller’s working directory:

warder build --project ./services/checkout
warder test --project ./services/checkout

Projects

Create a new project:

warder new my-project
cd my-project

This creates:

my-project/
├── warder.toml
├── src/
│   └── main.rl
├── tests/
│   └── main_test.rl
├── README.md
└── .gitignore

Initialize an existing directory:

warder init

warder init writes the root warder.toml, creates src/ and tests/ when needed, and adds a starter src/main.rl only when there is no existing source entry point.

Repository Configuration

warder.toml is the only authored Warder configuration in a managed repository. warder new and warder init generate this minimal form:

manifest-version = 1

[package]
name = "my-project"
version = "0.1.0"

The project conventions supply src/main.rl as the entry, edition 2025, and the default build settings (wasm32, optimization enabled, and dist/). Empty dependencies are omitted. Write package.entry, package.edition, or a build table only when overriding those conventions; description and authors remain optional metadata.

Adding a local dependency creates a separate table when it is needed:

[dependencies]
local_utils = { path = "../local-utils" }

The current implementation has one publishable root package. Direct local source packages are selected centrally from this root file; they do not have leaf manifests or leaf locks. A future multi-publish workspace graph will extend this same root warder.toml rather than add a workspace file or member manifests. Public package and Component identities are explicit configuration, not values derived from directory names.

The dependency-table key is the source namespace used by import. In the current v0.0.1 buildable slice, every dependency must be a direct local path dependency. The alias must be one non-keyword Restrict identifier, so use local_utils rather than local-utils; Warder never converts hyphens implicitly. The aliases std and project are reserved; Warder maps project to the root package source directory while compiling tests.

Registry versions, Git repositories, foreign WASM dependencies, and dependencies declared by a local dependency are not resolved yet. warder add, warder build, and warder test reject those forms explicitly instead of writing placeholder lock entries. Use warder wrap separately for experimental local evaluation of a foreign WASM file.

An explicit build table controls the target name, whether optimization is requested, and the output directory when the defaults are overridden.

Dependencies

Add a local dependency:

warder add local_utils --path ../local-utils

The referenced local source package needs only its library root:

local-utils/
└── src/
    ├── lib.rl
    └── numbers.rl

A minimal src/lib.rl might export a function:

pub fun score: () -> Int32 = {
    42
}

Remove a dependency:

warder remove local_utils

Package namespaces

The root configuration binding mounts the dependency’s src/ directory under its alias:

Source importDependency file
import local_utils.{score}../local-utils/src/lib.rl
import local_utils../local-utils/src/lib.rl
import local_utils.numbers.{double}../local-utils/src/numbers.rl

An unqualified import inside a dependency stays package-local. For example, import numbers.{double} inside local-utils/src/lib.rl resolves to that package’s src/numbers.rl, not an application module.

This is a configuration-to-compiler namespace binding. It does not add source-level import ... as aliases or re-exports; both remain unsupported.

On a successful build, Warder writes one generated warder.lock beside the root configuration. The lock records only dependency choices that cannot be reconstructed deterministically from repository sources. Direct local source packages are therefore not lock entries. Registry, Git, foreign WASM, and transitive resolution currently fail closed, so a local-only lock has no resolved package entries. Commit warder.lock when Warder generates it; do not edit it by hand.

Warder compiles immutable snapshots of both the application source tree and each dependency source tree. It rejects overlapping application, dependency, and output roots. Builds for one project are serialized, and the WAT, WASM, Cage, and lock file are published together through a recoverable transaction; a failed compile keeps the previous artifact set intact.

Build Outputs

Build the project:

warder build

For a package named my-project at version 0.1.0 with no [component] selection, the default outputs are:

dist/my-project-0.1.0.wat
dist/my-project-0.1.0.wasm
dist/my-project-0.1.0.rgc

The output stem is always <name>-<version>. Change the output directory with the root configuration’s build.output field.

The build target is read from warder.toml, not from a command-line flag.

Use watch mode during local iteration:

warder build --watch

Warder performs an initial build, then rebuilds when warder.toml, project .rl files, or .rl files in a configured direct local dependency change. This is a full rebuild watcher, not an incremental compiler or an npm bundler.

Component build

A Component project requires a schema-v1 or schema-v2 [component] selection in the root warder.toml. Ordinary pub and export declarations are not published implicitly. For example, schema v1 selects a public root function:

[component]
schema = 1
package = "acme:my-project@0.1.0"
world = "my-project"
abi = "canonical-v1-sync"

[[component.exports]]
interface = "api"
source = "run"
name = "run"

Once [component] is present, plain warder build publishes the Component artifact set. --component is an explicit assertion that the project must have a Component selection, while --core overrides the project default:

warder build
warder build --component
warder build --core

Warder validates and transactionally publishes this set together with the lock update:

dist/my-project-0.1.0.component.wasm
dist/my-project-0.1.0.component.wit
dist/my-project-0.1.0.component.toml

The metadata separates the semantic interface hash from exact Component and WIT content hashes. A failed rebuild preserves the previous complete set. Schema v2 adds root-only resources, value-only capture once-callables, and explicit generic function instances.

The .component.toml file above is generated artifact metadata under dist/, not another project configuration file. Source-first Component publication is also future work: a later edition may distinguish package-visible pub from Component-intent export, but the current implementation still requires the source-public plus [component] double gate.

Run And Test

Run the built program through an installed WASM runtime:

warder run
warder run -- arg1 arg2

warder run builds first, then looks for the generated dist/<name>-<version>.wasm. It is currently a Core Wasm program runner. In a Component project it reports that it is forcing a Core build; Component execution needs an explicit Component host.

Run tests:

warder test
warder test bonus

Warder discovers source-public functions whose names begin with test_ or end with _test. Each test must be synchronous, non-generic, take no arguments, and explicitly return Boolean:

import project.main.{calculate_bonus}

pub fun test_bonus: () -> Boolean = {
    (21, 4) calculate_bonus == 25
}

Warder compiles each test file to WASI Preview 1 Core Wasm and executes every matching export in an isolated Wasm instance. true passes; false, a trap, a compilation error, or a missing export fails. The optional filter matches function names. Tests resolve the same direct-local dependencies as warder build. This is a convention over ordinary functions, not a dedicated test declaration syntax. The reserved project namespace maps to the directory containing package.entry, which is src/ by default.

Publish Preflight

warder publish
warder publish --registry https://example.com/registry

For v0.0.1, warder publish performs a release-style preflight build and metadata validation. Registry upload, authentication, and signing remain experimental and no package is uploaded. This preflight currently validates the Core Cage profile and reports when it forces a Core build for a Component project.

Cage Commands

Builds already write a local .rgc cage next to the .wat and .wasm files.

Wrap an external WASM module for local evaluation:

warder wrap module.wasm --name module-name --version 0.1.0
warder wrap module.wasm --name module-name --version 0.1.0 --wit interface.wit --output module-name-0.1.0.rgc

Extract a cage:

warder unwrap module-name-0.1.0.rgc
warder unwrap module-name-0.1.0.rgc --output extracted-module

Foreign Wasm wrapping is experimental in v0.0.1. wrap --wit stores the caller-supplied WIT text without parsing, type-checking, matching it to the Core module, or componentizing the module. It is separate from warder build --component, which generates and validates the Component artifact set from a Restrict package selection.

Doctor

Check the current project:

warder doctor

warder doctor validates the root warder.toml, checks that the entry source exists, and validates warder.lock when present. It also checks for a Restrict compiler and reports whether a WASM runtime such as Wasmtime or Wasmer is available.

v0.0.1 Release Surface

This page records the public surface that v0.0.1 documentation, examples, and release-surface tests should agree on. LANGUAGE_SPECIFICATION.md remains the authoritative language specification; this page is the shorter release contract.

Supported

Surfacev0.0.1 status
OSV-only callsUse `value
Scoped verb clausesA callable’s final function parameter may open a typed scope such as values map { it + 1 } or `(values, 0) fold {
Completed-value applicationValues produced by match, then, blocks, and completed clauses may continue through direct OSV, pipe, named scoped verbs, or an anonymous exact-once unary scope such as `value {
Typed context scopescontext Name declares typed fields. with Context { bindings } { body } binds them for one lexical body, and nested scopes compose. Function-level context annotations and temporal lifetime scopes remain future work.
val / mut val bindingsImmutable bindings use val; mutable bindings use mut val.
Built-in generic valuesList<T>, Option<T>, Result<T, E>, and concrete Range<Int32> are supported.
Fixed-length arraysSource-level Array<T, N> is supported. Compiler-internal wildcard lengths are not a public Array<T, 0> contract.
Built-in container behaviorBuilt-in map, filter, and fold use compiler-supported container behavior for current built-ins. The internal Container associated-type machinery is not source-visible.
Source importsDotted source imports, named imports, wildcard imports, and whole-module imports are supported. String imports and aliases are not.
RecordsRecords are supported inside Restrict programs and across source modules. Direct host-visible record exports are not.
Scalar function exportsConcrete non-generic pub fun and export fun are supported when every host-visible parameter and result is scalar.
Scalar top-level constantsImmutable top-level literal constants can be exported when their ABI is Int32, Int64, Float64, Boolean, Char, or ().
Program entryZero-argument main is the executable source entry point. The generated _start export is a no-result wrapper that calls $main, drops any result, and resets the default arena. A parameterized function named main remains a normal function and does not emit _start.
Compilation targetRestrict source compiles to Core WebAssembly. The current program profile uses basic WASI Preview 1 imports; browser JavaScript is host glue rather than a JavaScript backend.

Scalar Host ABI

The current host-visible ABI is intentionally narrow:

Int32   -> i32
Int64   -> i64
Float64 -> f64
Boolean -> i32
Char    -> i32
()      -> no payload

Use scalar wrapper functions when a program computes with records, strings, lists, Option, or Result internally but needs to expose a stable host entry.

record Score {
    base: Int32,
    bonus: Int32
}

fun total_score: (score: Score) -> Int32 = {
    score.base + score.bonus
}

export fun exported_score: () -> Int32 = {
    val score = Score { base: 40, bonus: 2 };
    score |> total_score
}

Static Enums and Forms

The v0.0.1 release includes closed user-defined enums and a narrow static form system without widening the default host ABI:

SurfaceCurrent status
Closed user enumsSupported when non-generic and non-recursive. Every variant has zero or one payload.
Constructors and patternsUse qualified Type::Variant names. Constructors use OSV order and matches are exhaustive.
Custom Result errorsA closed enum can be the error in Result<T, CustomError>. Error propagation still uses explicit match; postfix ? remains future work.
pub enumExposes the enum namespace across Restrict source modules only. Enum values have no direct host-visible WebAssembly ABI.
Method-only formsform Name contains fully typed method signatures. Forms are non-generic and have no associated types or default bodies.
Concrete record adoptionsRecordName takes FormName supplies every method body for one concrete, non-generic record. A takes declaration itself is not public.
Form boundsGeneric functions use <T of Form> or <T of First + Second>. Calls are statically checked and monomorphized to direct adoption methods.
pub formExposes the form contract across Restrict source modules. It does not create a host-visible form object or dynamic dispatch ABI.
Standard Displaydisplay, print, and println accept <T of Display>. Scalar built-ins adopt Display; user records opt in explicitly. These compiler-reserved call targets are direct-call-only in the initial slice. eprint and eprintln remain String-only, and print_int / print_float remain compatibility helpers.

Rejected With Explicit Diagnostics

SurfaceReason
Traditional callsRestrict is OSV-only. Use (1, 2) add or `value
String imports and import aliasesv0.0.1 keeps the source module surface dotted and direct.
Re-exportsImport declarations stay at the source module boundary.
Exported generic functionsHost-visible generic ABI rules are still design work.
Exported composite host valuesStrings, records, lists, Option, and Result do not have a direct host ABI yet.
Computed or mutable exported globalsExported top-level bindings must be immutable scalar literal constants.

Reserved For Later

  • Temporal Affine Types
  • associated types, generic forms, and default form methods
  • generic, conditional, or enum takes declarations
  • dynamic form dispatch and runtime form objects
  • first-class values for the polymorphic display, print, and println builtins
  • generic or recursive user enums and variants with more than one direct payload
  • direct host WebAssembly ABI for user enum values
  • postfix ? error propagation
  • direct generic or composite host ABI
  • WebAssembly Component Model and WIT binding generation
  • general WASI filesystem, network, HTTP, and async bindings
  • direct portable browser DOM interfaces

Keeping these boundaries explicit is important: Restrict can evolve without silently promising unstable host layouts or unfinished syntax.

Standard Library Reference

This page documents the v0.0.1 compiler-registered standard-library surface, including Display and the compatibility helpers retained by the release. The files under std/ are source-adjacent indexes for readers and tests; runtime behavior is implemented in the compiler and WebAssembly code generator.

The current standard library is intentionally small. APIs listed as absent below are not user-facing v0.0.1 features, even if their names appear in older examples or design sketches.

Calling Convention

Standard-library calls use the same OSV syntax as user functions:

"hello" |> println
42 |> print
(left, right) max
values |> list_count
(maybe_value, fallback) option_unwrap_or

Traditional calls such as println("hello"), max(left, right), or value.method() are not supported.

Examples in this reference show expression or local-binding forms unless they explicitly use pub val. In v0.0.1, top-level constants are limited to literal Int32, Int64, Float64, Boolean, Char, and () values. Exported String, lists, records, Option, and Result values require a composite host ABI or runtime allocation and are not part of the top-level global export surface.

Prelude

The prelude contains generic function helpers and basic boolean/assertion helpers:

identity: <T>(T) -> T
map: generic container mapping builtin
filter: generic container filtering builtin
fold: generic List reduction builtin
not: (Boolean) -> Boolean
and: (Boolean, Boolean) -> Boolean
or: (Boolean, Boolean) -> Boolean
assert: (Boolean, String) -> ()
panic: (String) -> ()

The supported containers, callback types, scoped call forms, and affine behavior are described in Higher-Order Functions and Collection Transforms.

Canonical call shapes:

value |> identity
condition |> not
(left, right) and
(condition, "expected condition to hold") assert

Helpers such as xor, eq, ne, when, and debug_assert are not part of the current compiler-registered surface.

IO

Display is the standard compiler form for turning a value into String:

form Display {
    fun display: (self: Self) -> String
}

The compiler provides adoptions for String, Int32, Int64, Float64, Boolean, Char, and (). A user record adopts Display explicitly:

record Notice {
    text: String
}

Notice takes Display {
    fun display: (self: Notice) -> String = {
        self.text
    }
}

Current IO functions:

display: <T of Display>(T) -> String
println: <T of Display>(T) -> ()
print: <T of Display>(T) -> ()
print_int: (Int32) -> ()
print_float: (Float64) -> ()
eprint: (String) -> ()
eprintln: (String) -> ()

Canonical call shapes:

"hello" |> println
42 |> print
Notice { text: "records too" } |> println
3.14 |> print_float
"error" |> eprintln

print_int and print_float remain compatibility helpers. eprint and eprintln intentionally remain String-only. Form selection is static and monomorphized; these functions do not use runtime interface objects. display, print, and println are compiler-reserved direct call targets and cannot be declared as top-level source functions or ordinary/custom-form method selectors. The builtins themselves are direct-call-only and cannot be captured as first-class function values.

Stdin and file APIs are outside the v0.0.1 std surface. That includes readLine, readFile, writeFile, path metadata, directory operations, and fallible ?-style IO flows.

Lists

Current list functions:

list_is_empty: <T>(List<T>) -> Boolean
list_head: <T>(List<T>) -> Option<T>
list_tail: <T>(List<T>) -> Option<List<T>>
list_reverse: <T>(List<T>) -> List<T>
list_prepend: <T>(T, List<T>) -> List<T>
list_append: <T>(List<T>, T) -> List<T>
list_concat: <T>(List<T>, List<T>) -> List<T>
list_count: <T>(List<T>) -> Int32
list_length: <T>(List<T>) -> Int32
list_get: <T>(List<T>, Int32) -> T

Canonical call shapes:

values |> list_is_empty
values |> list_head
values |> list_tail
values |> list_reverse
(item, values) list_prepend
(values, item) list_append
(left, right) list_concat
values |> list_count
values |> list_length
(values, index) list_get

Collection literals use [1, 2, 3]. Without an expected type, the literal is a List<T>; in an expected Array<T, N> context, the same literal is checked as a fixed-size array. The bracket-bar array literal form is removed.

Dedicated list_map, list_filter, and list_fold_left helpers are not part of the current std surface. Use the compiler-registered prelude map, filter, and fold builtins where the type checker has the required context. The higher-order guide records the exact v0.0.1 container boundary.

Math

Current math functions:

abs: (Int32) -> Int32
max: (Int32, Int32) -> Int32
min: (Int32, Int32) -> Int32
pow: (Int32, Int32) -> Int32
factorial: (Int32) -> Int32
abs_f: (Float64) -> Float64
max_f: (Float64, Float64) -> Float64
min_f: (Float64, Float64) -> Float64

Canonical call shapes:

value |> abs
(left, right) max
(left, right) min
(base, exponent) pow
value |> factorial
value |> abs_f
(left, right) max_f
(left, right) min_f

Floating-point trig, logarithm, random-number, SIMD, and wider numeric conversion helpers are outside the current std surface.

Option

Option<T> is a built-in generic sum type. Current option helpers:

option_is_some: <T>(Option<T>) -> Boolean
option_is_none: <T>(Option<T>) -> Boolean
option_unwrap_or: <T>(Option<T>, T) -> T

Source-level constructors:

fun choose_score: () -> Int32 = {
    val maybe_score: Option<Int32> = 42 Option::Some;
    val no_score: Option<Int32> = () Option::None;
    (maybe_score, 0) option_unwrap_or
}

Canonical call shapes:

maybe_value |> option_is_some
maybe_value |> option_is_none
(maybe_value, fallback) option_unwrap_or

Higher-order option helpers such as option_map, option_flatten, option_and_then, option_zip, and option_to_list are not part of the current std surface.

Result

Result<T, E> is a built-in generic sum type with constructor and pattern support:

fun choose_result: (flag: Boolean) -> Result<Int32, String> = {
    flag then {
        42 Result::Ok
    } else {
        "missing" Result::Err
    }
}

There are no dedicated std result helper functions in the v0.0.1 surface. Use match for result handling:

fun result_or_zero: (score: Result<Int32, String>) -> Int32 = {
    score match {
        Ok(value) => { value }
        Err(message) => { 0 }
    }
}

There is no v0.0.1 error-propagation syntax; use match for result handling.

Strings

Current string operations are expression forms, not std functions:

a + b: concatenate two String values
a == b: compare String contents
a != b: compare String contents and negate the result

Canonical expression shapes:

first + second
first == second
first != second

The code generator lowers these through runtime helpers such as string_concat and string_eq. Length, parsing, formatting, case conversion, splitting, and trimming helpers are outside the current std surface.

Outside The Current Std Surface

The following areas are absent from the current compiler-registered surface:

  • File-system and path APIs
  • Time and date APIs
  • Synchronization primitives
  • Borrowing/reference-oriented memory helpers
  • Conversion forms
  • Hashing forms
  • Debug formatting
  • Random-number APIs
  • Networking APIs
  • Environment and process APIs
  • Associated types and advanced form features

When adding std documentation, document only APIs backed by compiler/runtime behavior and keep design sketches out of current-reference examples.

Keywords Reference

Restrict reserves a compact set of words for current syntax and future design space. This page separates the implemented v0.0.1 surface from words that remain reserved for future work.

Current Declaration Keywords

KeywordUse
funDefine a function.
valDefine an immutable binding.
mutMark a binding mutable as mut val.
recordDefine a record type.
enumDefine a closed, non-generic, non-recursive user enum.
formDefine a non-generic, method-only static interface.
takesAdopt a form for one concrete, non-generic record.
ofRequire one or more forms on a generic type parameter.
contextDefine a context binding shape.
pubExpose a supported top-level declaration from a source module.
importImport from dotted source modules.
exportExpose a host-visible function or supported scalar constant.
implDefine type-directed functions for a receiver type.
asReserved for import/type naming positions; aliases are outside v0.0.1 source imports.

Examples:

record Score {
    value: Int32
}

fun bump: (score: Int32) -> Int32 = {
    score + 1
}

export fun exported_score: () -> Int32 = {
    41 |> bump
}

User enum variants have zero or one payload and stay qualified under the enum name:

pub enum ParseError {
    Empty
    Message(String)
}

fun make_error: (message: String) -> ParseError = {
    message |> ParseError::Message
}

pub enum exposes the type to Restrict source modules only; it does not define a host enum ABI. Generic or recursive enums and ? propagation remain future work.

Forms use fully typed method signatures, while adoptions provide their bodies:

pub form Labelled {
    fun label: (self: Self) -> String
}

record Badge {
    text: String
}

Badge takes Labelled {
    fun label: (self: Badge) -> String = {
        self.text
    }
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}

The compiler selects these calls statically. Generic forms, associated types, default methods, conditional or generic adoptions, enum adoptions, and dynamic dispatch remain outside the current slice.

Mutable bindings place mut before val:

fun next_counter: () -> Int32 = {
    mut val counter = 0;
    counter = counter + 1;
    counter
}

Current Expression Keywords

KeywordUse
thenIntroduce the true branch of a conditional expression.
elseIntroduce the false branch.
matchPattern-match the value on its left.
trueBoolean true literal.
falseBoolean false literal.
SomeBuilt-in Option<T> present constructor.
NoneBuilt-in Option<T> absent match pattern; construct with () Option::None.
withBind a context value for a block.
fun label: (score: Int32) -> String = {
    score >= 80 then {
        "pass"
    } else {
        "retry"
    }
}

fun option_score: (value: Option<Int32>) -> Int32 = {
    value match {
        Some(score) => { score }
        None => { 0 }
    }
}

Result::Ok and Result::Err are qualified built-in Result<T, E> constructors. The unqualified names remain match patterns; value construction uses the qualified namespace:

fun checked_score: (score: Int32) -> Result<Int32, String> = {
    score >= 0 then {
        score Result::Ok
    } else {
        "negative" Result::Err
    }
}

Prototype And Ownership Keywords

KeywordUse
cloneRecord clone/update operation as .clone { ... }.
freezeCreate an immutable prototype-style value.
fatalReserved for fatal diagnostics and termination-oriented design.
record Reading {
    value: Int32,
    valid: Boolean
}

fun mark_valid: (reading: Reading) -> Reading = {
    reading.clone { valid: true }
}

Reserved Or Experimental

Keywordv0.0.1 status
temporalReserved for Temporal Affine Types, outside the default gate.
withinReserved for temporal/lifetime syntax.
whereReserved for future type constraints.
lifetimeReserved for lifetime syntax.
awaitReserved for async design.
spawnReserved for concurrency design.

Do not use reserved words as identifiers. If documentation or examples need a feature from this table, mark it as future or experimental instead of presenting it as current syntax.

Operators Reference

This page summarizes the v0.0.1 operator surface. Restrict keeps calls OSV, so operators either combine expressions directly or route a value into a function.

Arithmetic

OperatorMeaningNotes
+Addition or string concatenationNumeric addition; String + String concatenates.
-SubtractionNumeric.
*MultiplicationNumeric.
/DivisionNumeric.
%RemainderNumeric.
fun arithmetic_score: () -> Int32 = {
    val base = 10 + 5 * 2
    val adjusted = base - 3
    val divided = adjusted / 2;
    divided + (adjusted % 2)
}

fun greeting: () -> String = {
    "Hello, " + "Restrict"
}

Comparison And Equality

OperatorMeaning
==Equal
!=Not equal
<Less than
<=Less than or equal
>Greater than
>=Greater than or equal
fun passing: (score: Int32) -> Boolean = {
    score >= 80
}

fun same_label: (left: String, right: String) -> Boolean = {
    left == right
}

Boolean Operators

OperatorMeaning
&&Logical and
`
!Logical not
fun should_release: (tests_pass: Boolean, warnings_clear: Boolean) -> Boolean = {
    tests_pass && warnings_clear
}

fun should_hold: (blocked: Boolean, degraded: Boolean) -> Boolean = {
    blocked || degraded
}

fun invert: (value: Boolean) -> Boolean = {
    !value
}

Pipe Operator

|> sends the value on the left to the function on the right:

fun increment: (value: Int32) -> Int32 = {
    value + 1
}

fun main: () -> Int32 = {
    41 |> increment
}

The pipe is the single-argument OSV call form. Multiple arguments use grouped OSV calls instead:

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

fun main: () -> Int32 = {
    (20, 22) add
}

The removed mutable pipe operator |>> is not part of v0.0.1.

Field Access

. reads a field from a record value. Because records are affine values, avoid using the same non-copy record repeatedly. Destructure once when multiple fields are needed:

record Reading {
    value: Int32,
    weight: Int32
}

fun weighted: (reading: Reading) -> Int32 = {
    val Reading { value, weight } = reading;
    value * weight
}

Record update uses .clone { ... }:

fun reset_weight: (reading: Reading) -> Reading = {
    reading.clone { weight: 1 }
}

Conditional And Match Forms

then, else, and match are expression forms rather than symbolic operators, but they behave like operators in the expression grammar:

fun label: (score: Int32) -> String = {
    score >= 80 then {
        "pass"
    } else {
        "retry"
    }
}

fun option_or_zero: (value: Option<Int32>) -> Int32 = {
    value match {
        Some(score) => { score }
        None => { 0 }
    }
}

Precedence Notes

The practical precedence order for v0.0.1 examples is:

  1. grouped expressions, literals, variables, field access, and grouped OSV calls
  2. unary !
  3. *, /, %
  4. +, -
  5. comparison operators
  6. equality operators
  7. &&
  8. ||
  9. pipe |>
  10. then/else and match

Use parentheses when mixing grouped OSV calls with arithmetic or pipe chains. The compiler rejects function-first calls such as add(1, 2), so parentheses around arguments are not a traditional call signal in Restrict.

Online Compiler

The GitHub Pages site publishes the browser compiler beside this mdBook:

/docs/      mdBook documentation
/compiler/  online compiler
/blog/      implementation notes

The compiler page uses the Rust crate’s wasm-bindgen entry points through a wasm-pack web bundle. It is useful for quick syntax checks, parser inspection, type-checking, and generated WAT inspection without building the local CLI.

Build The Bundle

From the repository root:

wasm-pack build --target web --out-dir web/pkg

The Pages workflow runs the same command before assembling site/dist.

Share A Source Example

The compiler reads source code from the code query parameter:

compiler/?code=<url-encoded-restrict-source>

The mdBook theme uses that route for “Try in Playground” buttons on complete restrict code blocks that contain fun main.

What It Shows

The browser compiler can show:

  • generated WebAssembly text
  • lexer output
  • parsed AST debug output
  • type-checking and code-generation diagnostics

It uses the same parser, type checker, and code generator as the Rust crate. That makes it a good smoke test for examples in docs and blog posts.

The example menu is arranged as a short learning path:

  • Start here introduces output, functions and OSV calls, records, and Option matching.
  • Current compiler covers a custom enum carried by Result, a generic form contract, and Display-polymorphic output.
  • Diagnostics contains an intentional affine use-after-consume error.

Each selection shows what it teaches and the expected output or diagnostic above the editor. Choose Result with a custom error to see a qualified enum variant become the useful output invalid code, rather than an opaque numeric sentinel.

Forms and Display are deliberately separate. Generic form contract shows the whole static mechanism: form Labelled, Badge takes Labelled, and the explicit generic bound <T of Labelled>. Display across types then applies the same idea to the compiler prelude by sending an Int32, a String, and a record with an explicit Display adoption through println.

The checked-in sources under samples/playground/ are the catalog’s single source of truth. CI compiles every successful example, executes its generated WebAssembly, asserts exact stdout, and separately asserts the intentional diagnostic.

Module Imports

The web entry point supports a module-source map API internally. The default UI compiles single-file examples unless module sources are supplied by the page. For documentation examples, prefer self-contained programs:

fun increment: (value: Int32) -> Int32 = {
    value + 1
}

fun main: () -> Int32 = {
    41 |> increment
}

If an example depends on source imports, explain the required module sources instead of presenting it as a one-click playground example.

Current Limits

The online compiler is not a full IDE. It does not provide package resolution, Warder project builds, Wasmtime execution, or host stdin/file/network APIs. It is a browser-hosted compiler surface for the current source file and the explicit module sources supplied to the web API.

Testing

Restrict has two practical testing layers today: repository tests for compiler development and executable Warder tests for user projects.

Repository Tests

From the repository root, use the project-managed toolchain:

mise run test-fast

Useful focused commands:

mise exec -- cargo test --test quality_gates test_docs_hygiene::
mise exec -- cargo test --test integration_07 test_wat_validation::
mise run check
mise run preflight
mise run preflight-pages

mise run test-fast is the normal local gate for compiler work. It runs formatting, focused library checks, and one combined Cargo invocation for docs, release-surface, sample, and generic integration tests without the slow release example CLI sweep. mise run preflight is the one-command merge gate: it runs cheap checks first, then the complete workspace suite, ignored release example checks, and the checked-in browser runtime smoke. Use mise run preflight-pages for a publication handoff that must also rebuild the mdBook, WebAssembly package, and assembled Pages artifact.

GitHub Actions runs the same coverage as separate quality, compiler-core, integration, Warder, and release-gate jobs. Integration test targets are split deterministically across four shards, while the final test job preserves the stable branch-protection check name.

mise run check executes the slow release example CLI entrypoint validation. Those tests are ignored in the default cargo test run so active compiler iteration stays fast while CI/release checks keep full coverage.

test_docs_hygiene checks public documentation and examples for removed syntax such as let, fn, function-first calls, stale record initializers, and unsupported import forms. That test is intentionally part of the docs workflow: examples should not drift away from the language specification.

Warder Project Tests

A Warder project normally contains .rl files under tests/:

hello-world/
├── src/main.rl
└── tests/main_test.rl

Run:

warder test

Warder uses ordinary Restrict functions rather than a dedicated test declaration syntax. An executable test is source-public, synchronous, non-generic, takes no arguments, explicitly returns Boolean, and has a name that begins with test_ or ends with _test:

import project.main.{increment}

pub fun test_math: () -> Boolean = {
    2 + 2 == 4
}

pub fun pipeline_test: () -> Boolean = {
    (41) increment == 42
}

warder test compiles each test file to WASI Preview 1 Core Wasm and executes each matching export in a fresh instance. true passes; false, a trap, a compilation error, an invalid Boolean result, or a missing export fails. A positional filter matches test function names:

warder test pipeline

During tests, the reserved project namespace points at the directory containing package.entry (src/ by default), so tests can import application modules such as project.main.

Runtime Examples

Compiler tests also execute selected examples through WebAssembly runtimes where possible. Keep host-visible runtime examples scalar at the boundary:

export fun exported_score: () -> Int32 = {
    42
}

Composite values are useful inside examples, but exported records, strings, lists, Option, Result, and generic functions remain outside the v0.0.1 host ABI.

Documentation Examples

When adding docs:

  • use val, never let
  • use OSV calls, never function(args)
  • use mut val, never val mut
  • use : in record fields and record literals
  • avoid stdin, filesystem, and network APIs in quick-start runnable examples
  • keep current user enum examples closed, non-generic, and non-recursive, with qualified variants and exhaustive matches
  • keep form examples method-only, adoptions concrete and non-generic, and of bounds explicit
  • mark TAT, generic or recursive enums, enum host ABI, associated types, generic/conditional/enum adoptions, dynamic dispatch, and composite host ABI as future work

The docs tests are meant to enforce those rules automatically.

Benchmarking

Restrict’s in-repository benchmarks are regression tools for the compiler and generated Core WebAssembly. They are not yet evidence for public claims against Rust, Grain, MoonBit, or another language.

Run the suite

Use the short mode while changing the compiler:

mise run bench-smoke

Use the full local baseline when reviewing performance:

mise run bench

Enforce the checked-in deterministic baseline from a clean worktree:

mise run bench-gate

Record five full reports and assess within-run timing stability:

mise run bench-evidence

The smoke, full, and deterministic-gate commands build the compiler and the native wasmi benchmark runner in release mode. Results are written to target/benchmark-results/restrict-baseline.json; generated Wasm artifacts are stored beside the report under artifacts/.

benchmarks/baselines/core-wasm-v0.1.0.json is the current reviewed stable baseline. The v0.1.0-rc.1 and v0.0.1 baselines remain checked in as historical evidence, and benchmarks/regression-policy.json is the machine-readable policy. The gate requires an exact compiler/runtime/validator/compressor toolchain, workload sources and inputs, Wasm hashes, and memory observations. It also rejects any raw, release, or instrumented artifact growth. An intended compiler or corpus change therefore requires an explicit baseline review instead of silently moving the reference.

Repeated evidence is stored under target/benchmark-results/evidence/. benchmarks/stability-policy.json requires the reports to come from the same clean source revision, host, toolchain, target, mode, and workload set. The generated stability-summary.json records the median absolute deviation and the full relative range for execution median, optimized compiler time, runtime compilation, and cold instantiation.

What is measured

Every workload records:

  • separate compiler process times and SHA-256 digests for raw and --release artifacts;
  • Wasm runtime compilation and cold instantiation time;
  • raw and Zstandard-compressed sizes for both artifacts;
  • warm execution samples plus minimum, median, mean, and maximum; and
  • peak live arena bytes, allocation count, completed reset count, and live bytes after a host call from a separate instrumented artifact; and
  • source and Wasm SHA-256 digests, tool versions, host OS and architecture, source revision, and dirty-worktree state.

The runner compiles the --release artifact twice and requires exact byte identity. It validates both raw and release Wasm and rejects imports in both, then executes the release artifact. A non-reproducible release artifact fails the run before timing begins.

The current corpus covers scalar loops, recursion, records, and a map/filter/fold collection pipeline. Each workload exports one scalar benchmark function and declares an expected checksum. The runner checks the result during warm-up and for every measured iteration. A wrong result fails the run instead of becoming a misleading fast measurement.

Frozen B0 workload subset

Cross-language work may use only the Restrict behavior exercised here until a later milestone deliberately expands the subset:

  • Int32 literals, arithmetic, comparisons, mutable locals, branches, and while loops;
  • monomorphic direct calls, scalar exports, and direct recursion;
  • concrete records whose benchmark-observed fields are Int32; and
  • List<Int32>, non-capturing scoped lambdas, and the current map/filter/fold paths.

The subset excludes host I/O, generic host exports, composite host ABI values, temporal features, async, WIT, and platform APIs. Passing the corpus freezes only these workload forms; it does not imply that every accepted language feature has a benchmark-stable lowering.

Each raw or release artifact is compiled in a separate compiler process. Runtime measurements use one freshly compiled and instantiated release module per workload, run the declared warm-up calls, and then time individual calls on that same instance. The median is the primary local comparison value; raw nanosecond samples remain in the JSON report so another summary can be calculated without rerunning the suite. Benchmark report schema 4 stores the timing artifacts under rawArtifact and optimizedArtifact, the memory probe under instrumentedArtifact, and its observations under memory. It also records exact runner, validator, encoder, compressor, Rust, and compiler-owned optimizer identities.

Target boundary

The suite compiles with:

--target wasm-core --emit wasm

The optimized artifact adds --release. The raw artifact remains the control measurement, while the release artifact is the executable used for runtime timing. A third artifact adds both --release and --instrument-memory. The runner resets its counters and executes two identical verified calls, requiring the same peak/allocation result, exactly one completed arena reset, and zero live bytes after each call. Because this bookkeeping changes generated code, the instrumented artifact is never used for runtime timing. External wasm-opt output is not part of the current baseline.

wasm-core artifacts must have no imports. Host output such as print or println requires --target wasip1 and is rejected in the benchmark target. The benchmark manifest also selects an explicit arena capacity per workload so collection tests are not limited by the former fixed 4 KiB capacity.

Selected allocation-heavy workloads also declare a deliberately undersized arena probe. That call must trap after recording arena error code 1, a non-zero requested allocation size, and the configured capacity. This verifies that exhaustion is explicit and attributable without making it a recoverable Restrict error.

This B0 slice records attributable raw and compiler-release measurements. GitHub CI enforces deterministic correctness, reproducible Wasm, artifact size, and memory observations. It does not establish a timing baseline. Timing is recorded locally on demand with mise run bench-evidence and remains informational; observed threshold failures stay in the summary instead of failing an unrelated compiler change.

Local timing and cross-language comparisons

Restrict does not require a dedicated or self-hosted benchmark runner at this stage. A timing report describes only the local session that produced it. Do not compare its absolute nanosecond values with a report from another machine, another day, or a materially different host state.

When comparing Restrict with another language, use one same-session local run:

  1. Pin every compiler, runtime, validator, optimizer, and compression tool.
  2. Use equivalent workload semantics, inputs, exported interfaces, optimization modes, and correctness oracles.
  3. Build and measure every implementation on the same machine during one time window. Record OS, CPU, architecture, source revisions, flags, and tool versions.
  4. Warm every implementation before sampling. Interleave the language order by workload, using a fixed rotation such as Restrict, Rust, Grain, MoonBit followed by its reverse, instead of finishing every Restrict run first.
  5. Keep every raw sample, including unfavorable results and outliers. Use the within-session median as the primary comparison and report dispersion.
  6. If any implementation, workload, toolchain, or optimization flag changes, rerun all comparison targets in a new shared session.

The separate cross-language harness must encode this protocol and pin its own toolchains before any public performance claim is made. Artifact hashes, sizes, checksums, and memory observations in this repository remain enforced even though local timing does not become a persistent regression gate.

Language Server Protocol

The compiler can run a Language Server Protocol server over stdio:

restrict_lang --lsp

Editor integrations should start that command as a stdio language server from the workspace where Restrict files live.

Current Role

The LSP is a development aid for source editing. It should be treated as a thin frontend over the compiler’s lexer, parser, and type checker rather than a separate language implementation. The language specification and compiler tests remain the source of truth.

The current server implements:

  • live lexer, parser, type, affine-use, import, and release-surface diagnostics
  • semantic tokens, hover, and document symbols
  • completion restricted to bindings and APIs available at the cursor, including import visibility, qualified enum variants, record fields, and receiver types
  • cross-file definitions and workspace references that preserve imported source URIs and ranges
  • reference CodeLens links on definitions
  • inlay hints for inferred binding, return, and lambda parameter types plus OSV call parameter names

Completion and definition requests traverse the active file’s import closure. References and CodeLens search .rl files under the Restrict workspace. Open documents override disk content, so navigation follows unsaved edits when the imported file is open.

Local Setup

Build the compiler first:

mise exec -- cargo build --release

Then point the editor at:

target/release/restrict_lang --lsp

During active compiler development, a debug build is also fine:

target/debug/restrict_lang --lsp

Troubleshooting

If the editor shows no diagnostics, check:

  • the compiler binary path is correct
  • the editor starts the server with stdio, not TCP
  • the workspace root contains the .rl files being edited
  • imported modules are saved under the same paths used by source imports
  • the same source parses with the CLI

Use the CLI to separate editor setup problems from compiler problems:

mise exec -- cargo run --bin restrict_lang examples/release_readiness.rl

WebAssembly Integration

Restrict lowers source programs to WebAssembly without depending on a garbage collector. The ordinary v0.0.1 path provides executable programs and scalar Core exports. The explicit B1 path additionally provides synchronous rich Components without changing that default ABI.

One Backend, Multiple Hosts

WebAssembly is Restrict’s sole code-generation target. A host profile selects imports, exports, adapters, and packaging without changing Restrict source semantics:

Restrict source
    |
    v
Core WebAssembly
    |
    +-- native WASI runtime
    +-- Component Model host
    +-- browser adapter
    +-- cloud or edge adapter      (planned)

Generated JavaScript may currently load a module or provide browser and cloud APIs. That code is host glue, not a JavaScript backend. Restrict does not need to compile source to JavaScript in order to run Wasm from JavaScript.

The current execution boundary is:

PathStatus
Import-free wasm-core compute modulesCurrent
wasip1 with basic WASI Preview 1 program importsCurrent and default
Browser execution through the playground’s JavaScript WASI bridgeCurrent
Full WASI 0.2 command-interface coverageSeparate host-profile milestone; not a v0.1.0 ABI blocker
Complete WASI networking and HTTP profilesFollow-on host integration after the v0.2.0 async adapter gate
Explicit B1 WIT and WebAssembly Component outputStable v0.1.0
Generated browser and cloud platform adaptersFuture
Direct portable DOM access from WasmNot currently standardized

Native WASI runtimes can execute a Wasm application without JavaScript. The browser case is different: the current WebAssembly Web API does not give a module direct access to the DOM or native browser UI, so a host adapter remains necessary. Restrict keeps that adapter separate so a future standardized host interface can replace it without introducing a new language backend.

Build Outputs

The native compiler emits text or validated binary WebAssembly directly:

restrict_lang --target wasip1 --emit wat app.rl
restrict_lang --target wasip1 --emit wasm app.rl
restrict_lang --target wasm-core --emit wasm compute.rl
restrict_lang --target wasm-core --emit wasm --release compute.rl

wasm-core emits no imports and rejects host output. wasip1 supplies the current fd_write-based output surface. Arena capacity defaults to 4096 bytes; larger allocation-heavy workloads can select an explicit capacity such as --arena-bytes 1048576.

The default output is deliberately raw and retains the complete generated module for debugging. --release runs this deterministic pipeline:

  1. lower the release-validated program to WAT using Checked IR for the current ABI authority;
  2. root reachability at function exports and the start entry;
  3. follow direct calls transitively, retaining table elements only when a reachable indirect call needs them;
  4. remove unreachable functions and function imports, then unused named types, globals, tables, and element segments; and
  5. encode and validate the selected WAT or binary Wasm output.

This pass is dead-code elimination, not an instruction optimizer. It does not yet perform inlining, constant folding on production bodies, or invoke an external wasm-opt. If Binaryen is evaluated later, its result will be an additional downstream artifact; the raw and compiler-release artifacts remain available so size and runtime effects are attributable.

Warder emits both text and binary Wasm. A default Warder project build also includes a local cage artifact. Warder requests the compiler release pass when build.optimize = true in the repository-root warder.toml (the default) or when warder build --release is used:

dist/<package-name>-<package-version>.wat
dist/<package-name>-<package-version>.wasm
dist/<package-name>-<package-version>.rgc

With an explicit [component] selection, plain warder build uses Component output. --component can be used as an explicit assertion:

warder build --component

publishes a transactional Component set:

dist/<package-name>-<package-version>.component.wasm
dist/<package-name>-<package-version>.component.wit
dist/<package-name>-<package-version>.component.toml

The emitted .component.toml is artifact metadata, not another project configuration file. The current Component path still requires a source-public declaration plus explicit [component] selection in warder.toml; a future pub/export source-first distinction is not implemented.

For the repository itself, the browser compiler is packaged with wasm-pack:

wasm-pack build --target web --out-dir web/pkg

The Pages assembly step copies that bundle to /compiler/pkg/ beside the mdBook output and blog.

Program Entry

Zero-argument main is the source-level program entry point:

fun main: () -> Int32 = {
    40 + 2
}

Generated WebAssembly keeps $main as a normal function with its source result type. When main takes no parameters, a no-result wrapper named $__restrict_start initializes the default arena, calls $main, drops any returned value, resets the arena, and is exported as _start. A parameterized function named main is still a normal function and does not emit _start.

That split matters:

  • Restrict source keeps main type-correct.
  • WASI-style program execution gets a conventional no-result _start for zero-argument main.
  • Tests and host wrappers can still reason about the real source result.

Use a separate scalar export when the host should call a function and observe a return value:

fun compute_score: () -> Int32 = {
    42
}

export fun exported_score: () -> Int32 = {
    () compute_score
}

Host ABI Surface

The v0.0.1 host-visible ABI supports concrete scalar values:

Restrict typeHost ABI
Int32i32
Int64i64
Float64f64
Booleani32 boolean
Chari32 code point
()no result or parameter payload

Public or exported functions should be monomorphic at the host boundary. A function that exposes String, records, lists, Option, Result, or a generic type parameter directly is rejected by v0.0.1 release-surface validation instead of receiving an unstable ad hoc ABI.

Composite values are still valid inside Restrict programs:

record Score {
    base: Int32,
    bonus: Int32
}

fun total: (score: Score) -> Int32 = {
    score.base + score.bonus
}

export fun exported_total: () -> Int32 = {
    val score = Score { base: 30, bonus: 12 };
    score |> total
}

The exported function is scalar even though the implementation uses a record.

Versioned Interoperability Direction

The ordinary v0.0.1 compatibility boundary remains scalar-only. Stable v0.1.0 implements a synchronous Component ABI for String, List, Array, records, Option, Result, user enums/variants, scalar-signature resources, value-capturing once-callables, and explicit concrete generic function instances. It generates or consumes WIT, performs Canonical ABI lift/lower, validates and composes Components, classifies compatibility, and executes through Rust bindings in a pinned runtime.

  • v0.2.0 adds the asynchronous boundary: async Component functions, future/stream, cancellation, and cleanup across suspension.

Neither version boundary makes Restrict’s arena representation public. The repository’s v0.1 scope document records the implemented contract and its intentional limits; this page summarizes the public boundary.

The compiler’s ordinary artifact path remains .rl -> WAT -> Core Wasm. With an explicit schema-v1/schema-v2 selection, warder build (or the explicit warder build --component assertion) transactionally publishes validated .component.wasm, normalized .component.wit, and .component.toml metadata. wrap --wit only attaches unverified caller-supplied WIT to a Core module cage and is not Component generation.

Interface authority follows API ownership. WASI, standard worlds, and third-party contracts are external-WIT-first whether Restrict consumes/imports or implements/exports them. Rich guest imports and scalar external implementation/export are implemented; rich external implementations and external-WIT resources fail closed. Explicit Restrict-owned Component exports are checked through ComponentInterfaceIr and generate normalized WIT; ordinary pub declarations are not implicit host exports. WIT output alone is not completion. The repository E2E gate covers Rust-produced Component -> Restrict consumer and Restrict-produced Component -> Rust consumer through WIT only. MoonBit remains a reference and optional external comparison, not a repository gate.

Memory Model

The post-v0.1.0 development backend treats every executing function, block, and callable body as a lifetime unit. Cursor checkpoints bound temporary allocations; type-directed scope-exit compaction preserves returned data and updates to enclosing mutable bindings. While and fold reclaim obsolete replacement state across repetitions. Physical arena storage is shared between scopes. Three reusable arena-sized regions hold compaction data and forwarding entries; they are reserved once per module, not once per scope.

The host entry initializes invocation storage and resets it on normal exit. Internal calls, recursion, and synchronous re-entry inherit the active arena and use frame-local checkpoints. Component adapters retain their existing Canonical ABI copying and resource-storage contracts. See Scope Lifetimes and Affine Use for the guarantees and limits; the published v0.1.0 binary predates this change.

Arena exhaustion remains a deliberate, non-recoverable Wasm trap. Before the trap, the module records a machine-readable cause in these compiler-owned exports:

ExportMeaning
__restrict_arena_error_code0 for none, 1 for exhaustion, 2 for allocation without an active arena
__restrict_arena_error_requested_bytessize of the allocation that failed
__restrict_arena_capacity_bytescapacity selected by --arena-bytes

A host may inspect the globals after a trap to classify the failure. It must not treat them as a source-level Result or resume the trapped call.

For benchmark diagnostics, --instrument-memory emits a separate instrumented module with __restrict_arena_peak_bytes, __restrict_arena_live_bytes, __restrict_arena_allocation_count, __restrict_arena_reset_count, __restrict_scope_exit_count, and the __restrict_memory_metrics_reset function. Peak and live counts exclude the arena header. The option adds bookkeeping, so performance measurements should time the ordinary --release artifact and use the instrumented artifact only for memory observations. Scope exits and physical arena resets have separate counters. Live and peak counts cover the active invocation arena, excluding reusable scratch storage and aggregate Component resource/boundary storage.

Treat the memory layout as compiler-owned implementation detail. Core hosts must not reach into record, string, list, Option, or Result representations. Use scalar Core wrappers or the explicit Component path.

Browser Compiler

The Pages site hosts the online compiler under /compiler/. The compiler is a wasm-pack web bundle backed by the same Rust crate:

site/dist/
├── docs/       mdBook output
├── compiler/   browser compiler UI and wasm-pack bundle
└── blog/       implementation notes

The compiler page accepts a ?code= query parameter, so docs and blog posts can open a source example directly in the browser. The mdBook theme adds “Try in Playground” buttons to complete restrict code blocks that contain fun main.

The playground also provides the generated program’s WASI Preview 1 imports from JavaScript so it can capture stdout and stderr. This is a browser host adapter around a Wasm program, not a second Restrict code-generation backend.

Deployment Environments

A WASI artifact should remain independent of its launcher and packaging:

  • Wasmtime and other native WASI runtimes are the JavaScript-free executable path for CLI, batch, server, plugin, and edge programs.
  • Docker, containerd shims, and runwasi are possible OCI packaging and execution layers. They do not define a Docker-specific Restrict ABI.
  • Cloudflare Workers can execute Wasm, but its general documented integration currently uses V8 and platform bindings. Restrict should use a generated adapter instead of treating Cloudflare as a portable WASI contract.
  • Browsers require a host adapter for DOM, events, Fetch, and other Web APIs until a portable direct Wasm interface is standardized and implemented.

Platform behavior evolves independently from the language. See the official WASI releases, Cloudflare Workers Wasm documentation, Docker alternative runtime documentation, and WebAssembly Web API for the current host surfaces.

Current Limits

These are intentional v0.0.1 boundaries, not accidental omissions:

  • exported generic functions are not host-visible
  • exported composite values do not receive a direct host ABI
  • current form dispatch is statically selected and monomorphized; there are no runtime form objects or dynamic dispatch ABI
  • forms and concrete record adoptions are source-module features and do not add a composite host ABI
  • Temporal Affine Types are outside the default release gate
  • WebAssembly Component Model and WIT are available only through the explicit B1 path; they do not widen ordinary v0.0.1 Core exports
  • synchronous WIT capability imports are part of v0.1.0 conformance; full WASI command coverage is a separate host profile
  • futures, streams, and generic async adapters target v0.2.0; complete network and HTTP profiles are follow-on host integration
  • direct browser DOM access is not part of the current WebAssembly host surface

See the v0.0.1 Release Surface for the normative release-facing table.

Language Interoperability

Restrict interoperability is WebAssembly-centered. The ordinary v0.0.1 Core boundary remains intentionally scalar. The explicit B1 path adds synchronous rich Component producer and consumer interoperability without exposing the compiler’s arena layout.

The compiler’s ordinary artifact path is .rl -> WAT -> Core Wasm. With a schema-v1 or schema-v2 [component] selection in the repository-root warder.toml, warder build (or the explicit --component assertion) transactionally publishes .component.wit, validated .component.wasm, and .component.toml metadata. wrap --wit only attaches caller-supplied text to a Core module cage and is not Component generation.

Versioned Interoperability Direction

The ordinary v0.0.1 compatibility boundary remains scalar-only. Stable v0.1.0 implements String, List, Array, records, Option, Result, enums/variants, scalar-signature resources, value-capturing once-callables, and concrete generic function instances. It generates and consumes WIT, performs Canonical ABI lift/lower, validates and composes Components, classifies compatibility, and executes through Rust bindings.

  • v0.2.0 adds the asynchronous boundary: async component functions, future/stream, cancellation, and cleanup across suspension.

Neither version boundary makes Restrict’s arena representation public. The repository’s v0.1 scope document records the implemented contract and its intentional limits; this page summarizes the public boundary.

Interface authority follows API ownership. WASI, standard worlds, and third-party contracts are external-WIT-first whether Restrict consumes/imports or implements/exports them. Rich guest imports and scalar external implementation/export are implemented; rich external implementations and external-WIT resources fail closed. Explicit Restrict-owned component exports are checked through ComponentInterfaceIr and generate normalized WIT; ordinary pub declarations are not implicit host exports. Normalized WIT and stable ABI metadata form the compatibility contract, but WIT output alone is not the B1 gate; adapters, validation, composition, lifecycle, diffing, and runtime calls are included.

Repository E2E requires independently built Rust-produced Component -> Restrict consumer and Restrict-produced Component -> Rust consumer paths, connected only through WIT and the Canonical ABI. MoonBit remains a design precedent and optional external comparison, not a repository release toolchain.

JS/TS bindings and Worker loaders are optional host-adapter work, not B1 gates. Full WASI 0.2 command/network/HTTP coverage and async/future/stream belong to separate host-profile and v0.2 work.

Host Profiles, Not Language Backends

Restrict source always compiles to WebAssembly. WASI, browser, cloud/edge, and container environments provide different host imports and packaging around the same backend. JavaScript emitted for a browser or Worker entry point is an adapter; Restrict does not need a JavaScript code-generation backend.

Keep platform operations behind explicit imports and capabilities. A future WIT or browser host interface should be able to replace today’s adapter without changing ordinary Restrict calls or the internal arena representation.

Calling Restrict From A Host

For ordinary Core Wasm, expose host-callable functions with scalar monomorphic pub fun or export fun declarations:

fun adjust: (value: Int32) -> Int32 = {
    value + 1
}

export fun exported_adjust: (value: Int32) -> Int32 = {
    value |> adjust
}

The exported function can be called from a Core WebAssembly host using the normal scalar ABI. Keep rich values internal or convert them to scalar summaries on this path.

For rich interoperability, explicitly select the public function under [component] in the root warder.toml and run warder build (or warder build --component when the selection must be asserted). Ordinary pub or export alone never publishes a Component ABI. A future edition may distinguish package-visible pub from Component-intent export, but that source-first surface is not implemented. Schema v2 is root-only and adds resources, once-callables, and explicit generic function instances. The resulting WIT is the only contract shared with an independent Rust consumer.

Program Execution

For program-style execution, define main:

fun main: () -> Int32 = {
    42
}

When main takes no parameters, the generated module exports _start as a no-result wrapper around $main. That wrapper initializes the default arena, calls $main, drops any returned value, and resets the arena. If a host needs the result, add a separate scalar export.

Browser Compiler

The online compiler uses wasm-pack and wasm-bindgen to expose compiler entry points to JavaScript:

wasm-pack build --target web --out-dir web/pkg

The web UI can compile a single source string and display WAT, tokens, AST, and diagnostics. It is an interop example for the compiler itself, not a promise that every Restrict program has a JavaScript ABI for composite values.

The same distinction applies to other hosts. A Cloudflare Workers adapter may translate request and response values to the platform runtime, while a native WASI host may expose standard component interfaces. Neither path changes the Restrict language backend.

Imports

Source imports are for Restrict modules:

import examples.math.{double}

String import paths, aliases, re-exports, and source-level host module declarations are outside v0.0.1. External-WIT guest imports use the explicit B1 compiler path rather than this source-module syntax.

Practical Boundary Pattern

Use scalar wrappers:

record Reading {
    value: Int32,
    limit: Int32
}

fun is_over_limit: (reading: Reading) -> Boolean = {
    reading.value > reading.limit
}

export fun exported_over_limit: (value: Int32, limit: Int32) -> Boolean = {
    val reading = Reading { value: value, limit: limit };
    reading |> is_over_limit
}

This lets internal Restrict code use records while the host sees only scalar parameters and results.

Performance Tips

Restrict is designed for deterministic WebAssembly output, affine ownership, and no WebAssembly GC dependency. v0.0.1 performance guidance is therefore mostly about keeping ownership clear, avoiding unstable host ABI assumptions, and writing examples the compiler can lower predictably.

Keep Host Boundaries Scalar

Scalar exports are the stable host-facing path:

export fun exported_score: (base: Int32, bonus: Int32) -> Int32 = {
    base + bonus
}

When a computation needs records or lists, build them inside the function and return a scalar summary. That avoids depending on an unfinished composite host layout.

Prefer Straight Pipelines

OSV pipelines keep data flow explicit:

fun normalize: (score: Int32) -> Int32 = {
    score > 100 then {
        100
    } else {
        score
    }
}

fun add_bonus: (score: Int32) -> Int32 = {
    score + 5
}

fun main: () -> Int32 = {
    96 |> add_bonus |> normalize
}

For multi-argument operations, use grouped OSV calls so evaluation stays obvious:

fun weighted: (score: Int32, weight: Int32) -> Int32 = {
    score * weight
}

fun main: () -> Int32 = {
    (21, 2) weighted
}

Destructure Records Once

Records are affine values. If multiple fields are needed, destructure once instead of repeatedly accessing the same record:

record Reading {
    value: Int32,
    weight: Int32
}

fun weighted_reading: (reading: Reading) -> Int32 = {
    val Reading { value, weight } = reading;
    value * weight
}

This also makes ownership intent clearer to readers and tests.

Give Ambiguous Values Context

Empty lists, Option::None, Result::Ok, and Result::Err often need expected type context:

fun empty_scores: () -> List<Int32> = {
    []
}

fun no_score: () -> Option<Int32> = {
    () Option::None
}

Supplying the context early reduces inference work and improves diagnostics.

Build Modes

For compiler development:

mise exec -- cargo build
mise exec -- cargo test

For the browser compiler:

wasm-pack build --target web --out-dir web/pkg

For Pages:

mdbook build docs
wasm-pack build --target web --out-dir web/pkg
bash scripts/build-pages.sh

Current Non-Goals

Do not write performance-sensitive code that depends on:

  • direct host access to composite memory layout
  • WebAssembly Component Model lowering
  • WIT-generated adapters
  • Temporal Affine Type cleanup
  • source- or host-stable user enum tag and payload layout

Those areas are reserved for later design and should not be treated as current performance contracts.

Examples

These examples are small, self-contained v0.0.1 programs. They avoid host stdin, filesystem access, networking, Temporal Affine Types, and composite host exports.

Scalar Pipeline

fun add_bonus: (base: Int32, bonus: Int32) -> Int32 = {
    base + bonus
}

fun clamp: (score: Int32) -> Int32 = {
    score > 100 then {
        100
    } else {
        score
    }
}

fun main: () -> Int32 = {
    (96, 7) add_bonus |> clamp
}

Record Computation

Use records internally and expose scalar summaries when crossing the host boundary.

record ReleaseCheck {
    tests: Int32,
    failures: Int32
}

fun passed_tests: (check: ReleaseCheck) -> Int32 = {
    val ReleaseCheck { tests, failures } = check;
    tests - failures
}

export fun exported_passed_tests: () -> Int32 = {
    val check = ReleaseCheck { tests: 42, failures: 2 };
    check |> passed_tests
}

Option Handling

fun score_or_default: (score: Option<Int32>) -> Int32 = {
    score match {
        Some(value) => { value }
        None => { 0 }
    }
}

fun main: () -> Int32 = {
    42 Option::Some |> score_or_default
}

() Option::None often needs type context from a function parameter, return type, annotation, or sibling branch.

Result Handling

fun checked_divide: (left: Int32, right: Int32) -> Result<Int32, String> = {
    right == 0 then {
        "division by zero" Result::Err
    } else {
        (left / right) Result::Ok
    }
}

fun result_or_zero: (value: Result<Int32, String>) -> Int32 = {
    value match {
        Ok(result) => { result }
        Err(message) => { 0 }
    }
}

fun main: () -> Int32 = {
    (84, 2) checked_divide |> result_or_zero
}

Custom Enum Error In Result

This example uses the closed enum slice included in v0.0.1: a non-generic, non-recursive declaration, qualified OSV construction, and exhaustive matching. Running it prints -2.

enum CustomError {
    Empty
    Invalid(String)
}

fun decode: (code: Int32) -> Result<Int32, CustomError> = {
    code == 0 then {
        42 Result::Ok
    } else {
        "invalid code" CustomError::Invalid Result::Err
    }
}

fun collapse: (result: Result<Int32, CustomError>) -> Int32 = {
    result match {
        Ok(value) => { value }
        Err(error) => {
            error match {
                CustomError::Empty => { -1 }
                CustomError::Invalid(message) => { -2 }
            }
        }
    }
}

fun main: () -> () = {
    1 |> decode |> collapse |> print_int
}

pub enum can expose the enum namespace to another Restrict source module, but there is no direct host enum ABI. Generic and recursive enums and postfix ? propagation remain future work.

Lambda Context

Lambdas infer parameter types from the expected function type:

fun apply_int: (f: Int32 -> Int32, value: Int32) -> Int32 = {
    value |> f
}

fun main: () -> Int32 = {
    (|value| value + 1, 41) apply_int
}

When no expected type exists, annotate the lambda parameter:

fun main: () -> Int32 = {
    val bump = |value: Int32| value + 1
    41 |> bump
}

Host Export Wrapper

main is for program execution. Add a separate scalar export when a host needs to call a function and read its return value:

fun compute_score: () -> Int32 = {
    42
}

export fun exported_score: () -> Int32 = {
    () compute_score
}

fun main: () -> Int32 = {
    () compute_score
}

FAQ

Is Restrict production-ready?

Not yet. The documentation targets a focused v0.0.1 release surface. It is useful for compiler development, language experiments, WebAssembly examples, and release-surface validation, but several major design areas remain reserved.

Why does Restrict reject function(args)?

Restrict is OSV-only. Put the value or argument tuple first:

value |> function
(left, right) combine
() make_default

This rule is strict so examples, diagnostics, and generated code all use the same call shape.

Why does main return get dropped during execution?

main keeps its source result type in generated WebAssembly, but program-style execution uses a no-result _start wrapper only when main takes no parameters. The wrapper initializes the default arena, calls $main, drops any returned value, and resets the arena.

If a host needs a return value, expose a separate scalar pub fun or export fun.

Can I export strings or records to JavaScript?

Not directly in v0.0.1. Host-visible exports are limited to scalar monomorphic values: Int32, Int64, Float64, Boolean, Char, and ().

Use records, strings, lists, Option, and Result internally, then export a scalar wrapper while the composite host ABI is still being designed.

Does browser support require a JavaScript backend?

No. Restrict source continues to compile to WebAssembly. JavaScript can load the Wasm module and provide DOM, Fetch, event, or platform imports as a thin host adapter. That adapter may eventually be generated by Restrict tooling; it is not a second language backend.

Can a Restrict application run without JavaScript?

Yes, within the current boundary. Generated programs use basic WASI Preview 1 imports and can be hosted by a native WASI runtime. Full command applications still need documented bindings for arguments, standard input, environment, filesystem, clocks, and related capabilities.

Browsers do not currently expose the DOM directly to Wasm, so Web UI programs still need a host adapter. Docker and containerd may package and execute a WASI artifact, but do not define a separate Restrict target or ABI.

Are Temporal Affine Types included?

No. Temporal Affine Types are planned and reserved, but they are outside the default v0.0.1 gate.

Are user-defined enums supported?

Yes, in the v0.0.1 compiler. The supported slice is closed, non-generic, and non-recursive; variants have zero or one payload and use qualified Type::Variant constructors and exhaustive patterns. A custom enum can be the error in Result<T, CustomError>.

pub enum is source-module-only and creates no host enum ABI. Generic or recursive enums and postfix ? propagation are not implemented yet.

What should documentation examples use?

Use:

val value = 42
mut val counter = 0
value |> function
(left, right) combine
RecordName { field: value }

Avoid:

let value = 42
val mut counter = 0
function(value)
RecordName { field = value }

Where should I start?

Read the Quick Start, then the Language Guide. Use the Online Compiler for short examples and the local CLI/Warder flow for project builds.

はじめに

Restrict Languageへようこそ — メモリ安全性と最適なパフォーマンスを保証するアフィン型システムを備えた、WebAssembly向けのモダンなプログラミング言語です。

Restrict Languageとは?

Restrict Languageは、以下のユニークな特徴を持つ静的型付けコンパイル言語です:

  • 日本語の構文に着想を得たOSV(目的語-主語-動詞)語順
  • 各値が最大1回しか使用されないことを保証するアフィン型システム
  • 修飾されたバリアントと網羅的なmatchを持つ閉じたユーザー定義enum
  • form、具体recordのtakes、of境界による静的ポリモーフィズム
  • scalarと明示的に採用したrecordに対するDisplay出力
  • freezeとclone操作を持つプロトタイプベースのレコード
  • ガベージコレクタを持たないWebAssemblyファースト設計
  • WebAssemblyコンポーネントモデルとWITによる相互運用性

核となる哲学

名前1つ = 実体1つ

Restrict Languageでは、すべてのバインディングが単一の一意な実体を表します。この原則がアフィン型システムを駆動し、予測可能なリソース管理を実現し、use-after-moveやデータ競合などの一般的なプログラミングエラーを防ぎます。

// 各値には単一の所有者がいます
val x = "owned"
val y = x  // xはyに移動されます
// ここではxはもうアクセスできません

GCなしでのメモリ安全性

アフィン型と明示的なメモリ管理を活用することで、Restrict Languageはガベージコレクションのオーバーヘッドなしにメモリ安全性を実現します。これにより以下の用途に最適です:

  • 高性能WebAssemblyアプリケーション
  • リソース制約のある環境
  • リアルタイムシステム
  • ブロックチェーンとスマートコントラクト

主要機能

1. OSV構文

日本語文法に着想を得て、Restrict Languageは目的語-主語-動詞の順序を使用します:

// Restrict: value |> function

"Hello, World!" |> println
val numbers: List<Int32> = [1, 2, 3]
val doubled = (numbers, |x| x * 2) map

2. アフィン型

各値は最大1回しか参照できず、エイリアシングバグを防ぎます:

fun consume: (x: String) -> () = {
    x |> println
}

fun main: () = {
    val msg = "Hello";
    msg |> consume
    // msgはここでは使用できません
}

3. 閉じたユーザー定義enum

v0.0.1 compilerでは、非ジェネリックかつ非再帰のenumを定義できます。各バリアントはpayloadなし、または1つのpayloadを持ち、名前は必ず型名::バリアント名で修飾します。構築もOSV語順です。

enum ParseError {
    Empty
    Message(String)
}

fun fail: (message: String) -> Result<Int32, ParseError> = {
    (message |> ParseError::Message) Result::Err
}

fun error_code: (error: ParseError) -> Int32 = {
    error match {
        ParseError::Empty => { 1 }
        ParseError::Message(message) => { 2 }
    }
}

payloadなしの値は() ParseError::Emptyのように構築します。matchはすべてのバリアントを扱う必要があります。pub enumはRestrictソースモジュール間で公開できますが、ユーザー定義enumを直接渡すhost-visible WebAssembly ABIはまだありません。エラー伝播はmatchで明示し、?演算子は未実装です。

v0.0.1にはユーザー定義enumとsource-level formが含まれます。この節とForm と静的ポリモーフィズムは、その公開範囲を説明しています。

4. プロトタイプベース継承

クラスの代わりに、Restrictは明示的なクローンとフリーズを持つプロトタイプを使用します:

record Car {
    wheels: Int32
    color: String
}

fun main: () = {
    val base_car = Car { wheels: 4, color: "未設定" }
    val my_car = base_car.clone { color: "赤" }
    val frozen_car = my_car freeze;
    frozen_car
}

5. WebAssembly統合

Restrictは以下のファーストクラスサポートを持つWebAssemblyに直接コンパイルされます:

  • WASI(WebAssemblyシステムインターフェース)
  • コンポーネントモデル
  • WIT(WebAssemblyインターフェースタイプ)
  • 言語間相互運用性

はじめよう

準備はできましたか?以下から始めましょう:

  1. インストール - 開発環境のセットアップ
  2. Hello World - 最初のRestrictプログラムを書く
  3. Warderパッケージマネージャー - パッケージ管理について学ぶ

サンプルプログラム

Restrict Languageの雰囲気を味わってください:

// アフィン型を持つ関数を定義
fun greet: (name: String) -> String = {
    "こんにちは、" + name + "さん!"
}

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

// メインエントリポイント
fun main: () = {
    val name = "世界"
    val message = name |> greet;
    message |> println

    val total = (20, 22) add;
    total |> print_int
}

なぜRestrict Language?

  • パフォーマンス: ゼロコスト抽象化とGCオーバーヘッドなし
  • 安全性: アフィン型がコンパイル時に一般的なメモリバグを防ぐ
  • シンプルさ: 関数型プログラミングに着想を得た明確な構文
  • 相互運用性: 既存のWebAssemblyエコシステムとのシームレスな統合
  • モダンなツール: 組み込みパッケージマネージャー、LSPサポート、VS Code拡張

WebAssemblyプログラミングの未来を一緒に築きましょう!

インストール

v0.0.1はGitHub Releasesから配布し、ソースからもビルドできます。パッケージレジストリ、安定版Homebrew formula、VS Code Marketplaceは今回のリリースには含めません。

リリースバイナリをインストール

シェルインストーラーはx86-64 Linux、Intel Mac、Apple Silicon Macに対応し、ダウンロードしたアーカイブをSHA-256マニフェストで検証します。

curl --proto '=https' --tlsv1.2 -fsSL \
  https://raw.githubusercontent.com/Ischca/restrict_lang/main/install.sh | bash

表示された$HOME/.restrict-lang/binをPATHに追加してください。WindowsではGitHub Releaseのzipを直接ダウンロードします。

システム要件

  • Rust(ソースからビルドする場合)
  • mise(このリポジトリの開発コマンドで使用)
  • Git
  • テキストエディタ(VS Codeなど)

ソースからビルド

git clone https://github.com/Ischca/restrict_lang.git
cd restrict_lang
mise exec -- cargo build --workspace --release

ビルド後、コンパイラとWarderをPATHに追加します:

export PATH="$PWD/target/release:$PATH"

ワークスペースビルドではtarget/releaseにrestrict_langとwarderの両方が生成されます。

インストールの確認

restrict_lang --version
warder --version
restrict_lang --help
warder --help

WebAssemblyランタイム

warder runで生成済みWASMを実行するには、wasmtimeまたはwasmerが必要です。

curl https://wasmtime.dev/install.sh -sSf | bash

基本コマンド

コンパイラを直接使う場合:

restrict_lang hello.rl hello.wat
restrict_lang --check hello.rl

Warderでプロジェクトを扱う場合:

warder new my-project
cd my-project
warder build
warder run
warder test
warder doctor

warder buildの既定出力はdist/<name>-<version>.wat、dist/<name>-<version>.wasm、dist/<name>-<version>.rgcです。

開発用コマンド

このリポジトリで開発する場合、Cargoコマンドはmise exec --経由で実行します:

mise exec -- cargo build
mise exec -- cargo test
mise exec -- cargo run --bin restrict_lang -- hello.rl hello.wat

用意されているmiseタスクも利用できます:

mise run build
mise run test
mise run fmt
mise run lint
mise run ci

IDE設定

Language Server Protocol(LSP)対応エディタでは、次のコマンドをstdioの言語サーバーとして設定できます:

restrict_lang --lsp

トラブルシューティング

コマンドが見つからない

PATHにビルド成果物のディレクトリが含まれていることを確認してください:

export PATH="$PWD/target/release:$PATH"
which restrict_lang
which warder

ビルドに失敗する

Rustとmiseが利用できることを確認し、ワークスペースルートでビルドしてください:

rustc --version
mise --version
mise exec -- cargo build --workspace --release

WASMを実行できない

warder runはwasmtimeまたはwasmerを探します。どちらかをインストールしてPATHに含めてください。

次のステップ

Hello, World!

最初の Restrict Language プログラムを書きましょう。このページのコードブロックは、v0.0.1 の current surface に合わせた例です。

ファイルの作成

作業用ディレクトリに hello.rl を作成します。

// 最初の Restrict Language プログラム
fun main: () -> () = {
    "Hello, World!" |> println
}

このプログラムの構成要素は次のとおりです。

  1. fun main: () -> () = { ... } は引数なしで unit を返すエントリーポイントです。
  2. "Hello, World!" は文字列リテラルです。
  3. |> は値を左から右へ渡す OSV パイプ演算子です。
  4. println は標準出力へ文字列を出力する現在の標準ライブラリ関数です。

実行

リポジトリ内で試す場合は、コンパイラを直接実行できます。

mise exec -- cargo run --bin restrict_lang hello.rl

出力は次のようになります。

Hello, World!

OSV 構文

Restrict Language は Object-Subject-Verb の語順を使います。引数は関数名の前に置きます。

// 単一引数
"Hello, World!" |> println

// 複数引数
(10, 20) add

Rust や JavaScript のように関数名を先に書く呼び出し形式は、v0.0.1 の Restrict 構文ではありません。

少し拡張する

fun greet: (name: String) -> () = {
    "Hello, " + name + "!" |> println
}

fun main: () -> () = {
    "Restrict" |> greet
}

文字列結合には現在の文字列演算である + を使います。

アフィン型の基本

Restrict の値は、基本的に最大 1 回だけ使えます。

fun main: () -> () = {
    val message = "このメッセージは一度だけ使えます";

    message |> println

    // もう一度使うと、アフィン型チェックでエラーになります。
    // message |> println
}

同じ束縛を複数回使う必要がある場合は、明示的に可変束縛にします。

fun main: () -> () = {
    mut val greeting = "Hello";

    greeting |> println;
    greeting |> println
}

関数を分ける

fun greeting_word: (hour: Int32) -> String = {
    hour < 12 then {
        "おはよう"
    } else {
        hour < 18 then {
            "こんにちは"
        } else {
            "こんばんは"
        }
    }
}

fun greet_with_time: (name: String, hour: Int32) -> () = {
    val word = hour |> greeting_word;
    word + "、" + name + "さん!" |> println
}

fun main: () -> () = {
    ("Taro", 9) greet_with_time
    ("Yuki", 15) greet_with_time
    ("Hana", 20) greet_with_time
}

複数引数の関数は、タプルを関数名の前に置いて呼び出します。

Result の基本

ファイル I/O などの実用 API はまだ v0.0.1 の current standard-library surface ではありません。エラー処理の形は、現在の構文では次のように Result と match で表します。

fun greeting_for_hour: (hour: Int32) -> Result<String, String> = {
    hour < 0 then {
        "時刻が不正です" Result::Err
    } else {
        "Hello from Restrict" Result::Ok
    }
}

fun main: () -> () = {
    val result = 9 |> greeting_for_hour;

    result match {
        Ok(message) => { message |> println }
        Err(error) => { error |> println }
    }
}

v0.0.1 ではまだ current example ではないもの

次の内容は将来の標準ライブラリやツール設計で扱う予定です。このページでは、v0.0.1 の現在のコード例としては示しません。

  • 標準入力を読む対話プログラム
  • ファイルを読み書きするチュートリアル
  • テスト属性や専用テストハーネス
  • 標準ライブラリの集約 import

次のステップ

  1. OSV語順ガイド - パイプ演算子をマスター
  2. 型システム - アフィン型を深く理解
  3. Warderガイド - 依存関係の管理を学ぶ

構文リファレンス

このガイドは、v0.0.1 の公開構文と、意図的に範囲外としている将来構文を区別して説明します。

コメント

// 単一行コメント

/*
   複数行コメント
*/

識別子とキーワード

識別子は文字またはアンダースコアで始まり、その後に文字、数字、またはアンダースコアが続きます。

val valid_name = 1
val _private = 2
val camelCase = 3
val snake_case = 4
val number123 = 5

予約キーワードは次のとおりです。予約済みであっても、関連するすべての構文が v0.0.1 で実装済みとは限りません。

fun
val
mut
record
context
enum
match
then
else
while
temporal
within
where
clone
freeze
pub
import
export
as
fatal
true
false
Some
None
with
lifetime
await
spawn

リテラル

val decimal = 42
val hex = 0xFF
val with_underscores = 1_000_000

val float_value = 3.14
val scientific = 2.5e-10

val simple = "Hello, World!"
val escaped = "Line 1\nLine 2\tTabbed"

val letter = 'a'
val newline = '\n'

val yes = true
val no = false
val unit_value = ()

バイナリ・8進数リテラル、生文字列、複数行文字列は、このページでは v0.0.1 の current example として扱いません。

変数と束縛

val x = 42
val y: Int32 = 42
val pi: Float64 = 3.14

mut val counter = 0;
counter = counter + 1

不変束縛は val、複数回の使用や再代入が必要な束縛は mut val を使います。

式の境界

改行は空白として扱われるため、直接 OSV 式は次の行へ継続できます。一方、 動詞になれない値が続く場合は、セミコロンなしでも新しい式が始まります。

"first" println
"second" println

ローカル束縛の直後に識別子から始まる式を置き、それを束縛値の動詞として 解釈させたくない場合は ; で境界を明示します。

val message = "ready";
message println

高階変換の内側だけで名前が必要なら、スコープ動詞節のラムダ引数を使うと、 流れをセミコロンなしで表せます。

values map { |value|
    value + 1
}

基本式

val sum = 1 + 2
val difference = 5 - 3
val product = 4 * 3
val quotient = 10 / 2
val remainder = 7 % 3

val equal = x == y
val not_equal = x != y
val less = x < y
val greater = x > y
val less_eq = x <= y
val greater_eq = x >= y

val and_result = true && false
val or_result = true || false
val not_result = !true

べき乗、ビット演算、シフト演算は、v0.0.1 の current examples からは外しています。

条件式

Restrict は then と else を使います。

val label = score >= 80 then {
    "pass"
} else {
    "retry"
}

val greeting = hour < 12 then {
    "おはよう"
} else {
    hour < 18 then {
        "こんにちは"
    } else {
        "こんばんは"
    }
}

match 式

match は値の後ろに置きます。

val description = number match {
    0 => { "ゼロ" }
    1 => { "一" }
    _ => { "その他" }
}

val unwrapped = maybe_value match {
    Some(value) => { value }
    None => { 0 }
}

パターンには、ワイルドカード、変数束縛、リテラル、Some、None、リスト、レコード、修飾されたenumバリアントが使えます。

val first_or_zero = values match {
    [] => { 0 }
    [head | tail] => { head }
}

val label = point match {
    Point { x: 0, y: 0 } => { "origin" }
    Point { x, y } => { "point" }
}

ガード付きパターン、範囲パターン、テスト専用属性は、v0.0.1 の current examples としては扱いません。

リストとレコード

val numbers = [1, 2, 3]
val empty_numbers: List<Int32> = []

record Point {
    x: Int32
    y: Int32
}

val origin = Point { x: 0, y: 0 }

レコード定義とレコードリテラルのフィールドは : を使います。

ユーザー定義enum

現在のcompilerでは、閉じたユーザー定義enumを宣言できます。

enum ParseError {
    Empty
    Message(String)
}

fun empty_error: () -> ParseError = {
    () ParseError::Empty
}

fun message_error: (message: String) -> ParseError = {
    message |> ParseError::Message
}

バリアント名は常にParseError::Emptyのように型名::バリアント名で修飾します。payloadなしのコンストラクタはunitを受け取り、payloadありのコンストラクタは宣言された型の値を1つだけ受け取ります。どちらも直接のOSV呼び出し対象であり、ParseError::Message("error")のような従来順の呼び出しは使えません。

現在のenum宣言は非ジェネリックかつ非再帰で、各バリアントが持てるpayloadは0個または1個です。複数の値をまとめたい場合はrecordを1つのpayloadにします。

関数

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun answer: () -> Int32 = {
    42
}

fun identity: <T>(value: T) -> T = {
    value
}

関数呼び出しは OSV 構文だけです。引数が先、関数名が後です。

val total = (10, 20) add
val doubled = 21 |> double
val known = () answer

ラムダ式と関数型

val add_one = |x: Int32| x + 1
val multiply = |x: Int32, y: Int32| x * y

val transformer: Int32 -> Int32 = |x: Int32| x * 2
val reducer: (Int32, Int32) -> Int32 = |left: Int32, right: Int32| left + right

スコープ動詞節

最後に残った仮引数が関数型である動詞は、その関数をスコープとして 開けます。

val shifted = values map {
    it + 1
}

val total = (shifted, 0) fold { |sum, value|
    sum + value
}

ヘッダーのない形式は文脈的なit束縛を1つ導入します。明示スコープの ヘッダーはラムダのバインダーを再利用します。完成したスコープ節は、 後続の節やパイプより先に評価されます。

コールバック形式、コレクション動作、型推論、アフィンなキャプチャは 高階関数とコレクション変換を参照してください。

型

基本型

Int32
Int64
Float64
String
Char
Boolean
()

ジェネリック型

val maybe_score: Option<Int32> = 100 Option::Some
val no_score: Option<Int32> = () Option::None

val success: Result<Int32, String> = 42 Result::Ok
val failure: Result<Int32, String> = "error" Result::Err

List<T>、Array<T, N>、Option<T>、Result<T, E> は仕様上のジェネリック型です。Range<Int32> は v0.0.1 で Int32 の開始値と終了値だけを扱う組み込みコレクション型です。

インポート

v0.0.1 の import は、ソースモジュールの dotted path だけを扱います。

import release.policy.{score}
import release.policy.*
import release.policy

文字列パス、別名付き import、再 export、標準ライブラリ集約 import は、今後のモジュール設計で扱います。

pub 宣言

pub fun public_score: (input: Int32) -> Int32 = {
    input
}

pub record PublicPoint {
    x: Int32
    y: Int32
}

pub enum PublicError {
    Missing
    Invalid(String)
}

v0.0.1 では、export されたレコードや generic 関数はソースレベルのモジュールメタデータです。v0.0.1のpub enumもRestrictソースモジュール間だけの公開で、直接のhost-visible WebAssembly enum ABIは提供しません。

context と with

context Request {
    user: String
    trace_id: String
}

with Request { user: "alice", trace_id: "req-1" } {
    "request accepted" |> println
}

関数宣言に context を注入する注釈構文は、v0.0.1 の current example ではありません。

clone と freeze

record Settings {
    retries: Int32
    timeout: Int32
}

val base = Settings { retries: 3, timeout: 10 } freeze
val strict = base.clone { timeout: 3 }

演算子の優先順位

  1. フィールドアクセス、修飾されたバリアント名、グループ化された直接OSV呼び出し、スコープ動詞節: .field、.clone、Type::Variant、freeze、(value) f、() f、values map { ... }
  2. 単項演算子: !、-
  3. 乗除余: *、/、%
  4. 加減: +、-
  5. 比較: <、<=、>、>=
  6. 等価: ==、!=
  7. 論理 AND: &&
  8. 論理 OR: ||
  9. パイプ: |>

現在のenum境界

v0.0.1 compilerは上記の閉じたユーザー定義enumをサポートします。ジェネリックenum、再帰enum、1バリアントに複数の直接payloadを持たせる構文、host enum ABIは将来の設計対象です。Result<T, E>のエラー伝播はmatchで明示し、?演算子はまだ使えません。

v0.0.1 の current example ではない構文

次の項目は予約済み、実験中、または将来の設計対象です。公開ドキュメントで current Restrict のコード例として扱う場合は、実装状況を確認してください。

  • temporal affine types と lifetime scope
  • TAT cleanup
  • associated type、generic form、default method、generic/conditional/enum adoption
  • derive、属性、dynamic dispatch
  • ループラベルと範囲パターン
  • パッケージ単位の標準ライブラリ集約 import
  • メソッド呼び出し形式の通常関数
  • 可変パイプ演算子

まとめ

v0.0.1 の Restrict は、val、mut val、OSV 呼び出し、明示的な fun name: (...) -> Type = { ... } 構文、dotted source import を中心にしています。迷った場合は、必ず /LANGUAGE_SPECIFICATION.md を優先してください。

OSV語順

Restrict Languageの関数呼び出しは、v0.0.1ではOSV(目的語-主語-動詞)語順だけを使います。値や引数を先に書き、その後に関数名を書きます。

OSVとは?

OSVは以下を表します:

  • Object(目的語)- 操作されるデータ
  • Subject(主語)- 関数または演算子
  • Verb(動詞)- アクションまたは適用

Restrict Languageでは、単一引数はパイプ、複数引数はタプルで表します。

value |> function
(first, second) combine

関数名を先に置く呼び出しや、オブジェクト風のメソッド呼び出しはv0.0.1の現在の構文ではありません。

基本的な使用法

単一引数関数

単一引数の関数には|>を使います:

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun increment: (x: Int32) -> Int32 = {
    x + 1
}

fun main: () = {
    val result1 = 21 |> double
    val result2 = 41 |> increment;

    result1 |> print_int;
    result2 |> print_int
}

複数引数関数

複数引数の関数には、引数をタプルとして先に置きます:

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

fun multiply: (x: Int32, y: Int32) -> Int32 = {
    x * y
}

fun main: () = {
    val sum = (5, 10) add
    val product = (3, 4) multiply
    val total = (sum, product) add;
    total |> print_int
}

関数合成

OSVの連鎖では、データフローが左から右へ進みます:

fun increment: (x: Int32) -> Int32 = {
    x + 1
}

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun square: (x: Int32) -> Int32 = {
    x * x
}

fun main: () = {
    val result = 5
        |> increment
        |> double
        |> square;

    result |> print_int
}

スコープ動詞節

最後の引数に関数を受け取る動詞は、その関数本体を型付きスコープとして 開けます。通常の目的語は動詞より前に置かれ、完成した節全体が次の動詞の 目的語になります。

fun main: () -> Int32 = {
    val numbers: List<Int32> = [1, 2, 3, 4]
    val doubled = numbers map {
        it * 2
    } filter {
        it > 2
    }
    (doubled, 0) fold { |total, number|
        total + number
    }
}

ヘッダーのない単項スコープには、文脈的な束縛itが1つ導入されます。 名前を明示したい場合や複数引数のコールバックでは、既存ラムダの バインダーをスコープ先頭で使います。

values map { |value|
    value + 1
}

これらのスコープは通常ラムダと同じ型推論・アフィン検査を通ります。 暗黙itを使うスコープの入れ子は認められないため、少なくとも片方の バインダーを明示してください。

パイプ演算子との併用

途中で複数引数の関数を使う場合は、必要な値をいったん束縛してタプル呼び出しに戻します:

fun normalize: (value: Int32) -> Int32 = {
    value + 1
}

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

fun main: () = {
    val normalized = 10 |> normalize
    val total = (normalized, 5) add;
    total |> print_int
}

フィールドアクセスとプロトタイプ操作

フィールド参照は.を使えますが、関数呼び出しはOSVのままです。プロトタイプ更新にはclone、不変化にはfreezeを使います。

record Person {
    name: String
    age: Int32
}

fun greeting: (person: Person) -> String = {
    "Hello, " + person.name
}

fun main: () = {
    val alice = Person { name: "Alice", age: 30 }
    val message = alice |> greeting;
    message |> println

    val bob = Person { name: "Bob", age: 24 }
    val older_bob = bob.clone { age: 25 }
    val frozen_bob = older_bob freeze;
    frozen_bob
}

v0.0.1では現在対象外の書き方

次のような書き方は、古い資料や将来構想では見かけることがありますが、v0.0.1の現在の公開ドキュメントではRestrictコードとして示しません。

  • 関数名を先に書く呼び出し
  • ドット記法でメソッドを直接呼ぶ書き方
  • プレースホルダー引数を使った部分適用
  • パイプで新しい変数名を作る束縛構文
  • 可変パイプ構文
  • use形式や文字列パスのインポート

良い使用例

データ変換パイプライン

fun validate: (value: Int32) -> Int32 = {
    value
}

fun normalize: (value: Int32) -> Int32 = {
    value + 1
}

fun transform: (value: Int32) -> Int32 = {
    value * 2
}

fun main: () = {
    val raw_data = 10
    val result = raw_data
        |> validate
        |> normalize
        |> transform;

    result |> print_int
}

数学的操作

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun increment: (x: Int32) -> Int32 = {
    x + 1
}

fun square: (x: Int32) -> Int32 = {
    x * x
}

fun main: () = {
    val result = 10
        |> double
        |> increment
        |> square;

    result |> print_int
}

条件式との組み合わせ

fun choose_label: (score: Int32) -> String = {
    score >= 80 then { "pass" } else { "review" }
}

fun main: () = {
    val label = 92 |> choose_label;
    label |> println
}

実装の詳細

パース優先順位

フィールドアクセス、算術演算、比較演算のあとにパイプが適用されます。曖昧になりそうな式では括弧を使います。

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

fun main: () = {
    val first = (5 + 1) |> double
    val second = (5, 3 |> double) add
    val total = (first, second) add;
    total |> print_int
}

型推論

OSVは型推論と組み合わせて使えます。明示したい境界では型注釈を付けます。

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun main: () = {
    val input: Int32 = 21
    val output = input |> double;
    output |> print_int
}

ベストプラクティス

  1. OSVに統一する - v0.0.1のRestrictコードでは関数呼び出しをOSVだけで書く
  2. 単一引数はパイプを使う - value |> functionでデータフローを明確にする
  3. 複数引数はタプルを使う - (a, b) functionで引数を先に置く
  4. 複雑な式は分割する - 中間値に名前を付けて読みやすくする
  5. 将来構想の構文を混ぜない - 現在の公開サーフェスだけをコード例に使う

関連項目

型システム

Restrict Languageのv0.0.1で公開する型は、仕様で現在サポートされる構文に合わせて説明します。基本は静的型付け、アフィン型、OSV呼び出し、明示的なレコード型です。

基本型

現在の基本型名は大文字始まりです。

val count: Int32 = 42
val total: Int64 = 1_000_000
val ratio: Float64 = 0.75
val title: String = "release"
val marker: Char = 'R'
val ready: Boolean = true
val unit_value: () = ()

よく使う型は次の通りです。

  • Int32, Int64
  • Float64
  • String, Char
  • Boolean
  • ()(ユニット型)

アフィン型

Restrictの値は、基本的に最大1回まで使用できます。値を関数に渡すと、その値の所有権も渡されます。

fun consume_title: (title: String) -> String = {
    title
}

fun main: () -> String = {
    val title = "Restrict";
    title |> consume_title
}

同じ値を何度も読む設計ではなく、必要な値を明示的に渡していく設計にします。単純な数値や真偽値のようなコピー可能な基本型は、実装側のコピー意味論に従います。

可変束縛

可変束縛はmut valです。語順は固定です。

fun main: () -> Int32 = {
    mut val counter = 0;
    counter = counter + 1;
    counter
}

コレクション型

リストと固定長配列はジェネリック型で表します。範囲はv0.0.1ではRange<Int32>だけを公開します。

fun total_first_two: () -> Int32 = {
    val scores: List<Int32> = [10, 20, 30];
    scores match {
        [first, second] => { first + second }
        [first | rest] => { first }
        [] => { 0 }
    }
}
val empty_scores: List<Int32> = []
val range: Range<Int32> = [1..5]

型としてはList<T>、Array<T, N>、Range<Int32>を使います。v0.0.1の範囲リテラルはInt32の開始値と終了値だけを扱います。固定長配列の詳細な標準APIは、v0.0.1では実装と標準ライブラリの進行に合わせて扱います。

OptionとResult

オプショナルな値はOption<T>、成功または失敗はResult<T, E>で表します。

fun value_or_zero: (value: Option<Int32>) -> Int32 = {
    value match {
        Some(number) => { number }
        None => { 0 }
    }
}
fun result_or_zero: (result: Result<Int32, String>) -> Int32 = {
    result match {
        Ok(value) => { value }
        Err(message) => { 0 }
    }
}

ユーザー定義enum

現在のcompilerでは、閉じたタグ付き和としてユーザー定義enumを宣言できます。宣言は非ジェネリックかつ非再帰で、各バリアントのpayloadは0個または1個です。

enum DecodeError {
    Empty
    Invalid(String)
}

fun reject: (message: String) -> Result<Int32, DecodeError> = {
    (message |> DecodeError::Invalid) Result::Err
}

fun error_code: (error: DecodeError) -> Int32 = {
    error match {
        DecodeError::Empty => { 1 }
        DecodeError::Invalid(message) => { 2 }
    }
}

バリアントはDecodeError::Invalidのように必ずenum名で修飾します。payloadなしのバリアントは() DecodeError::Empty、payloadありのバリアントはmessage |> DecodeError::InvalidのようにOSV語順で構築します。matchはenumの全バリアントを網羅する必要があります。

enum値がCopyになるのは、すべてのpayload型がCopyの場合だけです。アフィンなpayloadを構築するとその値は移動し、enumをmatchするとscrutineeは通常のアフィン規則に従って1回消費されます。

この初期範囲ではenum値に==と!=は定義しません。内部の割り当てアドレスを誤って比較しないようcompilerがenumの等価比較を拒否するため、修飾されたバリアントをmatchしてください。

pub enumは別のRestrictソースモジュールからimportできる型名前空間を公開しますが、直接のhost-visible WebAssembly enum ABIは提供しません。Result<T, DecodeError>のエラー伝播は明示的なmatchで行い、?演算子はまだありません。

レコード型

関連する値はrecordでまとめます。フィールド定義とレコードリテラルのどちらも、フィールド名の後に:を置きます。

record User {
    name: String
    age: Int32
    active: Boolean
}

fun user_name: (user: User) -> String = {
    user.name
}

fun main: () -> String = {
    val user = User { name: "Alice", age: 30, active: true };
    user |> user_name
}

関数型とジェネリクス

関数型はA -> Bで表します。関数宣言はfun name: (...) -> Type = { ... }です。

fun identity: <T>(value: T) -> T = {
    value
}

fun apply_once: <T, U>(value: T, transform: T -> U) -> U = {
    value |> transform
}

複数引数の呼び出しはOSVのタプル形式です。

fun add: (left: Int32, right: Int32) -> Int32 = {
    left + right
}

fun main: () -> Int32 = {
    (20, 22) add
}

型推論

型注釈は必要な場所にだけ書けます。公開APIや曖昧になりやすい空リストでは、明示すると読みやすくなります。

fun main: () -> Int32 = {
    val answer = 42
    val numbers: List<Int32> = [];
    numbers match {
        [] => { answer }
        [first | rest] => { first }
    }
}

Form と静的ポリモーフィズム

現在のcompilerでは、method-only form、具体的な非ジェネリックrecordの takes、<T of Form>境界を利用できます。呼び出しは静的に選択され、具体型 ごとにmonomorphizeされます。

form Labelled {
    fun label: (self: Self) -> String
}

record Badge {
    text: String
}

Badge takes Labelled {
    fun label: (self: Badge) -> String = {
        self.text
    }
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}

詳細とDisplay出力についてはForm と静的ポリモーフィズムを参照してください。

現在の範囲外

次の項目は設計または実装が進行中であり、公開ガイドでは現在の実行可能なRestrictコードとして扱いません。

  • TATと時間スコープ付きリソース管理
  • 借用スライスや参照型中心のAPI
  • ジェネリックenum、再帰enum、複数の直接payloadを持つバリアント
  • ユーザー定義enumのhost-visible WebAssembly ABIと?演算子
  • associated type、generic form、default method、generic/conditional/enum adoption、dynamic dispatch
  • 旧来のRust風コレクションAPIやパス構文
  • 文字列インポート、インポート別名、パッケージ単位の標準ライブラリ集約

ユーザー定義enumはv0.0.1の公開範囲です。前節で説明した閉じた範囲を利用できます。

まとめ

現在の型システムでは、基本型、組み込みジェネリック型、レコード型、関数型に加え、制約されたユーザー定義enumと静的formを利用できます。例では常にvalまたはmut valを使い、関数呼び出しとenum構築はvalue |> function、(a, b) function、() Type::VariantなどのOSV形式に統一します。

スコープ単位の生存期間

関数、ブロック、スコープ付き呼び出しの実行を、生存期間の単位として扱います。 これは v0.1.0 に続く開発実装の説明です。公開済み v0.1.0 の保証とは区別してください。

内側で作った一時値は、その実行が終わると回収されます。戻り値は、その中の 文字列、record、list、array、variant、クロージャ捕捉も含め、外側の実行で 使えるように残します。外側から渡された値の領域は、内側の終了では回収しません。

fun make_message: () -> String = {
    val temporary = [1, 2, 3];
    temporary |> list_count;
    "scope" + " result"
}

fun main: () -> Boolean = {
    val message = () make_message;
    message == "scope result"
}

make_message の一時リストは関数終了で回収され、返した文字列は main で 利用できます。通常のブロックと with Arena にも同じ規則が適用されます。 利用者が arena や寿命注釈を書く必要はありません。

クロージャの定義と実行は別です。定義時には捕捉を保存し、呼び出すたびに 独立した生存期間を持ちます。再帰、map の各コールバック、while の各反復、 fold の各更新もこの規則で扱います。外側の mut val を内側で更新した場合は 新しい値を残し、反復中の古い置き換え値は回収します。 外側の array に新しい文字列などを格納した場合も、その要素を保持します。

affine 制約は「束縛を何回参照できるか」の規則で、生存期間とは独立しています。 今回の実装は Rust 型の所有権・借用規則を導入しません。Component の own/borrow も、ホスト境界の契約として扱います。

物理的にはスコープ間で arena を共有し、終了時に生存する新しいデータだけを 作業領域へコピーして詰め直します。括弧ごとに固定サイズの arena を作りません。 外側の有効な束縛は保守的に残すため、最終参照直後の回収までは保証しません。 本当に増え続ける生存データは領域を消費し、容量不足は trap になります。

trap では Wasm の終了処理は走りません。診断を読んだ後はインスタンスを破棄します。 Result::Err は通常の値として終了処理を受けます。return、break、continue、 ?? return/?? break/?? continue は、抜ける前に抜けるスコープの領域を回収します。 return は戻り値だけを残し、continue と break はループの外にも生きる束縛の値だけを残します。 後置 ?、async とキャンセルは未実装です。実験的 TAT の File/Database/Transaction 破棄 stub はコンパイルエラーにし、検証済みの同期 B1 resource 経路とは区別しています。

関数

Restrict Language では、関数は OSV 構文で呼び出します。引数は関数名の前に置き、関数宣言は fun name: (...) -> Type = { ... } の形で書きます。

関数定義

基本的な関数構文:

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

パラメータなしの関数:

fun get_answer: () -> Int32 = {
    42
}

戻り値型を推論させる関数:

fun double: (x: Int32) = {
    x * 2
}

OSV 呼び出し

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

fun double: (x: Int32) -> Int32 = {
    x * 2
}

val total = (5, 10) add
val doubled = 21 |> double

単一引数では |> を使い、複数引数ではタプルを関数名の前に置きます。

関数合成

OSV では、値の流れを左から右へつなげます。

fun increment: (x: Int32) -> Int32 = {
    x + 1
}

fun double: (x: Int32) -> Int32 = {
    x * 2
}

fun square: (x: Int32) -> Int32 = {
    x * x
}

val result = 5 |> increment |> double |> square

高階関数

関数は他の関数を受け取れます。

fun apply_twice: (value: Int32, f: Int32 -> Int32) -> Int32 = {
    value |> f |> f
}

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun main: () -> Int32 = {
    (5, double) apply_twice
}

コレクションのコールバック、スコープ動詞節、map、filter、foldは 高階関数とコレクション変換でまとめて説明します。

ジェネリック関数

fun identity: <T>(value: T) -> T = {
    value
}

fun map_option: <T, U>(opt: Option<T>, f: T -> U) -> Option<U> = {
    opt match {
        Some(value) => { value |> f |> Option::Some }
        None => { () Option::None }
    }
}

関数値

ラムダ式を束縛して、通常の関数と同じ OSV 形で使えます。

val add_five: Int32 -> Int32 = |x: Int32| x + 5
val multiply: (Int32, Int32) -> Int32 = |x: Int32, y: Int32| x * y

val result = 10 |> add_five
val product = (3, 4) multiply

分岐が返す関数値

thenやmatchの各分岐がラムダで終わる場合、その値をいったんvalに束縛し、後続のOSV呼び出しやmapから関数型を推論できます。

fun add_int: (total: Int32, value: Int32) -> Int32 = {
    total + value
}

fun main: (urgent: Boolean, bonus: Option<Int32>) -> Int32 = {
    val adjust = urgent then {
        val boost = 2;
        |score| score + boost
    } else {
        val factor = 2;
        |score| score * factor
    }
    val normalize = bonus match {
        Some(value) => {
            val doubled = value * 2;
            |score| score + doubled
        }
        None => {
            val doubled = 0;
            |score| score + doubled
        }
    }
    val scores = [10, 20]
    val adjusted = (scores, adjust) map
    val normalized = (adjusted, normalize) map

    (normalized, 0, add_int) fold
}

この分岐内の前置き処理は、v0.0.1では再実行しても安全な単純val束縛に限定します。mut val、複雑なパターン、Stringやレコード、リスト、関数値のような非Copy値はここでは拒否されます。

再帰関数

fun factorial: (n: Int32) -> Int32 = {
    n <= 1 then {
        1
    } else {
        n * ((n - 1) |> factorial)
    }
}

fun fibonacci: (n: Int32) -> Int32 = {
    n match {
        0 => { 0 }
        1 => { 1 }
        _ => { ((n - 1) |> fibonacci) + ((n - 2) |> fibonacci) }
    }
}

部分適用に近い書き方

v0.0.1 では専用の部分適用構文を使わず、ラムダで必要な引数を固定します。

fun add: (x: Int32, y: Int32) -> Int32 = {
    x + y
}

val add_five: Int32 -> Int32 = |y: Int32| (5, y) add
val result = 10 |> add_five

関数型アノテーション

val double_fn: Int32 -> Int32 = |x: Int32| x * 2
val add_fn: (Int32, Int32) -> Int32 = |x: Int32, y: Int32| x + y

fun transform: (value: Int32, f: Int32 -> Int32) -> Int32 = {
    value |> f
}

現在の境界

v0.0.1 compilerでは、method-only form、具体recordのtakes、 <T of Form>境界を利用できます。詳細はForm と静的ポリモーフィズムを参照してください。

次の機能は将来の設計対象です。

  • associated type、generic form、default method
  • generic/conditional/enum adoption と dynamic dispatch
  • 属性付きテスト関数
  • 関数名を先に置く呼び出し形式
  • 標準コレクション用の包括的な高階 API

ベストプラクティス

  1. パイプラインでは OSV を使い、値の流れを左から右へ保つ
  2. 関数は小さく保ち、1つの変換や判定に集中させる
  3. 複数引数はタプルを関数名の前に置く
  4. 必要な型は Int32、Float64、Boolean など current type 名で書く
  5. 迷った場合は /LANGUAGE_SPECIFICATION.md を確認する

関連項目

高階関数とコレクション変換

高階関数は、関数値を受け取ったり返したりする関数です。Restrictでも呼び出しは OSV語順のままで、通常の値と関数値を呼び出す関数より前に置きます。

コレクション変換では、もう一つRestrictらしい読み方ができます。高階の動詞が 最後の関数引数をレキシカルスコープとして開くため、関数名を先頭へ移動せずに コールバック本体を動詞の後ろへ置けます。

関数値は通常の引数

名前付き関数やラムダは、通常の引数として渡せます。

fun double: (value: Int32) -> Int32 = {
    value * 2
}

fun apply_twice: (value: Int32, transform: Int32 -> Int32) -> Int32 = {
    value |> transform |> transform
}

fun main: () -> Int32 = {
    (5, double) apply_twice
}

インラインラムダも、同じグループ化されたOSV呼び出しを使います。

fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3];
    (numbers, |value| value * 2) map
}

コンテナ、コールバック、それ以前の引数はすべて呼び出しの目的語なので、 map、filter、foldより前に置かれます。

現在のコレクション操作

v0.0.1コンパイラは、次の高階操作をpreludeへ登録しています。

操作現在の入力コールバック結果
mapList<T>T -> UList<U>
mapOption<T>T -> UOption<U>
filterList<T>T -> BooleanList<T>
filterOption<T>T -> BooleanOption<T>
foldList<T>と初期値U(U, T) -> UU

mapはリストの各要素、またはSomeのペイロードを変換します。Noneは Noneのままです。filterは述語がtrueになるリスト要素を残します。 Optionでは、条件を満たすSomeを残し、それ以外をNoneにします。foldは リストを左から右へ走査し、累積値と現在の要素をreducerへ渡します。

ArrayとResultは、現在のコンパイラのコンテナ動作には含まれません。 foldはList専用です。内部のContainer.ItemとContainer.Mapped<U>は ソースから見えるformではなく、ユーザー定義型からadoptすることもまだできません。

スコープ動詞節

最後に残った仮引数が関数型なら、動詞はその関数本体を後続スコープとして 開けます。

fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3]
    numbers map {
        it * 2
    }
}

ヘッダーのないブロックには、文脈的な束縛itが1つ導入されます。コンパイラは コンテナ要素型を期待される引数型として使い、通常ラムダを通して節を展開します。

numbers map { it * 2 }
// 同じコールバックモデル:
(numbers, |it| { it * 2 }) map

この形式はコレクションだけにハードコードされた特別構文ではありません。 最後に残った引数が関数である任意の呼び出しでスコープを開けます。

fun apply: (value: Int32, transform: Int32 -> Int32) -> Int32 = {
    value |> transform
}

fun main: () -> Int32 = {
    41 apply {
        it + 1
    }
}

完成した41 apply { ... }節は、ほかのOSV呼び出しと同じように値を生成します。

暗黙バインダーと明示バインダー

短い単項コールバックには、暗黙it形式を使えます。

values filter {
    it > 0
}

本体が長い場合や、名前自体に意味がある場合は引数を明示します。

values map { |value|
    val shifted = value + 1;
    shifted * 2
}

複数引数のコールバックには明示バインダーが必要です。foldのreducerは、 累積値を先、現在の要素を後に受け取ります。

(values, 0) fold { |total, value|
    total + value
}

引数なしのスコープには明示的な空ヘッダー{ || ... }を使います。これは最後の 引数が() -> Tである高階関数に使えますが、map、filter、foldには 当てはまりません。

完成した節をつなぐ

スコープ動詞節は左から右へ結合します。完成した各節が次の動詞の目的語になります。

fun main: () -> Int32 = {
    val values = [1, 2, 3]
    val selected = values map {
        it + 1
    } filter {
        it > 2
    }
    (selected, 0) fold { |total, value|
        total + value
    }
}

このプログラムは次の順に読めます。

  1. [1, 2, 3]を[2, 3, 4]へmapする
  2. 完成したmap結果を[3, 4]へfilterする
  3. その結果を7へfoldする

後続のパイプも、完成した節全体の結果を受け取ります。

values map { it + 1 } |> list_count

型推論

高階呼び出しは、両方向に型情報を与えます。

  • コンテナ型がコールバックの要素型を決める
  • map本体が変換後の要素型を決める
  • 宣言された結果型からコールバック結果を制約できる
  • filterの結果にはBooleanが必要
  • 初期値とreducer結果がfoldの累積値型を決める
  • identityのような名前付きジェネリック関数は、期待されるコールバック型から 特殊化できる
fun main: () -> List<Int32> = {
    val numbers = [1, 2, 3]
    (numbers, identity) map
}

空コレクションや値のないOptionでは、アノテーションや別の具体的な利用が必要に なる場合があります。Restrictはフォールバック型を選ばず、未解決の型を報告します。

Optionの変換

現在のOptionコンテナ動作にも、同じスコープ形式を使えます。

fun increment_if_present: (value: Option<Int32>) -> Option<Int32> = {
    value map {
        it + 1
    }
}

fun keep_positive: (value: Option<Int32>) -> Option<Int32> = {
    value filter {
        it > 0
    }
}

これはコンテナとしてのmap/filterであり、独立したoption_map APIではありません。 v0.0.1のfoldは引き続きList専用です。

アフィン値とキャプチャ

スコープ付きコールバックも、通常ラムダと呼び出しと同じアフィン規則に従います。

  • 非Copyのコレクション束縛をmap、filter、foldへ渡すと、その呼び出しで 束縛を使用する
  • コールバック引数とキャプチャした束縛は、通常のCopyまたはアフィン動作を保つ
  • 波括弧によってキャプチャしたアフィン値の利用回数が増えることはない
  • コールバック本体は、受け取る関数の契約に従って0回、1回、または複数回実行される

暗黙スコープを2重にすると、どちらのfocusもitになるためRestrictは拒否します。 少なくとも片方のバインダーを明示してください。

groups map { |group|
    group map {
        it + 1
    }
}

外側をgroupと明示することで、値の流れとキャプチャ意図が明確になります。

形式の選び方

コールバックにすでに適切な名前がある場合や、関数値として選択した場合は、 通常の関数引数を使います。

(numbers, normalize) map

コールバックが1つの変換にだけ属する場合は、スコープ動詞節を使います。

numbers map {
    it + 1
}

複数引数、ネストしたスコープ、長い本体には明示バインダーを使います。

(numbers, 0) fold { |total, number|
    total + number
}

3形式はいずれも同じ高階関数モデルです。違うのはコールバックの導入方法と、 ローカルな値の流れをどの程度明確に読めるかだけです。

関連項目

Form と静的ポリモーフィズム

Form は、Restrict における明示的な振る舞いの契約です。OSV 呼び出し、 アフィン所有権、WebAssembly の直接呼び出しを保ったまま、ジェネリック関数が 必要とする振る舞いを名前で表せます。

v0.0.1 slice は意図的に小さくしています。

  • form は非ジェネリックで、必須メソッドのシグネチャだけを持つ
  • 各メソッドは完全に型付けされ、先頭は self: Self
  • 具体的な非ジェネリック record が takes で form を採用する
  • 型パラメータは <T of A + B> で必要な form を列挙する
  • コンパイラは vtable や実行時辞書を使わず、呼び出しを単相化する

Form の宣言と採用

pub form Labelled {
    fun label: (self: Self) -> String
}

record Badge {
    text: String
}

Badge takes Labelled {
    fun label: (self: Badge) -> String = {
        self.text
    }
}

fun read_label: <T of Labelled>(value: T) -> String = {
    value |> label
}

適合は明示的です。同名の通常 impl メソッドがあっても、対応する takes 宣言がなければ form を満たしません。takes は form が要求するメソッドを 過不足なく実装し、Self を対象 record 型へ置き換えた完全なシグネチャを 記述します。適合判定は位置と型で行われるため、パラメータ名は契約と異なっても 構いません。

pub form は別の Restrict ソースモジュールから import できます。 takes 自体には pub を付けず、form と nominal record を公開します。

複数の制約

+ は、具体型が列挙されたすべての form を満たすことを意味します。

fun inspect: <T of Display + Labelled>(value: T) -> String = { ... }

この初期 slice では、同じ具体型の通常 impl と form adoption は一つの selector 名前空間を共有するため、二つの宣言から同じ selector を公開できません。 複数の generic bound が同じ selector を公開する場合も曖昧性エラーになり、 暗黙の優先順位は付きません。

アフィンな receiver

Form メソッドも通常のアフィン関数です。非 Copy record を self として渡すと 値を消費します。Form の解決が値を借用、複製、再評価することはありません。 Form の採用によって型が Copy になることもありません。

Display と出力

コンパイラは display: (self: Self) -> String を要求する Display form と、 String、Int32、Int64、Float64、Boolean、Char、() の adoption を 提供します。ユーザー record は明示的に採用します。

record Notice {
    text: String
}

Notice takes Display {
    fun display: (self: Notice) -> String = {
        self.text
    }
}

fun main: () -> () = {
    42 |> print
    " · " |> print
    Notice { text: "records too" } |> println
}

print と println は任意の Display 値を受け取ります。eprint と eprintln は String 専用のままで、print_int と print_float も互換用に 残ります。display、print、println はコンパイラ予約の直接呼び出し先で、 トップレベル関数や通常/custom form の method selector として宣言できません。 組み込み自体を first-class 関数値として捕捉することもまだできません。例外は RecordName takes Display 内の display メソッドだけです。

現在の境界

関連型、generic form、generic/conditional takes、default method、enum adoption、 negative bound、adoption の選択的 import、existential form value、dynamic dispatch は今後の機能です。コレクション組み込みが内部で使う Container projection は、 Container やソース関連型の公開を意味しません。

Warderパッケージマネージャー

WarderはRestrict Languageのプロジェクト作成、依存関係管理、ビルド、実行、テストをまとめるツールです。v0.0.1で公開対象として扱うコマンドは、new、init、add、remove、build、run、test、publish、wrap、unwrap、doctorです。すべてのサブコマンドでグローバルオプション--project <dir>を使えます。たとえばwarder build --project ./services/checkoutは、呼び出し元の作業ディレクトリを変更せずに対象プロジェクトをビルドします。

主要概念

Cageフォーマット(.rgc)

CageはWarderのパッケージ成果物です。warder buildは既定でdist/<name>-<version>.wat、dist/<name>-<version>.wasm、dist/<name>-<version>.rgcを生成します。

ルートロックファイル(warder.lock)

warder.lockはWarderがリポジトリルートに生成する唯一のロックファイルです。リポジトリソースから決定的に再構築できない外部依存関係の解決結果だけを記録します。直接ローカルソースパッケージはロック対象ではありません。現在はレジストリ、Git、外部WASM、推移的依存関係の解決がfail closedするため、ローカルのみのロックに解決済みパッケージエントリはありません。生成されたlockは手で編集せず、リポジトリへコミットします。

プロジェクトの作成

新しいプロジェクトを作成します:

warder new my-project
cd my-project

作成される基本構造:

my-project/
├── warder.toml
├── src/
│   └── main.rl
├── tests/
│   └── main_test.rl
├── README.md
└── .gitignore

既存ディレクトリをWarderプロジェクトにする場合:

warder init

リポジトリ設定

warder.tomlはWarder管理リポジトリで人が編集する唯一の設定ファイルです。warder newとwarder initは次の最小形を生成します:

manifest-version = 1

[package]
name = "my-project"
version = "0.1.0"

規約値としてentryはsrc/main.rl、editionは2025、buildはtarget wasm32・最適化有効・出力先dist/が適用され、空のdependenciesは省略 されます。package.entry、package.edition、buildは規約値を変更する 場合だけ記述します。descriptionとauthorsは必要に応じて追加できる 任意のメタデータです。

ローカル依存を追加した場合だけ、次のテーブルが加わります:

[dependencies]
local_utils = { path = "../local-utils" }

現行実装が公開可能なパッケージはルートの1つです。直接ローカルソースパッケージはこのルート設定から一元的に選択し、leaf manifestやleaf lockを持ちません。将来の複数公開パッケージworkspaceも同じルートwarder.tomlを拡張し、別のworkspace設定やmember manifestは追加しません。公開identityはディレクトリ名から導出せず、ルート設定に明示します。

依存関係の管理

v0.0.1でビルドできる依存関係は、直接参照するローカルパス依存関係だけです。[dependencies]のキーがRestrictソースで使う名前空間になります。この別名は予約語ではない単一のRestrict識別子である必要があります。local-utilsは暗黙に変換されないため、local_utilsのように記述してください。stdとprojectは予約済みで、projectはテストからルートpackageのsourceをimportするために使います。

ローカル依存関係を追加します:

warder add local_utils --path ../local-utils

依存先に必要なのはsrc/lib.rlだけです:

local-utils/
└── src/
    ├── lib.rl
    └── numbers.rl

依存先のsrc/lib.rlは、たとえば次のように公開関数を定義できます:

pub fun score: () -> Int32 = {
    42
}

アプリケーション側のインポートとファイルの対応は次のとおりです:

ソースのインポート依存先ファイル
import local_utils.{score}../local-utils/src/lib.rl
import local_utils../local-utils/src/lib.rl
import local_utils.numbers.{double}../local-utils/src/numbers.rl

依存パッケージ内の修飾なしインポートは、その依存パッケージ内で解決されます。たとえばlocal-utils/src/lib.rl内のimport numbers.{double}は、アプリケーション側ではなく同じパッケージのsrc/numbers.rlを参照します。

これはルート設定とコンパイラ間の名前空間バインドです。ソース構文としてのimport ... asやre-exportは引き続き未対応です。

レジストリ、Git、外部WASM、推移的依存関係はまだ解決しません。warder add、warder build、warder testはこれらを明示的にエラーにし、見せかけのロックエントリを生成しません。外部WASMのローカル評価には、別機能のwarder wrapを使用してください。

Warderはアプリケーションと各依存パッケージのソースを不変スナップショットへコピーしてからコンパイルします。アプリケーション、依存先、出力先のルートが重なる構成は拒否します。同じプロジェクトの並行ビルドは直列化され、WAT、WASM、Cage、ロックファイルは復旧可能な一括更新として公開されます。コンパイル失敗時は以前の成果物一式を維持します。

依存関係の削除:

warder remove local_utils

ビルド

warder build

[component]がないプロジェクトの既定成果物はdist/<name>-<version>.wat、dist/<name>-<version>.wasm、dist/<name>-<version>.rgcです。

buildは次のフラグを受け付けます:

warder build --release
warder build --watch
warder build --component
warder build --core
warder build --verify
warder build --repro

--watchは初回ビルド後、ルートwarder.toml、プロジェクトの.rl、直接ローカル依存関係の.rlを監視してフルビルドをやり直します。incremental compilerやnpm bundlerではありません。[component]があるプロジェクトでは、通常のwarder buildがComponent成果物を生成します。--componentはComponent選択が存在することを明示的に要求し、--coreはCore Wasm/Cageを強制します。現行実装ではpubとexportのどちらも単独ではComponent ABIを公開せず、source-publicと[component]の二重gateが必要です。pubをpackage公開、exportをComponent公開の意図として分離するsource-first方式は将来のeditionの計画です。ターゲットはルート設定の[build]で指定します。

Componentビルドは、ロック更新とともに次の一式を復旧可能なトランザクションで公開します:

dist/<name>-<version>.component.wasm
dist/<name>-<version>.component.wit
dist/<name>-<version>.component.toml

.component.tomlは意味的なinterface hashとComponent/WITの内容hashを分離して記録する生成成果物であり、プロジェクト設定ではありません。再ビルドが失敗した場合は以前の完全な一式を維持します。schema-v2はルート宣言に限定され、resource、値だけをcaptureするonce-callable、明示的なgeneric関数の具体化を追加します。

実行

warder run

プログラム引数を渡す場合:

warder run -- arg1 arg2

warder runは先にビルドを実行し、生成されたWASMをwasmtimeまたはwasmerで実行します。現時点ではCore Wasm用の実行コマンドなので、[component]がある場合はCoreビルドを強制することを表示します。

テスト

warder test

warder testはtests/以下から、名前がtest_で始まるか_testで終わるsource-public関数を探します。各関数は同期・非generic・引数なしで、戻り型を明示的にBooleanとします:

import project.main.{calculate_bonus}

pub fun test_bonus: () -> Boolean = {
    (21, 4) calculate_bonus == 25
}

WarderはテストファイルをWASI Preview 1 Core Wasmへコンパイルし、各exportを独立したinstanceで実行します。trueなら成功し、false、trap、コンパイルエラー、export欠落は失敗します。projectはpackage.entryを含むsource directory(既定ではsrc/)へ対応し、warder buildと同じ直接ローカル依存関係も利用できます。filterはファイル名ではなくテスト関数名に適用されます:

warder test bonus

公開

warder publish
warder publish --registry https://example.com

v0.0.1のpublishはCore Cageの事前ビルドとメタデータ検証を行います。[component]がある場合はCoreビルドを強制することを表示します。レジストリへのアップロードは実験的で、このリリース範囲では実行されません。

外部WASMのCage化

外部WASMをCageに包む場合:

warder wrap module.wasm --name foreign-math --version 0.1.0
warder wrap module.wasm --name foreign-math --version 0.1.0 --wit interface.wit --output foreign-math.rgc

生成されるCageはローカル評価向けの実験的な成果物です。--witは指定されたWITテキストをCageへ添付するだけで、WITの生成・解析・型検証、Core moduleとの整合確認、Component化は行いません。これはRestrictパッケージからComponent一式を生成・検証するwarder build --componentとは別機能です。

Cageを展開する場合:

warder unwrap foreign-math.rgc
warder unwrap foreign-math.rgc --output extracted

warder unwrap --componentは受け付けますが、Cage展開時のWASM Component変換は行いません。

プロジェクトの健全性チェック

warder doctor

doctorはリポジトリルート、warder.toml、エントリーポイント、warder.lock、基本的な設定問題を確認します。一部の詳細解析はv0.0.1ではスキップされます。

コマンドリファレンス

コマンド説明
warder new <name>新しいプロジェクトを作成
warder init現在のディレクトリを初期化
warder add <alias> --path <dir>直接ローカル依存関係を追加
warder remove <name>依存関係を削除
warder buildプロジェクト設定に従ってCoreまたはComponent成果物を生成
warder runビルドして実行
warder test [filter]tests/以下のBooleanテストを実行
warder publish事前ビルドとメタデータ検証
warder wrap <wasm>外部WASMをCage化
warder unwrap <cage>Cageを展開
warder doctorプロジェクトの健全性を確認

標準ライブラリリファレンス

このページは、Displayと互換helperを含む、v0.0.1のcompiler-registered standard-library surfaceを説明します。標準関数は主にコンパイラへ登録された組み込みsurfaceとして提供され、std/*.rlは読者とテスト向けの参照インデックスです。

import について

v0.0.1 では、標準ライブラリを集約モジュールとして読み込む構文は current surface ではありません。ソースモジュールの import は dotted path 形式だけを扱いますが、標準ライブラリの package-level aggregator は今後のモジュール設計対象です。

prelude.rl

自動的に利用できる基本関数です。

identity: <T>(T) -> T
map: compiler-registered generic container mapping builtin
filter: compiler-registered generic container filtering builtin
fold: compiler-registered generic List reduction builtin
not: (Boolean) -> Boolean
and: (Boolean, Boolean) -> Boolean
or: (Boolean, Boolean) -> Boolean
assert: (Boolean, String) -> ()
panic: (String) -> ()

対応コンテナ、コールバック型、スコープ呼び出し、アフィン動作は 高階関数とコレクション変換で説明します。

fun prelude_example: () -> Boolean = {
    val value = 42 |> identity
    val inverted = false |> not
    val both = (true, inverted) and
    mut val result = (both, value == 42) or

    (result, "prelude example should pass") assert;
    result
}

io.rl

現在の I/O surface はコンソール出力に限定されています。

Display は値を String に変換する標準 form です。

form Display {
    fun display: (self: Self) -> String
}

コンパイラは String、Int32、Int64、Float64、Boolean、Char、 () の adoption を提供します。ユーザー定義 record は明示的に Display を adopt します。

record Notice {
    text: String
}

Notice takes Display {
    fun display: (self: Notice) -> String = {
        self.text
    }
}
display: <T of Display>(T) -> String
println: <T of Display>(T) -> ()
print: <T of Display>(T) -> ()
print_int: (Int32) -> ()
print_float: (Float64) -> ()
eprint: (String) -> ()
eprintln: (String) -> ()
fun io_example: () -> () = {
    "Hello" |> print
    "World" |> println
    42 |> print
    Notice { text: "record も出力できます" } |> println
    3.14 |> print_float
    "error" |> eprintln
}

print_int と print_float は互換 helper として残ります。eprint と eprintln は String 専用です。form の選択は静的で、コンパイル時に monomorphize されます。display、print、println はコンパイラ予約の 直接呼び出し先で、トップレベル関数や通常/custom form の method selector として 宣言できません。組み込み自体を first-class 関数値として捕捉することもまだ できません。

標準入力、ファイル読み書き、ディレクトリ操作は current standard-library surface には含まれていません。

string.rl

現在の文字列 surface は、文字列結合と内容比較です。

left + right: concatenate two String values
left == right: compare String contents
left != right: compare String contents and negate the result
fun string_example: () -> Boolean = {
    val joined = "Hello, " + "World"
    val matches = joined == "Hello, World";
    matches
}

長さ取得、パース、フォーマット、trim、split などのヘルパーは current surface には含まれていません。

math.rl

abs: (Int32) -> Int32
max: (Int32, Int32) -> Int32
min: (Int32, Int32) -> Int32
pow: (Int32, Int32) -> Int32
factorial: (Int32) -> Int32
abs_f: (Float64) -> Float64
max_f: (Float64, Float64) -> Float64
min_f: (Float64, Float64) -> Float64
fun math_example: () -> Int32 = {
    val a = -5 |> abs
    val b = (10, 20) max
    val c = (3, 7) min
    val d = (2, 3) pow
    val e = 4 |> factorial;

    a + b + c + d + e
}
fun float_math_example: () -> Float64 = {
    val a = -3.14 |> abs_f
    val b = (1.5, 2.7) max_f
    val c = (0.5, 1.0) min_f;

    a + b + c
}

三角関数、丸め、対数、乱数は current surface には含まれていません。

list.rl

list_is_empty: <T>(List<T>) -> Boolean
list_head: <T>(List<T>) -> Option<T>
list_tail: <T>(List<T>) -> Option<List<T>>
list_reverse: <T>(List<T>) -> List<T>
list_prepend: <T>(T, List<T>) -> List<T>
list_append: <T>(List<T>, T) -> List<T>
list_concat: <T>(List<T>, List<T>) -> List<T>
list_count: <T>(List<T>) -> Int32
list_length: <T>(List<T>) -> Int32
list_get: <T>(List<T>, Int32) -> T
fun list_example: () -> Int32 = {
    mut val numbers = [1, 2, 3, 4]

    val count = numbers |> list_count
    val length = numbers |> list_length
    val first = (numbers, 0) list_get
    val extended = (numbers, 5) list_append
    val extended_count = extended |> list_count;

    count + length + first + extended_count
}
fun list_composition_example: () -> Int32 = {
    val extended = ([1, 2, 3, 4], 5) list_append
    val combined = ([1, 2, 3, 4], [6, 7, 8]) list_concat
    val first = (0, [1, 2, 3, 4]) list_prepend

    val a = extended |> list_count
    val b = combined |> list_count
    val c = first |> list_count;

    a + b + c
}

専用の list map/filter/fold helper は current list module surface には含まれていません。prelude の compiler-registered generic container builtins として扱われます。正確なv0.0.1のコンテナ境界は高階関数ガイドを参照してください。

option.rl

option_is_some: <T>(Option<T>) -> Boolean
option_is_none: <T>(Option<T>) -> Boolean
option_unwrap_or: <T>(Option<T>, T) -> T
fun option_example: () -> Int32 = {
    mut val maybe = 42 Option::Some

    val has_value = maybe |> option_is_some
    val is_empty = maybe |> option_is_none
    val value = (maybe, 0) option_unwrap_or;

    value
}

値の構築にはqualified OSVの value Option::Some と () Option::None を使います。matchでの分解は従来どおり Some(value) と None です。option map、flatten、and-then、zip などの高階 helper は current surface には含まれていません。

組み合わせ例

fun standard_library_flow: () -> Boolean = {
    val abs_result = -42 |> abs
    val max_result = (abs_result, 50) max

    mut val numbers = [1, 2, 3, 4, 5]
    val list_size = numbers |> list_count
    mut val maybe_first = numbers |> list_head

    mut val first = (maybe_first, 0) option_unwrap_or
    val has_value = maybe_first |> option_is_some

    val above_threshold = max_result > 40
    mut val result = (has_value, above_threshold) and;

    first |> print_int;
    list_size |> print_int
    (result, "standard library flow should pass") assert;

    result
}

v0.0.1 の current surface ではない標準 API

次の領域は、今後の標準ライブラリまたはランタイム設計で扱う予定です。このページでは current Restrict のコード例としては示しません。

  • 標準入力とファイルシステム
  • 時刻、乱数、ネットワーク、プロセス管理
  • 反復子 trait とカスタム iterator
  • Debug、Hash など Display 以外の標準 form
  • associated type、generic form、default method、conditional/generic/enum adoption、dynamic dispatch
  • macro ベースのフォーマット API
  • try-style early return operator

標準ライブラリの例を追加する場合は、std/*.rl の参照インデックスと compiler/runtime support が一致していることを先に確認してください。