X语言规范

1. 简介

X语言是一种现代、安全、高效的编程语言,设计目标是提供一种既具有高级语言表达能力,又具有接近低级语言性能的编程体验。

2. 词法结构

2.1 关键字

X语言的关键字包括:

fn let mut const struct enum
if else for while match return
import export module use type trait
impl self super pub priv async
await try catch throw option result
            

2.2 标识符

标识符由字母、数字和下划线组成,必须以字母或下划线开头。X语言区分大小写。

// 有效的标识符
let x = 5;
let _value = "hello";
let userName = "John";

// 无效的标识符
let 123abc = 10; // 不能以数字开头
let my-variable = 20; // 不能包含连字符
            

3. 数据类型

3.1 基本类型

3.2 复合类型

3.3 用户定义类型

4. 语法结构

4.1 变量声明

// 不可变变量
let x: i32 = 5;

// 可变变量
let mut y = 10;
y = 15; // 允许修改

// 常量
const PI: f64 = 3.14159;
            

4.2 函数定义

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

// 简短函数语法
fn subtract(a: i32, b: i32) -> i32 = a - b;
            

4.3 控制流

// if-else 语句
if x > 0 {
    print("x is positive");
} else if x < 0 {
    print("x is negative");
} else {
    print("x is zero");
}

// for 循环
for i in 0..10 {
    print(i);
}

// while 循环
let mut i = 0;
while i < 10 {
    print(i);
    i += 1;
}

// match 语句
match x {
    1 => print("one"),
    2 => print("two"),
    _ => print("other"),
}
            

4.4 结构体和枚举

// 结构体定义
struct Person {
    name: string,
    age: u32,
}

// 枚举定义
enum Option<T> {
    Some(T),
    None,
}
            

5. 模块系统

// 模块定义
module utils {
    pub fn add(a: i32, b: i32) -> i32 {
        return a + b;
    }
}

// 导入模块
import utils;

// 使用模块中的函数
let result = utils::add(1, 2);
            

6. 特质和实现

// 特质定义
trait Drawable {
    fn draw(&self);
}

// 实现特质
struct Circle {
    radius: f64,
}

impl Drawable for Circle {
    fn draw(&self) {
        print("Drawing a circle with radius {}", self.radius);
    }
}
            

7. 错误处理

// Option 类型
fn divide(a: f64, b: f64) -> Option<f64> {
    if b == 0.0 {
        return None;
    }
    return Some(a / b);
}

// Result 类型
fn read_file(path: string) -> Result<string, string> {
    // 模拟文件读取
    if path == "nonexistent.txt" {
        return Err("File not found".to_string());
    }
    return Ok("File content".to_string());
}