如何使用、如何写程序
本页教 Russd 怎么写:语法、你实际能做的事,以及一长串刻意加上的限制。安装与下载见「下载核心」;项目配置见「如何配置」。
1. 程序长什么样
源文件扩展名是 `.rsd`。`russd run` 需要 `fn main()`。分号可写可不写。块里最后一个表达式就是返回值。
注释只有 `//`。关键字:`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`。超出范围要写 `i64` 后缀。浮点要有小数点,例如 `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]` 只接受整数;越界是运行时错误。`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` 与 `.get`(返回 `Option`),不能 `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 { ... }` 给方法。没有继承、没有构造函数关键字、没有私有字段。
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` `None` `Ok` `Err` 可直接写。也可用 `_`、整数、布尔、字符串模式。没有 guard。自定义枚举请写 `match (值) { Color::Red => ... }`:`match 值 { 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`。中止:`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`。路径与网络都有沙盒。`http_serve` 在本机开 HTTP/1.0。完整网站例子在 `examples/site/`。细节见下一节限制清单。
文件 / 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` 检查。通常仍放一个空的 `fn main()`。
test_
fn test_add() {
assert(1 + 2 == 3)
}
fn main() {}18. 语法限制(刻意没有的东西)
Russd 看起来像简化的 Rust,但下面这些写法这里都没有。写之前先看完。
- 没有 `unsafe`、原始指针、生命周期 `'a`、`dyn`、`impl Trait`。
- 没有 `trait`、class、继承、`super`。结构靠字段组合,行为写在 `impl`。
- 没有泛型函数或泛型结构。只有内建 `Vec[T]`、`Map[V]`、`Option[T]`、`Result[T,E]` 带类型参数,写法是 `[]` 不是 `<>`。
- 没有闭包、函数指针、把 `fn` 当值传递。`spawn` 只接受函数名字符串。
- 没有 `use` / `pub` / `crate` / 路径 `foo::bar`(枚举变体 `Color::Red` 除外)。模块是扁平合并。
- 没有 `const`、`static`。
- 没有元组(只有 `()`)、没有定长数组、没有 `char`、没有 slice。
- 没有 `u8`/`u32`/`usize`/`f32`。整数默认 `i32`,更大请加 `i64` 后缀。没有 `0x`/`0b` 字面量。
- 标识符只能是 ASCII 字母、数字、下划线;不能用中文当变量名。
- 注释只有 `//` 到行尾。没有 `/* */`、没有 `///`、没有属性 `#[...]`、没有宏。
- 字符串只有 `"..."`,转义只允许 `\n` `\t` `\\` `\"`。没有插值、没有 `format!`。
- 没有 `if let` / `while let` / match guard。可以用 `else if`。
- 没有 `..=`。`1..4` 是 1、2、3。
- 复合赋值只有 `+=` `-=` `*=`,没有 `/=` `%=` `&=`。
- `&mut` 目前只能取变量地址。
- 结构字段不能是引用。引用只活在局部变量和参数上。
- 枚举变体只能是无字段或元组字段,没有结构体变体。
- 没有运算符重载。只有 `Vec` 能用 `[]`。`Map` 必须 `.set` / `.get`,键必须是 `str`。
- `push`/`pop`/`set`/`clear`/`reverse` 的接收者必须是变量。
- 没有类型别名,几乎没有 `as` 转型。
- 没有 `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` 只能碰工作目录内的相对路径。绝对路径、`..` 一律拒绝。
- 单次写入上限 1 MB。
- `http_get` 只接受 `http://`(没有 TLS/HTTPS)、只连端口 80、拒绝 localhost / 私有网段。URL 最长 2048。响应最多 256 KB。超时约 5 秒。
- `http_serve(port, handler)` 只绑定 `127.0.0.1`,端口 1024–49151。处理函数必须是 `fn(method, path, query, body) -> str`。完整例子:`examples/site/`。
- `url_decode` 解码表单 URL(`+` 与 `%XX`)。
- `sleep_ms` 最多睡 5000 毫秒。
- `spawn("name")` 必须是 ≤64 字符的 ASCII 标识符,对应已有无参数函数。不能传参数进线程,也不能 spawn 操作系统命令。
- `extern_call` 白名单只有 `sin` `cos` `sqrt` `floor` `ceil` `pow` `abs`。不能 `dlopen`。
- 没有读环境变量、没有标准输入 API、没有任意 TCP/UDP(只有 `http_get` 和本机 `http_serve`)、没有执行 shell。
- `str.len()` 是字节数,不是 Unicode 字符数。
- `print` 用空格拼接参数并换行。没有 `println!` 格式化。
- 执行器是优化编译器 + 安全 VM,不是 LLVM 机器码。