feat: add managed types, source classes and scoped native calls

This commit is contained in:
2026-10-21 01:47:08 +08:00
parent 7c842789c0
commit a970fd7707
48 changed files with 2069 additions and 134 deletions
+2 -2
View File
@@ -3,7 +3,7 @@
| 文件 | 职责 |
| --- | --- |
| [lib.rs](lib.rs) | CompileOptions、公开分析/编译入口、AST 原文范围检查与带来源诊断 |
| [analysis.rs](analysis.rs) | 模块/函数/表达式/单次交互作用域、局部槽、全局名称、逐引用绑定和初始化检查 |
| [codegen.rs](codegen.rs) | AST 到已有指令、嵌套代码模板、EndorCode 验证、显式 VM 装载与临时根释放 |
| [analysis.rs](analysis.rs) | 模块/函数/类方法/表达式/单次交互作用域、局部槽、全局名称、逐引用绑定和初始化检查 |
| [codegen.rs](codegen.rs) | AST 到函数与类创建指令、嵌套代码模板、EndorCode 验证、显式 VM 装载与临时根释放 |
节点定义在 frontend/Endor.asdl;这里匹配生成的 AST,不复制节点类型。源码和调用方提供的 AST 都先分析后生成,不执行 AST。修改名称语义、代码布局或所有权时同步 [编译契约](../../../docs/runtime/compiler.md)、[检查](../tests/README.md) 与 [示例](../examples/README.md)。返回 [compiler](../README.md)。
+66 -17
View File
@@ -39,7 +39,7 @@ pub struct Scope {
#[derive(Debug, Clone)]
pub struct SymbolTable {
pub root: Scope,
/// Top-level function scopes in declaration order. Nested declarations
/// Function and class-method scopes in declaration order. Nested declarations
/// are rejected until source closure semantics are implemented.
pub functions: Vec<Scope>,
}
@@ -48,9 +48,11 @@ fn error(span: Span, message: impl Into<String>) -> Diagnostic {
diagnostic(DiagnosticKind::Semantic, span, message)
}
fn definition(declaration: &Decl) -> &Function {
let DeclKind::Function(function) = &declaration.kind;
function
fn declaration_name(declaration: &Decl) -> &frontend::ast::Name {
match &declaration.kind {
DeclKind::Function(function) => &function.name,
DeclKind::Class(class) => &class.name,
}
}
/// Resolve a closed source unit plus explicitly declared host globals.
@@ -69,21 +71,25 @@ pub fn analyze(root: &AstRoot, options: &CompileOptions) -> Result<SymbolTable,
if globals.contains("") {
return Err(error(root.span(), "host global names must not be empty"));
}
let functions: Vec<&Function> = match root {
AstRoot::Module(program) => program.declarations.iter().map(definition).collect(),
let declarations: Vec<&Decl> = match root {
AstRoot::Module(program) => program.declarations.iter().collect(),
AstRoot::Interactive(input) => input
.statements
.iter()
.filter_map(|statement| {
if let StmtKind::Declaration(declaration) = &statement.kind {
Some(definition(declaration))
} else {
None
}
.filter_map(|statement| match &statement.kind {
StmtKind::Declaration(declaration) => Some(declaration),
_ => None,
})
.collect(),
AstRoot::Expression(_) => Vec::new(),
};
let functions: Vec<&Function> = declarations
.iter()
.flat_map(|declaration| match &declaration.kind {
DeclKind::Function(function) => vec![function],
DeclKind::Class(class) => class.methods.iter().collect(),
})
.collect();
let (kind, name) = match root {
AstRoot::Module(_) => (ScopeKind::Module, "<module>"),
AstRoot::Expression(_) => (ScopeKind::Expression, "<expression>"),
@@ -91,10 +97,43 @@ pub fn analyze(root: &AstRoot, options: &CompileOptions) -> Result<SymbolTable,
};
let mut root_scope = Builder::new(kind, name, root.span());
let mut declared = BTreeSet::new();
for function in &functions {
declare(&mut declared, &function.name.text, function.name.span)?;
globals.insert(function.name.text.clone());
root_scope.intern(&function.name.text);
for declaration in &declarations {
let name = declaration_name(declaration);
declare(&mut declared, &name.text, name.span)?;
globals.insert(name.text.clone());
root_scope.intern(&name.text);
}
for declaration in &declarations {
if let DeclKind::Class(class) = &declaration.kind {
let base_name = class
.base
.as_ref()
.map_or("Object", |base| base.text.as_str());
if !globals.contains(base_name) {
return Err(error(
class.span,
format!("class base is not supplied: {base_name}"),
));
}
root_scope.intern(base_name);
let mut members = BTreeSet::new();
for field in &class.fields {
declare(&mut members, &field.name.text, field.span)?;
}
for method in &class.methods {
declare(&mut members, &method.name.text, method.span)?;
if method
.parameters
.first()
.is_none_or(|parameter| parameter.name.text != "self")
{
return Err(error(
method.span,
"class method requires an explicit first self parameter",
));
}
}
}
}
// Analyze all bodies after registering all functions, enabling forward
// references and recursion without instantiating function objects here.
@@ -119,6 +158,11 @@ pub fn analyze(root: &AstRoot, options: &CompileOptions) -> Result<SymbolTable,
globals.insert(assignment.name.text.clone());
root_scope.intern(&assignment.name.text);
}
StmtKind::MemberAssignment(assignment) => {
root_scope.expression(&assignment.object, &globals)?;
root_scope.expression(&assignment.value, &globals)?;
root_scope.intern(&assignment.name.text);
}
StmtKind::Declaration(_) => {}
StmtKind::Expression(expression) => {
root_scope.expression(expression, &globals)?
@@ -181,7 +225,7 @@ fn function_scope(function: &Function, globals: &BTreeSet<String>) -> Result<Sco
StmtKind::Declaration(_) => {
return Err(error(
statement.span,
"nested function declarations are not compiled yet",
"nested declarations are not compiled yet",
));
}
_ => {}
@@ -210,6 +254,11 @@ fn function_scope(function: &Function, globals: &BTreeSet<String>) -> Result<Sco
}
returned = true;
}
StmtKind::MemberAssignment(assignment) => {
builder.expression(&assignment.object, globals)?;
builder.expression(&assignment.value, globals)?;
builder.intern(&assignment.name.text);
}
StmtKind::Expression(expression) => builder.expression(expression, globals)?,
StmtKind::Declaration(_) => unreachable!("nested declaration rejected above"),
}
+39 -2
View File
@@ -150,7 +150,39 @@ impl<'a> Emitter<'a> {
}
fn declaration(&mut self, declaration: &Decl, symbols: &SymbolTable) -> Result<(), Diagnostic> {
let DeclKind::Function(function) = &declaration.kind;
match &declaration.kind {
DeclKind::Function(function) => {
self.function_value(function, symbols)?;
self.emit(Opcode::StoreGlobal, self.name_index(&function.name.text))
}
DeclKind::Class(class) => {
self.constant(Value::Text(class.name.text.clone()))?;
let base = class
.base
.as_ref()
.map_or("Object", |base| base.text.as_str());
self.emit(Opcode::LoadGlobal, self.name_index(base))?;
for field in &class.fields {
self.constant(Value::Text(field.name.text.clone()))?;
self.constant(Value::Text(field.type_name.text.clone()))?;
}
self.emit(Opcode::BuildMap, class.fields.len())?;
for method in &class.methods {
self.constant(Value::Text(method.name.text.clone()))?;
self.function_value(method, symbols)?;
}
self.emit(Opcode::BuildMap, class.methods.len())?;
self.simple(Opcode::BuildClass);
self.emit(Opcode::StoreGlobal, self.name_index(&class.name.text))
}
}
}
fn function_value(
&mut self,
function: &frontend::ast::Function,
symbols: &SymbolTable,
) -> Result<(), Diagnostic> {
let scope = symbols
.functions
.iter()
@@ -176,7 +208,7 @@ impl<'a> Emitter<'a> {
self.children.push((index, child));
self.constant(Value::Nil)?; // Replaced by a managed code object during load().
self.instructions.push(Instruction::make_function(0, 0));
self.emit(Opcode::StoreGlobal, self.name_index(&function.name.text))
Ok(())
}
fn store_binding(&mut self, name: &str, value: &Expr) -> Result<(), Diagnostic> {
@@ -202,6 +234,11 @@ impl<'a> Emitter<'a> {
StmtKind::Assignment(assignment) => {
self.store_binding(&assignment.name.text, &assignment.value)?
}
StmtKind::MemberAssignment(assignment) => {
self.expression(&assignment.value)?;
self.expression(&assignment.object)?;
self.emit(Opcode::StoreAttr, self.name_index(&assignment.name.text))?;
}
StmtKind::Return(statement) => {
if let Some(value) = &statement.value {
self.expression(value)?;
+2
View File
@@ -1,5 +1,7 @@
# 编译链路检查
[classes.rs](classes.rs) 覆盖源码 class、继承字段构造、动态方法覆盖、绑定接收者保活/回收、绑定后参数数量和重复成员/缺少 self 的预执行诊断。只编译,不在本地运行。
[pipeline.rs](pipeline.rs) 将真实 Endor 示例交给 reader/parser/名称分析/代码生成/VM,检查函数值、前向引用、局部遮蔽、精确数字常量、语义诊断、宿主全局与属性回调、对象结果保活、跨 VM 模板装载、反复调用、错误帧清理、递归限额、共享交互命名空间及超过 255 的操作数。
裸赋值检查覆盖跨交互输入创建/更新 globals、参数重赋值、局部槽复用及未初始化读取;执行结束检查空堆。
+115
View File
@@ -0,0 +1,115 @@
use compiler::{CompileOptions, compile_source};
use endor_core::{ObjectRef, Value, Vm};
use frontend::{EndorReader, ParseMode};
fn execute(vm: &mut Vm, globals: ObjectRef, source: &str, mode: ParseMode) -> Value {
let names = vm
.dict_items(globals)
.unwrap()
.iter()
.filter_map(|(name, _)| {
if let Value::Text(name) = name {
Some(name.clone())
} else {
None
}
})
.collect();
let source = EndorReader::from_text("<classes>", source);
let template = compile_source(&source, mode, &CompileOptions { globals: names }).unwrap();
let code = template.load(vm).unwrap();
let result = vm.execute(code, globals).unwrap();
vm.release(code).unwrap();
result
}
#[test]
fn source_inheritance_binding_and_dynamic_dispatch_keep_the_real_receiver_alive() {
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
let roots = vm.bootstrap_types().unwrap();
for (name, object) in [("Object", roots.object), ("Type", roots.type_type)] {
vm.dict_set(globals, Value::Text(name.into()), Value::Object(object))
.unwrap();
vm.release(object).unwrap();
}
let source = r#"
class Base {
value: Number
function read(self: Base): Number { return self.value }
function via(self: Base): Number { return self.read() }
function withEvent(self: Base, event: Object): Object { return event }
}
class Child: Base {
label: String
function read(self: Child): Number { return 12 }
}
"#;
assert_eq!(
execute(&mut vm, globals, source, ParseMode::Module),
Value::Nil
);
let callback = execute(
&mut vm,
globals,
"Child(9, \"ok\").via",
ParseMode::Expression,
);
let Value::Object(callback) = callback else {
panic!("bound callback")
};
assert_eq!(
vm.object_store()
.positional_parameter_count(callback)
.unwrap(),
Some(0)
);
let with_event = execute(
&mut vm,
globals,
"Child(9, \"ok\").withEvent",
ParseMode::Expression,
);
let Value::Object(with_event) = with_event else {
panic!("bound callback")
};
assert_eq!(
vm.object_store()
.positional_parameter_count(with_event)
.unwrap(),
Some(1)
);
vm.release(with_event).unwrap();
vm.dict_clear(globals).unwrap();
vm.release(globals).unwrap();
vm.collect_cycles();
// No global name or external instance root remains. The bound callback
// alone retains its receiver and can still dispatch to Child.read.
assert_eq!(
vm.call(callback, &[]).unwrap(),
Value::Number(12_i64.into())
);
vm.release(callback).unwrap();
vm.collect_cycles();
assert_eq!(vm.object_count(), 0);
}
#[test]
fn duplicate_members_and_missing_receivers_fail_before_execution() {
for text in [
"class Bad { value: Number value: String }",
"class Bad { function read(): Number { return 1 } }",
] {
let source = EndorReader::from_text("<invalid-class>", text);
assert!(
compile_source(
&source,
ParseMode::Module,
&CompileOptions {
globals: vec!["Object".into()]
}
)
.is_err()
);
}
}