如何使用、如何寫程式
這頁教 Russd 怎麼寫:語法、你實際能做的事,以及一長串刻意加上的限制。安裝與下載請看「下載核心」;專案設定請看「如何設定」。
1. 程式長什麼樣子
原始檔副檔名是 `.rsd`。`russd run` 要有 `fn main()`。分號可寫可不寫。區塊最後一個表達式就是回傳值,不必處處 `return`。
註解只有 `//`。關鍵字:`fn` `let` `mut` `if` `else` `while` `for` `in` `loop` `break` `continue` `struct` `enum` `match` `impl` `return` `true` `false` `self` `mod`。
先進入倉庫:`cd russd-core`(`Cargo.toml` 在這裡;停在上一層會報 `could not find Cargo.toml`)。再跑 `cargo run -- examples/hello.rsd`(`--` 與檔名分開寫;不要寫成 `cargo run --run`)。程式參數再加一組 `--`:`cargo run -- examples/hello.rsd -- foo`,用 `args()` 讀成 `Vec[str]`。
hello.rsd
fn greet(name: str) -> str {
"Hello, " + name
}
fn main() {
print(greet("Russd"))
}編譯器會最佳化
Russd 是最佳化編譯器。預設 `-O2`:常數摺疊、`x+0`/`x*1` 這類代數簡化、`if true` 刪掉死分支、小型函式內聯、沒用到的 `let` 刪除、bytecode peephole。
`russd run f.rsd -O0` 關掉最佳化。`russd opt f.rsd` 印摺疊/內聯/刪碼次數與 bytecode。溢位與除零不會被摺成繞回。後端仍是安全 VM,不是 LLVM 原生碼。
看最佳化
russd opt examples/hello.rsd
russd run examples/fizzbuzz.rsd -O2
russd run examples/fizzbuzz.rsd -O02. 型別
內建型別:`i32` `i64` `f64` `bool` `str` `()` `Vec[T]` `Map[V]` `Option[T]` `Result[T,E]`。泛型參數用方括號。
整數字面值預設是 `i32`。超過 `i32` 要寫成 `10000000000i64`,否則型別檢查會擋。浮點要有小數點,例如 `3.14`。
型別
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. 變數
`let` 不可變;`let mut` 才能再賦值。可以寫 `let n: i32 = 1` 標型別,也可以靠推斷。
賦值目標必須是變數、結構欄位、或 `Vec` 索引。不能對不可變綁定賦值。
let / let mut
fn main() {
let a = 1
let mut b = 2
b = b + a
b += 3
print(b)
}4. 運算子
算術 `+ - * / %`(`+` 也可接字串)。比較 `== != < <= > >=`。邏輯 `&& || !`。位元 `& | ^ ~ << >>`。
運算子沒有多載:`+` 不能拿來加兩個結構。比較目前只允許數字。
運算
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. 控制流程
`if` / `else if` / `else` 是表達式,分支要用 `{ }`。`while` 條件必須是 `bool`。
`for x in xs` 可走 `Vec` 或範圍 `1..n`(不含 n)。`loop` 搭配 `break` / `continue`。`break` 不能帶值。
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. 函式
寫法:`fn 名稱(參數: 型別) -> 回傳型別 { ... }`。省略 `->` 就是 `()`。
參數可為值、`mut x: T`、`&T`、`&mut T`。`impl` 裡可用 `self`、`&self`、`&mut self`。沒有預設參數、沒有可變參數、沒有泛型參數。可變狀態主要靠 `let mut` 與 Vec/Map 方法;`*x = ...` 還不能用來寫回引用。
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. 字串
`str` 是擁有所有權的字串。方法:`len` `is_empty` `contains` `split` `replace` `trim` `to_upper` `to_lower` `starts_with` `ends_with` `parse_i32`。
`parse_i32` 回傳 `Result[i32, str]`。`len` 是 UTF-8 位元組數。
字串方法
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(...)` 建立向量,可帶初始元素。`push` `pop` `clear` `reverse` 會改原向量,接收者必須是變數。
索引 `xs[i]` 只接受整數;越界執行期錯誤。`for x in xs` 會走過元素。`join(sep)` 只適用於 `Vec[str]`。
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()` 不接受參數。值型別寫在 `Map[V]`。鍵永遠是 `str`,用 `.set(k, v)` 與 `.get(k)`(回 `Option[V]`),不能 `m["k"]`。
還有 `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. 結構與 impl
具名欄位結構:`struct Point { x: i32 y: i32 }`。建構:`Point { x: 3, y: 4 }`。欄位必須一次給齊、名稱必須對。
`impl Point { fn mag2(self) -> i32 { ... } }` 給方法。沒有繼承、沒有建構子關鍵字、沒有私有欄位。
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. 列舉與 match
自訂列舉:`enum Color { Red Rgb(i32, i32, i32) }`。值寫 `Color::Red` 或 `Color::Rgb(1,2,3)`。
`match` 用 `=>`。內建 `Some(x)` `None` `Ok(x)` `Err(e)` 可直接寫。也可用 `_`、整數、布林、字串模式。沒有 guard。對自訂列舉請寫 `match (值) { Color::Red => ... }`:若寫 `match 值 { Color::... }`,`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)`。
在回傳 `Result` 的函式裡,`expr?` 遇到 `Err` 會立刻回傳那個錯誤。`?` 不能用在 `Option`。失敗要處理就 `match`,或 `panic("...")` / `assert(條件)` 直接停。
Result 與 ?
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. 所有權與借用
非 Copy 值(`str`、`Vec`、`Map`、結構、列舉)傳進函式會被移動,不能再用。Copy 的有 `i32` `i64` `f64` `bool` `()`。
`&T` 可同時有多個;`&mut T` 同時只能一個,且不能再同時有共享借用。解引用用 `*`。沒有生命週期標註可寫——編譯器拒絕把引用塞進結構,問題直接不存在。
移動
fn take(s: str) {
print(s)
}
fn main() {
let s = "hi"
take(s)
// take(s) // 錯誤:已被移動。要用 s.clone()
let t = "ok".clone()
print(t)
}14. 模組
`mod math` 會載入同目錄 `math.rsd` 或 `math/mod.rsd`,把裡面的項目合併進目前程式。沒有獨立命名空間、沒有 `pub`。循環載入會被跳過。
mod
// app.rsd
mod math
fn main() {
print(add(2, 3))
}
// math.rsd(同目錄)
fn add(a: i32, b: i32) -> i32 {
a + b
}15. 你還能做的事(內建)
輸出:`print(...)`。數學:`abs` `min` `max` `sqrt`。時間:`now_ms()` `sleep_ms(n)`。測試:`assert(bool)`。中止:`panic(str)`。
執行緒:`spawn("函式名")` 回 `i32` id,再用 `join(id)`。FFI 白名單:`extern_call("sin", x)` 等。複製:`.clone()`。
內建
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. 檔案與 HTTP
I/O 回 `Result`。路徑與網路都有沙盒,失敗是 `Err`,不是默默讀到系統檔。`http_serve` 在本機開 HTTP/1.0。完整網站範例在 `examples/site/`(路由、FizzBuzz、留言板、`/api/stats`)。細節見下一節限制清單。
檔案 / 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. 測試
`russd test 檔案.rsd` 會執行所有名稱以 `test_` 開頭的函式。用 `assert` 檢查。不必有 `main` 邏輯,但檔案裡通常仍放一個空的 `fn main()`。
test_
fn test_add() {
assert(1 + 2 == 3)
}
fn main() {}18. 語法限制(刻意沒有的東西)
Russd 看起來像簡化的 Rust,但下面這些你在 Rust 裡習慣的寫法,這裡都沒有。寫之前先看完,少踩編譯器。
- 沒有 `unsafe`、原始指標、生命週期 `'a`、`dyn`、`impl Trait`。
- 沒有 `trait`、class、繼承、`super`、`virtual`。結構用欄位組合,行為寫在 `impl`。
- 沒有泛型函式或泛型結構。只有內建 `Vec[T]`、`Map[V]`、`Option[T]`、`Result[T,E]` 帶型別參數,語法用 `[]` 不是 `<>`。
- 沒有閉包、函式指標、把 `fn` 當值傳遞。`spawn` 只接受函式名稱字串。
- 沒有 `use` / `pub` / `crate` / 路徑 `foo::bar`(列舉變體 `Color::Red` 除外)。模組是扁平合併,名稱會撞車。
- 沒有 `const`、`static`、執行期全域可變狀態。
- 沒有 tuple(只有 `()`)、沒有固定長度陣列、沒有 `char`、沒有 slice。
- 沒有 `u8`/`u32`/`usize`/`f32`。整數預設 `i32`,超過請加 `i64` 後綴。沒有 `0x`/`0b` 字面值。
- 識別字只能 ASCII 字母、數字、底線;不能用中文當變數名。
- 註解只有 `//` 到行尾。沒有 `/* */`、沒有 `///` 文件註解、沒有屬性 `#[...]`、沒有巨集。
- 字串只有 `"..."`,跳脫只允許 `\n` `\t` `\\` `\"`。沒有字串插值、沒有 `format!`、沒有原始字串 `r""`。
- 沒有 `else if` 關鍵字以外的 `if let` / `while let` / match guard(`if` 條件)。`else if` 可以用。
- 沒有 `..=` 含端點範圍。`1..4` 是 1、2、3。
- 複合賦值只有 `+=` `-=` `*=`,沒有 `/=` `%=` `&=` `|=`。
- `&mut` 目前只能取變數位址,不能對任意表達式取可變引用。
- 結構欄位不能是引用(`x: &i32` 會被拒絕)。引用只活在區域變數與參數上。
- 列舉變體只能是無欄位或元組欄位 `Rgb(i32,i32,i32)`,沒有結構體變體 `Rgb { r, g, b }`。
- 沒有運算子多載、沒有 `Index` trait。只有 `Vec` 能用 `[]`。`Map` 必須 `.set` / `.get`,鍵必須是 `str`。
- `push`/`pop`/`set`/`clear`/`reverse` 的接收者必須是變數,不能寫 `vec().push(1)`。
- 沒有型別別名、沒有 `as` 轉型(少數內建如 `sqrt` 會把 `i32` 當 `f64`)。
- 沒有 `async`/`await`、channel、mutex、Rc/Arc、內部可變。並行只有 `spawn`/`join`。
- 檔案頂層只能出現 `fn` `struct` `enum` `impl` `mod`。不能在頂層寫 `let`。
- `russd run` 需要 `fn main()`。測試函式名稱必須以 `test_` 開頭,沒有 `#[test]`。
- `join` 只接受 `Vec[str]`,不能對 `Vec[i32]` 呼叫。
- `match x { Color::Red => ... }` 會被解析成結構字面值。請寫 `match (x) { ... }`,或模式只寫 `Red` / `Rgb(r,g,b)`。
- 賦值左邊只能是變數、結構欄位或 `Vec` 索引。不能寫 `*x = ...` 把值寫回 `&mut`。
19. 執行期與安全限制
這些不是「還沒做完」的含糊承諾,而是執行期現在就會執行的規則。想做清單以外的事,目前就是不行。
- `i32` 加減乘溢位是錯誤,不是繞回。除零、向量越界也是錯誤,不是未定義行為。
- `str` 與 `Vec` 傳遞會移動;之後再用會編譯失敗。數字、`bool`、`()` 會複製。需要第二份就 `.clone()`。
- `read_file` / `write_file` 只能碰工作目錄內的相對路徑。絕對路徑、`..`、超出 cwd 一律拒絕。
- 單次寫入上限 1 MB。
- `http_get` 只接受 `http://`(沒有 TLS、沒有 HTTPS)、只連埠 80、拒絕 localhost / 私有網段 / DNS 指到內網。URL 最長 2048。回應最多 256 KB。逾時約 5 秒。
- `http_serve(port, handler)` 只綁 `127.0.0.1`,埠 1024–49151。`handler` 必須是 `fn(method, path, query, body) -> str`。第三個參數可限制請求次數。沒有 HTTPS、沒有任意 socket。完整範例:`examples/site/`。
- `url_decode` 解 `application/x-www-form-urlencoded`(`+` 與 `%XX`)。
- `sleep_ms` 最多睡 5000 毫秒,再大也會被截斷。
- `spawn("name")` 的名稱必須是 ≤64 字元的 ASCII 識別字,對應現有無參數函式。不能傳參數進執行緒,也不能 spawn 作業系統指令。
- `extern_call` 白名單只有 `sin` `cos` `sqrt` `floor` `ceil` `pow` `abs`。不能 `dlopen`、不能呼叫任意 C 函式。
- 沒有讀環境變數、沒有標準輸入 API、沒有任意 TCP/UDP(只有 `http_get` 與本機 `http_serve`)、沒有執行 shell。
- `str.len()` 是位元組數,不是 Unicode 字數。沒有字元迭代。
- `print` 把參數用空白接起來並換行。沒有 `println!` 格式化。
- 執行器是最佳化編譯器 + 安全 VM,不是 LLVM 機器碼。不要期待原生碼那種「世界最快」。