Skip to content
This repository was archived by the owner on Aug 18, 2025. It is now read-only.

Commit 25d2ac5

Browse files
committed
重构解析器和解释器以支持命名空间导入,增强了对库和代码命名空间的处理能力。更新了AST结构,添加了命名空间类型字段,并优化了相关函数的实现,提升了代码的可读性和可维护性。同时,修复了命名空间函数调用的解析逻辑,确保能够正确处理嵌套命名空间。
1 parent c55b0a9 commit 25d2ac5

File tree

14 files changed

+843
-192
lines changed

14 files changed

+843
-192
lines changed

examples/kaizaojiy.cn

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using lib <os>;
2+
using lib <io>;
3+
using lib <time>;
4+
using ns std;
5+
6+
fn main() : int {
7+
while (true) {
8+
exec("powershell", "-Command", "Clear-Host");
9+
println(" 🎃");
10+
println("██░░██");
11+
println(" ░░");
12+
sleep_seconds(0.2);
13+
exec("powershell", "-Command", "Clear-Host");
14+
println(" 🎃");
15+
println("░░██░░");
16+
println(" ██");
17+
sleep_seconds(0.2);
18+
};
19+
return 0;
20+
};

library_io/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,13 @@ pub extern "C" fn cn_init() -> *mut HashMap<String, LibraryFunction> {
145145
.add_function("println", std::cn_println)
146146
.add_function("read_line", std::cn_read_line)
147147
.add_function("printf", std::cn_printf);
148-
148+
/*
149149
// 同时注册为直接函数,不需要命名空间前缀
150150
registry.add_direct_function("print", std::cn_print)
151151
.add_direct_function("println", std::cn_println)
152152
.add_direct_function("read_line", std::cn_read_line)
153153
.add_direct_function("printf", std::cn_printf);
154-
154+
*/
155155
// 构建并返回库指针
156156
registry.build_library_pointer()
157157
}

namespace_mixed_test.cn

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// 测试混合使用库命名空间和代码命名空间
2+
3+
// 导入多个库
4+
using lib <io>;
5+
using lib <time>;
6+
using ns std;
7+
8+
// 创建自定义命名空间,其函数可能与库函数同名
9+
ns my_std {
10+
fn println(message : string) : void {
11+
// 调用真正的io库函数,但添加时间戳
12+
current_time : string = time::std::format_now("[%H:%M:%S] ");
13+
io::std::println(current_time + message);
14+
};
15+
16+
fn get_timestamp() : string {
17+
return time::std::now();
18+
};
19+
};
20+
21+
// 创建另一个命名空间
22+
ns app {
23+
fn version() : string {
24+
return "应用版本 2.0.0";
25+
};
26+
};
27+
28+
fn main() : int {
29+
// 直接使用库命名空间函数
30+
println("测试混合使用库命名空间和代码命名空间");
31+
32+
// 导入自定义命名空间
33+
using ns my_std;
34+
35+
// 现在使用自定义命名空间的函数,它会调用真正的库函数
36+
my_std::println("这条消息将带有时间戳");
37+
38+
// 获取并显示时间戳
39+
timestamp : string = my_std::get_timestamp();
40+
println("当前时间戳: " + timestamp);
41+
42+
// 导入并使用另一个命名空间
43+
using ns app;
44+
println(version());
45+
46+
// 直接使用完整路径,避免命名空间冲突
47+
io::std::println("这条消息直接使用io库,没有时间戳");
48+
49+
return 0;
50+
};

