繁體中文English简体中文

How to use and how to write Russd

This page is the language tutorial: syntax, what you can actually do, and a long list of limits. Install and clone live under Download core; project files live under How to configure.

1. Shape of a program

Source files end in `.rsd`. `russd run` requires `fn main()`. Semicolons are optional. The last expression in a block is the return value.

Comments are `//` only. Keywords: `fn` `let` `mut` `if` `else` `while` `for` `in` `loop` `break` `continue` `struct` `enum` `match` `impl` `return` `true` `false` `self` `mod`.

First `cd russd-core` (that folder has `Cargo.toml`; staying in the parent directory yields `could not find Cargo.toml`). Then `cargo run -- examples/hello.rsd` (space after `--`; do not write `cargo run --run`). Extra program args go after another `--`: `cargo run -- examples/hello.rsd -- foo`, read with `args()` as `Vec[str]`.

hello.rsd

fn greet(name: str) -> str {
    "Hello, " + name
}

fn main() {
    print(greet("Russd"))
}

The compiler optimizes

Russd is an optimizing compiler. Default `-O2`: constant folding, algebraic identities (`x+0`, `x*1`), dead `if` branches, small inlining, unused `let` removal, bytecode peephole.

`russd run f.rsd -O0` turns passes off. `russd opt f.rsd` prints fold/inline/dce counts and bytecode. Overflow and division by zero are not folded into wraparound. The backend is still a safe VM, not LLVM native code.

inspect optimizations

russd opt examples/hello.rsd
russd run examples/fizzbuzz.rsd -O2
russd run examples/fizzbuzz.rsd -O0

2. Types

Built-ins: `i32` `i64` `f64` `bool` `str` `()` `Vec[T]` `Map[V]` `Option[T]` `Result[T,E]`. Type arguments use square brackets.

Integer literals are `i32` by default. Values that do not fit need an `i64` suffix. Floats need a decimal point (`3.14`).

types

fn main() {
    let n: i32 = 7
    let big: i64 = 10000000000i64
    let x: f64 = 3.14
    let ok: bool = true
    let s: str = "hi"
    let nothing: () = ()
    print(n, big, x, ok, s, nothing)
}

3. Variables

`let` is immutable; `let mut` can be assigned again. You may annotate `let n: i32 = 1` or let the checker infer.

Assignment targets are variables, struct fields, or `Vec` indexes.

let / let mut

fn main() {
    let a = 1
    let mut b = 2
    b = b + a
    b += 3
    print(b)
}

4. Operators

Arithmetic `+ - * / %` (`+` also concatenates strings). Comparison `== != < <= > >=`. Logic `&& || !`. Bitwise `& | ^ ~ << >>`.

No overloading: you cannot `+` two structs. Comparisons are for numbers.

operators

fn main() {
    print(1 + 2 * 3)
    print(10 / 2)
    print(10 % 3)
    print(1 << 3)
    print(6 & 3)
    print(6 | 1)
    print(7 ^ 3)
    print(~0)
    print(true && false)
    print(!false)
}

5. Control flow

`if` / `else if` / `else` are expressions; branches need `{ }`. `while` conditions are `bool`.

`for x in xs` walks a `Vec` or a range `1..n` (exclusive). `loop` with `break` / `continue`. `break` does not take a value.

if / while / for / loop

fn main() {
    let n = 15
    if n % 15 == 0 {
        print("FizzBuzz")
    } else if n % 3 == 0 {
        print("Fizz")
    } else {
        print(n)
    }

    let mut i = 0
    while i < 3 {
        i += 1
    }

    for x in 1..4 {
        print(x)
    }

    loop {
        i += 1
        if i >= 6 {
            break
        }
        if i == 4 {
            continue
        }
        print(i)
    }
}

6. Functions

`fn name(param: Type) -> Type { ... }`. Omit `->` for `()`.

Parameters may be values, `mut x: T`, `&T`, or `&mut T`. Methods may take `self`, `&self`, `&mut self`. No default args, no varargs, no type parameters on your functions. Mutation is mainly `let mut` plus Vec/Map methods; `*x = ...` cannot write back through a reference yet.

fn

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn twice(n: i32) -> i32 {
    n + n
}

fn main() {
    print(twice(add(2, 3)))
}

7. Strings

`str` is an owned string. Methods: `len` `is_empty` `contains` `split` `replace` `trim` `to_upper` `to_lower` `starts_with` `ends_with` `parse_i32`.

`parse_i32` returns `Result[i32, str]`. `len` is UTF-8 bytes.

strings

fn main() {
    let s = " Hello, Russd\n "
    print(s.trim())
    print("Ab".to_lower())
    print("ab".to_upper())
    print("a,b,c".split(",").join("-"))
    print("hello".starts_with("he"))
    print("hello".contains("ell"))
    print("12".parse_i32())
}

8. Vec

`vec(...)` builds a vector. `push` `pop` `clear` `reverse` mutate in place and need a variable receiver.