namespace_nested_test.cn

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// 测试嵌套命名空间
2+
3+
// 导入库命名空间
4+
using lib <io>;
5+
using ns std;
6+
7+
// 创建父命名空间
8+
ns parent {
9+
// 创建子命名空间
10+
ns child {
11+
fn hello() : string {
12+
return "来自嵌套命名空间的问候!";
13+
};
14+
15+
fn add(a : int, b : int) : int {
16+
return a + b;
17+
};
18+
};
19+
20+
// 父命名空间中的函数
21+
fn say_hello() : string {
22+
return "来自父命名空间的问候!";
23+
};
24+
};
25+
26+
// 定义另一个命名空间,与父命名空间同级
27+
ns utils {
28+
fn get_version() : string {
29+
return "1.0.0";
30+
};
31+
};
32+
33+
fn main() : int {
34+
// 使用库命名空间
35+
println("测试嵌套命名空间");
36+
37+
// 导入并使用嵌套命名空间
38+
using ns parent::child;
39+
greeting : string = hello();
40+
println(greeting);
41+
42+
// 导入父命名空间
43+
using ns parent;
44+
parent_greeting : string = say_hello();
45+
println(parent_greeting);
46+
47+
// 使用完整路径访问嵌套命名空间函数
48+
sum : int = parent::child::add(30, 40);
49+
println("30 + 40 = " + sum);
50+
51+
// 导入并使用另一个命名空间
52+
using ns utils;
53+
println("版本: " + get_version());
54+
55+
return 0;
56+
};

namespace_simple_test.cn

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// 测试简单的库函数调用
2+
3+
// 导入IO库
4+
using lib <io>;
5+
6+
fn main() : int {
7+
// 直接使用库函数
8+
io::std::println("测试简单的库函数调用");
9+
return 0;
10+
};

namespace_unified_test.cn

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// 测试统一的命名空间机制
2+
3+
// 导入库命名空间
4+
using lib <io>;
5+
6+
// 创建并使用代码命名空间
7+
ns math {
8+
fn add(a : int, b : int) : int {
9+
return a + b;
10+
};
11+
12+
fn multiply(a : int, b : int) : int {
13+
return a * b;
14+
};
15+
};
16+
17+
// 创建另一个命名空间
18+
ns string_utils {
19+
fn concat(a : string, b : string) : string {
20+
return a + b;
21+
};
22+
23+
fn repeat(text : string, count : int) : string {
24+
result : string = "";
25+
for (i : 0..count-1) {
26+
result = result + text;
27+
};
28+
return result;
29+
};
30+
};
31+
32+
fn main() : int {
33+
// 使用库命名空间函数
34+
io::std::println("测试统一的命名空间机制");
35+
36+
// 从代码命名空间导入函数
37+
using ns math;
38+
using ns string_utils;
39+
40+
// 直接使用已导入的命名空间函数
41+
sum : int = add(10, 20);
42+
io::std::println("10 + 20 = " + sum);
43+
44+
product : int = multiply(5, 6);
45+
io::std::println("5 * 6 = " + product);
46+
47+
// 使用string_utils命名空间函数
48+
message : string = concat("Hello, ", "World!");
49+
io::std::println(message);
50+
51+
repeated : string = repeat("-=", 10);
52+
io::std::println(repeated);
53+
54+
// 使用完整的命名空间路径
55+
full_sum : int = math::add(100, 200);
56+
io::std::println("使用完整路径: 100 + 200 = " + full_sum);
57+
58+
return 0;
59+
};

src/ast.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,13 @@ pub enum Expression {
3535
// 未来可以扩展更多表达式类型
3636
}
3737

38+
// 命名空间类型
39+
#[derive(Debug, Clone, PartialEq)]
40+
pub enum NamespaceType {
41+
Code, // 代码命名空间 (ns xxx)
42+
Library, // 库命名空间 (lib xxx)
43+
}
44+
3845
#[derive(Debug, Clone)]
3946
pub enum BinaryOperator {
4047
Add,
@@ -71,8 +78,7 @@ pub enum Statement {
7178
PreIncrement(String), // 前置自增语句 (++var)
7279
PreDecrement(String), // 前置自减语句 (--var)
7380
CompoundAssignment(String, BinaryOperator, Expression), // 复合赋值 (+=, -=, *=, /=, %=)
74-
UsingNamespace(Vec<String>), // 导入命名空间 (using ns xxx;)
75-
LibraryImport(String), // 导入动态库 (using lib_once <xxx>;)
81+
ImportNamespace(NamespaceType, Vec<String>), // 统一的命名空间导入,第一个参数表示类型,第二个参数是路径
7682
FileImport(String), // 导入文件 (using file "xxx.cn";)
7783
FunctionCallStatement(Expression), // 函数调用语句
7884
NamespacedFunctionCallStatement(Vec<String>, Vec<Expression>), // 命名空间函数调用语句 (ns::func())
@@ -102,6 +108,7 @@ pub struct Function {
102108
#[derive(Debug, Clone)]
103109
pub struct Namespace {
104110
pub name: String,
111+
pub ns_type: NamespaceType, // 添加命名空间类型字段
105112
pub functions: Vec<Function>,
106113
pub namespaces: Vec<Namespace>, // 嵌套命名空间
107114
}
@@ -110,6 +117,6 @@ pub struct Namespace {
110117
pub struct Program {
111118
pub functions: Vec<Function>,
112119
pub namespaces: Vec<Namespace>, // 顶层命名空间
113-
pub library_imports: Vec<String>, // 顶层库导入
120+
pub imported_namespaces: Vec<(NamespaceType, Vec<String>)>, // 统一的导入记录
114121
pub file_imports: Vec<String>, // 顶层文件导入
115122
}

src/interpreter/library_loader.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use std::env;
55
use libloading::{Library, Symbol};
66
use once_cell::sync::Lazy;
77
use crate::interpreter::debug_println;
8+
use crate::interpreter::value::Value;
89

910
// 已加载库的缓存,使用Lazy静态变量确保线程安全的初始化
1011
static LOADED_LIBRARIES: Lazy<Arc<Mutex<HashMap<String, Arc<Library>>>>> =
@@ -46,6 +47,18 @@ fn get_library_path(lib_name: &str) -> PathBuf {
4647
path
4748
}
4849

50+
// 添加一个函数来打印库中的所有函数
51+
pub fn debug_library_functions(lib_name: &str) -> Result<(), String> {
52+
let functions = load_library(lib_name)?;
53+
54+
debug_println(&format!("库 '{}' 中的所有函数:", lib_name));
55+
for (func_name, _) in functions.iter() {
56+
debug_println(&format!(" - {}", func_name));
57+
}
58+
59+
Ok(())
60+
}
61+
4962
// 加载库并返回其函数映射
5063
pub fn load_library(lib_name: &str) -> Result<Arc<HashMap<String, LibraryFunction>>, String> {
5164
debug_println(&format!("开始加载库: {}", lib_name));
@@ -206,4 +219,33 @@ pub fn call_library_function(lib_name: &str, func_name: &str, args: Vec<String>)
206219
},
207220
None => Err(format!("库 '{}' 中未找到函数 '{}'", lib_name, func_name)),
208221
}
222+
}
223+
224+
// 新增函数,将Value类型转换为字符串参数
225+
pub fn convert_value_to_string_arg(value: &Value) -> String {
226+
match value {
227+
Value::Int(i) => i.to_string(),
228+
Value::Float(f) => f.to_string(),
229+
Value::Bool(b) => b.to_string(),
230+
Value::String(s) => s.clone(),
231+
Value::Long(l) => l.to_string(),
232+
Value::Array(arr) => {
233+
let elements: Vec<String> = arr.iter()
234+
.map(|v| convert_value_to_string_arg(v))
235+
.collect();
236+
format!("[{}]", elements.join(", "))
237+
},
238+
Value::Map(map) => {
239+
let entries: Vec<String> = map.iter()
240+
.map(|(k, v)| format!("{}:{}", k, convert_value_to_string_arg(v)))
241+
.collect();
242+
format!("{{{}}}", entries.join(", "))
243+
},
244+
Value::None => "null".to_string(),
245+
}
246+
}
247+
248+
// 从Vector<Value>转换为Vector<String>,用于库函数调用
249+
pub fn convert_values_to_string_args(values: &[Value]) -> Vec<String> {
250+
values.iter().map(|v| convert_value_to_string_arg(v)).collect()
209251
}

0 commit comments

Comments
 (0)