`xs[i]` indexes with an integer; out of bounds is a runtime error. `join(sep)` works on `Vec[str]` only.

Vec

fn main() {
    let mut xs: Vec[i32] = vec()
    xs.push(10)
    xs.push(20)
    xs.push(30)
    print(xs.len())
    print(xs[1])
    xs[1] = 21
    print(xs.contains(21))
    match xs.pop() {
        Some(v) => print(v)
        None => print("empty")
    }
    xs.reverse()
    print(xs)
}

9. Map

`map()` takes no arguments. Write the value type as `Map[V]`. Keys are always `str`. Use `.set` and `.get` (an `Option`); not `m["k"]`.

Also `keys()` `contains` `len` `is_empty` `clear`.

Map

fn main() {
    let mut m: Map[i32] = map()
    m.set("score", 99)
    match m.get("score") {
        Some(v) => print("score", v)
        None => print("missing")
    }
    print(m.keys())
    print(m.contains("score"))
}

10. Structs and impl

Named fields: `struct Point { x: i32 y: i32 }`. Build with `Point { x: 3, y: 4 }`. Every field is required.

`impl Point { ... }` adds methods. No inheritance, no constructor keyword, no private fields.

struct / impl

struct Point {
    x: i32
    y: i32
}

impl Point {
    fn mag2(self) -> i32 {
        self.x * self.x + self.y * self.y
    }
}

fn main() {
    let p = Point { x: 3, y: 4 }
    print(p.x, p.y, p.mag2())
}

11. Enums and match

`enum Color { Red Rgb(i32, i32, i32) }`. Values: `Color::Red` or `Color::Rgb(1,2,3)`.

`match` uses `=>`. Built-in `Some` `None` `Ok` `Err` can be written without a path. Patterns: `_`, ints, bools, strings. No guards. For a custom enum write `match (value) { Color::Red => ... }`. `match value { Color::... }` is parsed as a struct literal because of `Color:`.

enum / match

enum Color {
    Red
    Rgb(i32, i32, i32)
}

fn main() {
    let c = Color::Rgb(1, 2, 3)
    match (c) {
        Color::Red => print("red")
        Color::Rgb(r, g, b) => print(r, g, b)
    }
}

12. Option, Result, ?

`Option[T]`: `Some(v)` / `None`. `Result[T,E]`: `Ok(v)` / `Err(e)`.

In a function that returns `Result`, `expr?` forwards `Err`. `?` does not work on `Option`. Otherwise `match`, or stop with `panic` / `assert`.

Result and ?

fn parse() -> Result[i32, str] {
    "41".parse_i32()
}

fn go() -> Result[i32, str] {
    let n = parse()?
    Ok(n + 1)
}

fn main() {
    match go() {
        Ok(n) => print(n)
        Err(e) => print(e)
    }
}

13. Ownership and borrows

Non-Copy values (`str`, `Vec`, `Map`, structs, enums) move into calls. Copy types: `i32` `i64` `f64` `bool` `()`.

Many `&T` at once; only one `&mut T`, and not together with shared borrows. Dereference with `*`. There is no lifetime syntax — storing a reference in a struct is rejected instead.

moves

fn take(s: str) {
    print(s)
}

fn main() {
    let s = "hi"
    take(s)
    // take(s)  // 錯誤:已被移動。要用 s.clone()
    let t = "ok".clone()
    print(t)
}

14. Modules

`mod math` loads `math.rsd` or `math/mod.rsd` beside the current file and merges items. No separate namespace, no `pub`. Cycles are skipped.

mod

// app.rsd
mod math

fn main() {
    print(add(2, 3))
}

// math.rsd(同目錄)
fn add(a: i32, b: i32) -> i32 {
    a + b
}

15. What else you can do

Output: `print(...)`. Math: `abs` `min` `max` `sqrt`. Time: `now_ms()` `sleep_ms(n)`. Tests: `assert`. Abort: `panic(str)`.

Threads: `spawn("name")` returns an `i32` id; `join(id)` waits. FFI whitelist: `extern_call("sin", x)`. Copy: `.clone()`.

built-ins

fn worker() {
    print("thread")
}

fn main() {
    print(abs(-3))
    print(min(2, 9))
    print(sqrt(9.0))
    print(extern_call("sin", 0.0))
    print(now_ms())
    let id = spawn("worker")
    join(id)
}

16. Files and HTTP

I/O returns `Result`. Paths and the network are sandboxed. `http_serve` is a loopback HTTP/1.0 server. A full sample site lives in `examples/site/` (routing, FizzBuzz, guestbook, `/api/stats`). Hard caps are in the next sections.

files / HTTP

fn on_request(method: str, path: str, query: str, body: str) -> str {
    "<p>" + path + "</p>"
}

fn main() {
    match write_file("out.txt", "hello") {
        Ok(_) => print("wrote")
        Err(e) => print(e)
    }
    match http_get("http://example.com/") {
        Ok(body) => print(body.len())
        Err(e) => print(e)
    }
    http_serve(4371, "on_request")
}

17. Tests

`russd test file.rsd` runs every function whose name starts with `test_`. Use `assert`. A dummy `fn main()` is still typical.

test_

fn test_add() {
    assert(1 + 2 == 3)
}

fn main() {}

18. Syntax limits (things that do not exist)

Russd looks like simplified Rust. These familiar pieces are missing on purpose. Read them before you fight the checker.

  • No `unsafe`, raw pointers, lifetimes `'a`, `dyn`, or `impl Trait`.
  • No `trait`, classes, inheritance, `super`, or `virtual`. Compose structs; put behavior in `impl`.
  • No generic functions or generic structs. Only built-in `Vec[T]`, `Map[V]`, `Option[T]`, `Result[T,E]` take type arguments, written with `[]` not `<>`.
  • No closures, function pointers, or passing `fn` as a value. `spawn` takes a function-name string.
  • No `use` / `pub` / `crate` / paths `foo::bar` (except enum variants like `Color::Red`). Modules flatten into one namespace.
  • No `const` or `static`.
  • No tuples except `()`, no fixed-size arrays, no `char`, no slices.
  • No `u8`/`u32`/`usize`/`f32`. Integers default to `i32`; write `i64` with an `i64` suffix. No `0x`/`0b` literals.
  • Identifiers are ASCII letters, digits, and `_` only. Chinese (or other non-ASCII) names are rejected.
  • Comments are `//` to end of line only. No `/* */`, no `///`, no attributes `#[...]`, no macros.
  • Strings are `"..."` with escapes `\n` `\t` `\\` `\"` only. No interpolation, no `format!`, no raw strings.
  • No `if let`, `while let`, or match guards. `else if` is allowed.
  • No inclusive range `..=`. `1..4` yields 1, 2, 3.
  • Compound assignment is only `+=` `-=` `*=`. No `/=` `%=` `&=` `|=`.
  • `&mut` currently applies to variables only, not arbitrary expressions.
  • Struct fields cannot be references (`x: &i32` is rejected). References live on locals and parameters only.
  • Enum variants are unit or tuple-like (`Rgb(i32,i32,i32)`), not struct-like `{ r, g, b }`.
  • No operator overloading. Only `Vec` supports `[]`. Maps use `.set` / `.get` and keys must be `str`.
  • `push`/`pop`/`set`/`clear`/`reverse` need a variable receiver: not `vec().push(1)`.
  • No type aliases and almost no `as` casts (`sqrt` will take `i32` as `f64`).
  • No `async`/`await`, channels, mutexes, Rc/Arc, or interior mutability. Concurrency is `spawn`/`join` only.
  • File top level allows only `fn` `struct` `enum` `impl` `mod`. No top-level `let`.
  • `russd run` needs `fn main()`. Tests must be named `test_*`; there is no `#[test]`.
  • `join` accepts only `Vec[str]`, not `Vec[i32]`.
  • `match x { Color::Red => ... }` is parsed as a struct literal. Write `match (x) { ... }`, or drop the prefix (`Red`, `Rgb(r,g,b)`).
  • Assignment targets are variables, struct fields, or `Vec` indexes. You cannot write `*x = ...` through `&mut`.

19. Runtime and safety limits

These rules are enforced now. If it is not on the allowed list, you cannot do it yet.

  • `i32` add/sub/mul overflow is an error, not wraparound. Division by zero and out-of-bounds indexes are errors, not undefined behavior.
  • `str` and `Vec` move on pass; using them afterwards fails at check time. Numbers, `bool`, and `()` copy. Use `.clone()` for a second owned value.
  • `read_file` / `write_file` only accept relative paths inside the working directory. Absolute paths and `..` are rejected.
  • A single write is capped at 1 MB.
  • `http_get` is `http://` only (no TLS/HTTPS), port 80 only, and it refuses localhost, private networks, and DNS that resolves private. URL max 2048 bytes, body max 256 KB, timeout about 5s.
  • `http_serve(port, handler)` binds `127.0.0.1` only, ports 1024–49151. The handler must be `fn(method, path, query, body) -> str`. An optional third argument caps how many requests to accept. No HTTPS, no raw sockets. See `examples/site/`.
  • `url_decode` decodes form URLs (`+` and `%XX`).
  • `sleep_ms` is capped at 5000 ms.
  • `spawn("name")` must be a ≤64-character ASCII identifier naming an existing zero-argument function. You cannot pass thread arguments or spawn OS processes.
  • `extern_call` is a whitelist: `sin` `cos` `sqrt` `floor` `ceil` `pow` `abs`. No `dlopen`, no arbitrary C.
  • No env vars, no stdin API, no arbitrary TCP/UDP (only `http_get` and loopback `http_serve`), no shell.
  • `str.len()` is bytes, not Unicode scalar count. No character iteration.
  • `print` joins arguments with spaces and adds a newline. No `println!` formatting.
  • The engine is an optimizing compiler plus a safe VM, not LLVM native code. It is not “the world’s fastest language.”