feat: connect source compilation and VM execution
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m56s

This commit is contained in:
2026-10-19 14:50:37 +08:00
parent f5268d2e09
commit aa3257bfe6
45 changed files with 1501 additions and 44 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "compiler"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
core.workspace = true
frontend.workspace = true
[lints]
workspace = true
+12
View File
@@ -0,0 +1,12 @@
# compiler
最小 Endor 编译器:frontend AST → 名称/作用域分析 → wordcode 模板 → VM 代码对象。依赖本地 frontend 和 core(Rust 库名 endor_core),不引入第三方依赖,不让 core 反向依赖 parser。运行时基础类和类型注解求值不是编译前提。
| 内容 | 职责 |
| --- | --- |
| [Cargo.toml](Cargo.toml) | compiler 包、本地 frontend/core 依赖与工作区 lint |
| [src](src/README.md) | 分析、字节码生成与显式代码对象装载 |
| [examples](examples/README.md) | 可供 cli run/eval 的 Endor 源码文件,也是远端集成测试输入 |
| [tests](tests/README.md) | 源码到 VM、错误路径、名称与对象生命周期检查 |
公开入口为 analyze、compile_ast、compile_source、CompileOptions 和 CompiledCode::load。完整规则与所有权见 [编译链路](../../docs/runtime/compiler.md);CLI 使用见 [运行指南](../../docs/operations/README.md)。修改语法仍进入 [frontend](../frontend/README.md),修改指令/验证进入 [objects](../objects/README.md),修改执行进入 [core](../core/README.md)。返回 [工作区](../README.md)。
+21
View File
@@ -0,0 +1,21 @@
# 可执行 Endor 示例
这些 UTF-8 文件由 compiler 和 CLI 集成测试直接使用;运行只在指定远端环境进行,本地不运行。
| 文件 | 输入模式与预期结果 |
| --- | --- |
| [hello.endor](hello.endor) | run;main 返回“你好,Endor 🌱” |
| [calls.endor](calls.endor) | run;前向函数引用、参数和 let,返回“函数调用已接通” |
| [shadowing.endor](shadowing.endor) | run;参数遮蔽全局函数名并传递函数值,返回“局部名称优先” |
| [number.endor](number.endor) | run;返回无损负十进制常量 -123456789012345678901234567890.00100 |
| [literal.endor](literal.endor) | eval;返回“表达式 → 字节码 → VM” |
```sh
cli run crates/compiler/examples/hello.endor
cli run crates/compiler/examples/calls.endor
cli run crates/compiler/examples/shadowing.endor
cli run crates/compiler/examples/number.endor
cli eval crates/compiler/examples/literal.endor
```
run 默认调用无参数 main,可用 --entry name 选择另一个无参数入口;eval 解析一个完整表达式,二者都支持 - 读取 stdin 到 EOF。类型名称暂只保留语法,Callable 不要求预先注册语言类。例子不依赖 print 或其他默认标准库。编译器尚无算术运行语义;前端 basic.endor 含算术,只是解析示例,不能混作可执行示例。规则见 [编译契约](../../../docs/runtime/compiler.md),返回 [compiler](../README.md)。
+13
View File
@@ -0,0 +1,13 @@
// The callee is declared after main. Parameters, locals and calls use wordcode.
function main(): String {
let message = echo("函数调用已接通")
return relay(message)
}
function relay(value: String): String {
return echo(value)
}
function echo(value: String): String {
return value
}
+4
View File
@@ -0,0 +1,4 @@
// cli run crates/compiler/examples/hello.endor → 你好,Endor 🌱
function main(): String {
return "你好,Endor 🌱"
}
+2
View File
@@ -0,0 +1,2 @@
// cli eval crates/compiler/examples/literal.endor
"表达式 → 字节码 → VM"
+5
View File
@@ -0,0 +1,5 @@
// Signed decimal constants retain all digits; no f64 conversion or arithmetic.
function main(): Number {
let value = -123456789012345678901234567890.00100
return value
}
+13
View File
@@ -0,0 +1,13 @@
// A parameter can shadow a module function, and functions are ordinary values.
function echo(value: String): String {
return value
}
function invoke(echo: Callable, value: String): String {
let chosen = echo
return chosen(value)
}
function main(): String {
return invoke(echo, "局部名称优先")
}
+9
View File
@@ -0,0 +1,9 @@
# Compiler 源码
| 文件 | 职责 |
| --- | --- |
| [lib.rs](lib.rs) | CompileOptions、公开分析/编译入口、AST 原文范围检查与带来源诊断 |
| [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)。
+287
View File
@@ -0,0 +1,287 @@
use std::collections::BTreeSet;
use endor_core::CodeLayout;
use frontend::ast::{AstRoot, Decl, DeclKind, Expr, ExprKind, Function, Spanned, StmtKind};
use frontend::{Diagnostic, DiagnosticKind, Span};
use crate::{CompileOptions, diagnostic};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeKind {
Module,
Expression,
Interactive,
Function,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameBinding {
Local(usize),
Global(usize),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NameUse {
pub name: String,
pub span: Span,
pub binding: NameBinding,
}
#[derive(Debug, Clone)]
pub struct Scope {
pub kind: ScopeKind,
pub name: String,
pub span: Span,
pub layout: CodeLayout,
pub references: Vec<NameUse>,
}
#[derive(Debug, Clone)]
pub struct SymbolTable {
pub root: Scope,
/// Top-level function scopes in declaration order. Nested declarations
/// are rejected until source closure semantics are implemented.
pub functions: Vec<Scope>,
}
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
}
/// Resolve a closed source unit plus explicitly declared host globals.
/// Function locals are collected before reading expressions; a later let
/// shadows the global for the entire function, but cannot be read early.
pub fn analyze(root: &AstRoot, options: &CompileOptions) -> Result<SymbolTable, Diagnostic> {
if let AstRoot::Interactive(input) = root
&& input.statements.len() != 1
{
return Err(error(
input.span,
"interactive input must contain exactly one statement",
));
}
let mut globals: BTreeSet<String> = options.globals.iter().cloned().collect();
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(),
AstRoot::Interactive(input) => input
.statements
.iter()
.filter_map(|statement| {
if let StmtKind::Declaration(declaration) = &statement.kind {
Some(definition(declaration))
} else {
None
}
})
.collect(),
AstRoot::Expression(_) => Vec::new(),
};
let (kind, name) = match root {
AstRoot::Module(_) => (ScopeKind::Module, "<module>"),
AstRoot::Expression(_) => (ScopeKind::Expression, "<expression>"),
AstRoot::Interactive(_) => (ScopeKind::Interactive, "<interactive>"),
};
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);
}
// Analyze all bodies after registering all functions, enabling forward
// references and recursion without instantiating function objects here.
let scopes = functions
.iter()
.map(|function| function_scope(function, &globals))
.collect::<Result<Vec<_>, _>>()?;
match root {
AstRoot::Module(_) => {}
AstRoot::Expression(expression) => root_scope.expression(expression, &globals)?,
AstRoot::Interactive(input) => {
for statement in &input.statements {
match &statement.kind {
StmtKind::Binding(binding) => {
declare(&mut declared, &binding.name.text, binding.name.span)?;
root_scope.expression(&binding.value, &globals)?;
globals.insert(binding.name.text.clone());
root_scope.intern(&binding.name.text);
}
StmtKind::Declaration(_) => {}
StmtKind::Expression(expression) => {
root_scope.expression(expression, &globals)?
}
StmtKind::Return(_) => {
return Err(error(statement.span, "return outside a function"));
}
}
}
}
}
Ok(SymbolTable {
root: root_scope.scope,
functions: scopes,
})
}
fn declare(names: &mut BTreeSet<String>, name: &str, span: Span) -> Result<(), Diagnostic> {
if name.is_empty() || !names.insert(name.to_owned()) {
return Err(error(
span,
format!("duplicate or empty declaration: {name}"),
));
}
Ok(())
}
fn function_scope(function: &Function, globals: &BTreeSet<String>) -> Result<Scope, Diagnostic> {
let mut builder = Builder::new(ScopeKind::Function, &function.name.text, function.span);
let mut locals = BTreeSet::new();
for parameter in &function.parameters {
declare(&mut locals, &parameter.name.text, parameter.name.span)?;
builder
.scope
.layout
.parameters
.push(parameter.name.text.clone());
builder
.scope
.layout
.locals
.push(parameter.name.text.clone());
builder.initialized.insert(parameter.name.text.clone());
}
for statement in &function.body.statements {
match &statement.kind {
StmtKind::Binding(binding) => {
declare(&mut locals, &binding.name.text, binding.name.span)?;
builder.scope.layout.locals.push(binding.name.text.clone());
}
StmtKind::Declaration(_) => {
return Err(error(
statement.span,
"nested function declarations are not compiled yet",
));
}
_ => {}
}
}
let mut returned = false;
for statement in &function.body.statements {
if returned {
return Err(error(
statement.span,
"statement after return is unreachable",
));
}
match &statement.kind {
StmtKind::Binding(binding) => {
builder.expression(&binding.value, globals)?;
builder.initialized.insert(binding.name.text.clone());
}
StmtKind::Return(statement) => {
if let Some(value) = &statement.value {
builder.expression(value, globals)?;
}
returned = true;
}
StmtKind::Expression(expression) => builder.expression(expression, globals)?,
StmtKind::Declaration(_) => unreachable!("nested declaration rejected above"),
}
}
Ok(builder.scope)
}
struct Builder {
scope: Scope,
initialized: BTreeSet<String>,
}
impl Builder {
fn new(kind: ScopeKind, name: &str, span: Span) -> Self {
Self {
scope: Scope {
kind,
name: name.into(),
span,
layout: CodeLayout::default(),
references: Vec::new(),
},
initialized: BTreeSet::new(),
}
}
fn intern(&mut self, name: &str) -> usize {
if let Some(index) = self
.scope
.layout
.names
.iter()
.position(|candidate| candidate == name)
{
index
} else {
self.scope.layout.names.push(name.to_owned());
self.scope.layout.names.len() - 1
}
}
fn expression(
&mut self,
expression: &Expr,
globals: &BTreeSet<String>,
) -> Result<(), Diagnostic> {
match &expression.kind {
ExprKind::Name(name) => {
let binding = if let Some(index) = self
.scope
.layout
.locals
.iter()
.position(|local| local == name)
{
if !self.initialized.contains(name) {
return Err(error(
expression.span,
format!("local variable read before initialization: {name}"),
));
}
NameBinding::Local(index)
} else if globals.contains(name) {
NameBinding::Global(self.intern(name))
} else {
return Err(error(expression.span, format!("undefined name: {name}")));
};
self.scope.references.push(NameUse {
name: name.clone(),
span: expression.span,
binding,
});
}
ExprKind::Unary { operand, .. } => self.expression(operand, globals)?,
ExprKind::Binary { left, right, .. } => {
self.expression(left, globals)?;
self.expression(right, globals)?;
}
ExprKind::Member { object, name } => {
self.expression(object, globals)?;
self.intern(&name.text);
}
ExprKind::Call { callee, arguments } => {
self.expression(callee, globals)?;
for argument in arguments {
self.expression(argument, globals)?;
}
}
ExprKind::Number(_) | ExprKind::String(_) | ExprKind::Symbol(_) => {}
}
Ok(())
}
}
+315
View File
@@ -0,0 +1,315 @@
use endor_core::{
CodeLayout, DecodedInstruction, EndorCode, EndorNumber, Instruction, ObjectRef, Opcode, Value,
Vm, VmError,
};
use frontend::ast::{AstRoot, Decl, DeclKind, Expr, ExprKind, Stmt, StmtKind, UnaryOp};
use frontend::{Diagnostic, DiagnosticKind, SourceUnit, Span};
use crate::{NameBinding, Scope, ScopeKind, SymbolTable, diagnostic};
/// Validated, heap-independent executable template. Nested code constants
/// remain templates until load(), so no ObjectRef is shared across VM heaps.
#[derive(Debug, Clone)]
pub struct CompiledCode {
code: EndorCode,
children: Vec<(usize, CompiledCode)>,
}
impl CompiledCode {
pub fn instructions(&self) -> &[DecodedInstruction] {
self.code.instructions()
}
pub fn layout(&self) -> &CodeLayout {
self.code.layout()
}
pub fn name(&self) -> &str {
self.code.name()
}
pub fn filename(&self) -> &str {
self.code.filename()
}
pub fn first_line(&self) -> usize {
self.code.first_line()
}
pub fn children(&self) -> impl Iterator<Item = &CompiledCode> {
self.children.iter().map(|(_, child)| child)
}
/// Return one owned code-object root; release it after execution. The
/// parent retains its nested code constants. Temporary child roots are
/// released on both success and failure, including partial recursive loads.
pub fn load(&self, vm: &mut Vm) -> Result<ObjectRef, VmError> {
let mut roots = Vec::new();
let result = (|| {
let mut constants = self.code.constants().to_vec();
for (index, child) in &self.children {
let reference = child.load(vm)?;
roots.push(reference);
constants[*index] = Value::Object(reference);
}
let code = EndorCode::with_layout(
self.code.bytecode().to_vec(),
constants,
self.code.layout().clone(),
)?
.with_location(
self.code.name(),
self.code.filename(),
self.code.first_line(),
);
vm.new_code(code)
})();
for reference in roots {
vm.release(reference)
.expect("loader owns each temporary code root");
}
result
}
}
fn error(span: Span, message: impl Into<String>) -> Diagnostic {
diagnostic(DiagnosticKind::Compilation, span, message)
}
pub(crate) fn generate(
root: &AstRoot,
source: &SourceUnit,
symbols: &SymbolTable,
) -> Result<CompiledCode, Diagnostic> {
let mut emitter = Emitter::new(&symbols.root, source);
match root {
AstRoot::Module(program) => {
for declaration in &program.declarations {
emitter.declaration(declaration, symbols)?;
}
emitter.constant(Value::Nil)?;
emitter.simple(Opcode::ReturnValue);
}
AstRoot::Expression(expression) => {
emitter.expression(expression)?;
emitter.simple(Opcode::ReturnValue);
}
AstRoot::Interactive(input) => {
for statement in &input.statements {
if let StmtKind::Expression(expression) = &statement.kind {
emitter.expression(expression)?;
} else {
emitter.statement(statement, symbols)?;
emitter.constant(Value::Nil)?;
}
}
emitter.simple(Opcode::ReturnValue);
}
}
emitter.finish()
}
struct Emitter<'a> {
scope: &'a Scope,
source: &'a SourceUnit,
instructions: Vec<Instruction>,
constants: Vec<Value>,
children: Vec<(usize, CompiledCode)>,
}
impl<'a> Emitter<'a> {
fn new(scope: &'a Scope, source: &'a SourceUnit) -> Self {
Self {
scope,
source,
instructions: Vec::new(),
constants: Vec::new(),
children: Vec::new(),
}
}
fn emit(&mut self, opcode: Opcode, argument: usize) -> Result<(), Diagnostic> {
let argument = u32::try_from(argument)
.map_err(|_| error(self.scope.span, "bytecode operand exceeds u32"))?;
self.instructions.push(Instruction::new(opcode, argument));
Ok(())
}
fn simple(&mut self, opcode: Opcode) {
self.instructions.push(Instruction::simple(opcode));
}
fn constant(&mut self, value: Value) -> Result<(), Diagnostic> {
let index = self.constants.len();
self.constants.push(value);
self.emit(Opcode::LoadConst, index)
}
fn name_index(&self, name: &str) -> usize {
self.scope
.layout
.names
.iter()
.position(|candidate| candidate == name)
.expect("analysis interns every emitted name")
}
fn declaration(&mut self, declaration: &Decl, symbols: &SymbolTable) -> Result<(), Diagnostic> {
let DeclKind::Function(function) = &declaration.kind;
let scope = symbols
.functions
.iter()
.find(|scope| scope.span == function.span && scope.name == function.name.text)
.expect("analysis creates each function scope");
let mut body = Emitter::new(scope, self.source);
for statement in &function.body.statements {
body.statement(statement, symbols)?;
}
if !matches!(
function
.body
.statements
.last()
.map(|statement| &statement.kind),
Some(StmtKind::Return(_))
) {
body.constant(Value::Nil)?;
body.simple(Opcode::ReturnValue);
}
let child = body.finish()?;
let index = self.constants.len();
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))
}
fn statement(&mut self, statement: &Stmt, symbols: &SymbolTable) -> Result<(), Diagnostic> {
match &statement.kind {
StmtKind::Binding(binding) => {
self.expression(&binding.value)?;
if self.scope.kind == ScopeKind::Function {
let index = self
.scope
.layout
.locals
.iter()
.position(|name| name == &binding.name.text)
.expect("analysis allocates each local");
self.emit(Opcode::StoreFast, index)?;
} else {
self.emit(Opcode::StoreGlobal, self.name_index(&binding.name.text))?;
}
}
StmtKind::Return(statement) => {
if let Some(value) = &statement.value {
self.expression(value)?;
} else {
self.constant(Value::Nil)?;
}
self.simple(Opcode::ReturnValue);
}
StmtKind::Expression(expression) => {
self.expression(expression)?;
self.simple(Opcode::PopTop);
}
StmtKind::Declaration(declaration) => self.declaration(declaration, symbols)?,
}
Ok(())
}
fn expression(&mut self, expression: &Expr) -> Result<(), Diagnostic> {
match &expression.kind {
ExprKind::String(value) => self.constant(Value::Text(value.clone()))?,
ExprKind::Number(spelling) => self.number(spelling, expression.span)?,
ExprKind::Name(name) => {
let reference = self
.scope
.references
.iter()
.find(|reference| reference.span == expression.span && &reference.name == name)
.expect("analysis resolves every name expression");
let (opcode, index) = match reference.binding {
NameBinding::Local(index) => (Opcode::LoadFast, index),
NameBinding::Global(index) => (Opcode::LoadGlobal, index),
};
self.emit(opcode, index)?;
}
ExprKind::Call { callee, arguments } => {
self.expression(callee)?;
self.simple(Opcode::PushNull);
for argument in arguments {
self.expression(argument)?;
}
self.emit(Opcode::Call, arguments.len())?;
}
ExprKind::Member { object, name } => {
self.expression(object)?;
self.emit(Opcode::LoadAttr, self.name_index(&name.text))?;
}
ExprKind::Unary { .. } => {
// Literal sign folding preserves arbitrarily large integers
// and decimal spelling; this is not general numeric arithmetic.
let Some(spelling) = signed_literal(expression, false) else {
return Err(error(
expression.span,
"numeric unary operations are not implemented; only signed number literals are supported",
));
};
self.number(&spelling, expression.span)?;
}
ExprKind::Binary { .. } => {
return Err(error(
expression.span,
"numeric arithmetic bytecode is not implemented yet",
));
}
ExprKind::Symbol(_) => {
return Err(error(
expression.span,
"symbol runtime values are not implemented yet",
));
}
}
Ok(())
}
fn number(&mut self, spelling: &str, span: Span) -> Result<(), Diagnostic> {
let value = if spelling.contains('.') {
EndorNumber::decimal(spelling)
} else {
EndorNumber::integer(spelling)
}
.map_err(|failure| error(span, failure.to_string()))?;
self.constant(Value::Number(value))
}
fn finish(self) -> Result<CompiledCode, Diagnostic> {
let line = self
.scope
.span
.location(self.source.text())
.map_or(1, |location| location.line);
let code = EndorCode::from_instructions(
&self.instructions,
self.constants,
self.scope.layout.clone(),
)
.map_err(|failure| error(self.scope.span, failure.to_string()))?
.with_location(&self.scope.name, self.source.origin().to_string(), line);
Ok(CompiledCode {
code,
children: self.children,
})
}
}
fn signed_literal(expression: &Expr, negative: bool) -> Option<String> {
match &expression.kind {
ExprKind::Number(spelling) => Some(if negative {
format!("-{spelling}")
} else {
spelling.clone()
}),
ExprKind::Unary {
operation: UnaryOp::Negate,
operand,
} => signed_literal(operand, !negative),
_ => None,
}
}
+56
View File
@@ -0,0 +1,56 @@
//! Minimal source-to-wordcode compiler. Analysis and emission do not allocate
//! VM objects; a compiled unit can be loaded into independent VMs explicitly.
mod analysis;
mod codegen;
pub use analysis::{NameBinding, NameUse, Scope, ScopeKind, SymbolTable, analyze};
pub use codegen::CompiledCode;
use frontend::ast::{AstDocument, AstRoot};
use frontend::{Diagnostic, DiagnosticKind, ParseMode, SourceDiagnostic, SourceUnit, Span};
/// Names supplied by the host's globals or builtins dictionary. These are
/// compile-time declarations only; loading code never injects their values.
#[derive(Debug, Clone, Default)]
pub struct CompileOptions {
pub globals: Vec<String>,
}
pub fn compile_source(
source: &SourceUnit,
mode: ParseMode,
options: &CompileOptions,
) -> Result<CompiledCode, SourceDiagnostic> {
let root = frontend::parse_source_ast(source, mode)?;
compile_ast(&root, source, options).map_err(|error| source.annotate(error))
}
/// Compile an AST against its original source snapshot. Span validation does
/// not prove the AST's semantic equivalence to the supplied text.
pub fn compile_ast(
root: &AstRoot,
source: &SourceUnit,
options: &CompileOptions,
) -> Result<CompiledCode, Diagnostic> {
AstDocument::new(root.clone())
.and_then(|document| document.validate_source(source.text()))
.map_err(|error| {
diagnostic(
DiagnosticKind::Compilation,
Span::default(),
error.to_string(),
)
})?;
let symbols = analyze(root, options)?;
codegen::generate(root, source, &symbols)
}
fn diagnostic(kind: DiagnosticKind, span: Span, message: impl Into<String>) -> Diagnostic {
Diagnostic {
kind,
span,
message: message.into(),
expected: Vec::new(),
}
}
+5
View File
@@ -0,0 +1,5 @@
# 编译链路检查
[pipeline.rs](pipeline.rs) 将真实 Endor 示例交给 reader/parser/名称分析/代码生成/VM,检查函数值、前向引用、局部遮蔽、精确数字常量、语义诊断、宿主全局与属性回调、对象结果保活、跨 VM 模板装载、反复调用、错误帧清理、递归限额、共享交互命名空间及超过 255 的操作数。
同时检查重复名称、局部提前读取、未声明名称、不支持的执行特性和不合法 AST 原文范围。CLI 的文件/stdin 与退出码检查见 [cli/tests](../../cli/tests/README.md)。源码说明验证意图;仅由 ces-control 的 cargo test --workspace --locked 执行,本地不运行,结果边界见 [验证](../../../docs/operations/validation.md)。返回 [compiler](../README.md)。
+370
View File
@@ -0,0 +1,370 @@
use compiler::{CompileOptions, CompiledCode, NameBinding, analyze, compile_ast, compile_source};
use endor_core::{
EndorCodeObject, EndorFunctionObject, EndorNumber, ExecutionLimits, NativeFunction, ObjectRef,
Value, Vm, VmError,
};
use frontend::{DiagnosticKind, EndorReader, ParseMode, SourceUnit, parse_ast};
fn compile(text: &str, mode: ParseMode) -> CompiledCode {
compile_source(
&EndorReader::from_text("<test>", text),
mode,
&CompileOptions::default(),
)
.unwrap()
}
fn module(vm: &mut Vm, compiled: &CompiledCode) -> (ObjectRef, ObjectRef) {
let code = compiled.load(vm).unwrap();
let globals = vm.new_dict().unwrap();
let value = vm.execute(code, globals).unwrap();
assert_eq!(value, Value::Nil);
vm.release_value(value).unwrap();
(code, globals)
}
fn function(vm: &Vm, globals: ObjectRef, name: &str) -> ObjectRef {
let Some(Value::Object(function)) = vm.dict_get(globals, &Value::Text(name.into())).unwrap()
else {
panic!("missing function {name}")
};
function
}
fn cleanup(vm: &mut Vm, code: ObjectRef, globals: ObjectRef) {
vm.release(code).unwrap();
vm.dict_clear(globals).unwrap();
vm.release(globals).unwrap();
vm.collect_cycles();
assert_eq!(vm.object_count(), 0);
}
#[test]
fn source_files_execute_through_module_and_function_code_objects() {
for (text, expected) in [
(
include_str!("../examples/hello.endor"),
Value::Text("你好,Endor 🌱".into()),
),
(
include_str!("../examples/calls.endor"),
Value::Text("函数调用已接通".into()),
),
(
include_str!("../examples/shadowing.endor"),
Value::Text("局部名称优先".into()),
),
(
include_str!("../examples/number.endor"),
Value::Number(EndorNumber::decimal("-123456789012345678901234567890.00100").unwrap()),
),
] {
let compiled = compile(text, ParseMode::Module);
let mut vm = Vm::new().unwrap();
let (code, globals) = module(&mut vm, &compiled);
let main = function(&vm, globals, "main");
let data = vm.payload::<EndorFunctionObject>(main, "function").unwrap();
assert_eq!(
vm.payload::<EndorCodeObject>(data.code(), "code")
.unwrap()
.code()
.name(),
"main"
);
let result = vm.call(main, &[]).unwrap();
assert_eq!(result, expected);
vm.release_value(result).unwrap();
cleanup(&mut vm, code, globals);
}
}
#[test]
fn expression_mode_preserves_exact_literals_and_signs() {
for (text, expected) in [
(
include_str!("../examples/literal.endor"),
Value::Text("表达式 → 字节码 → VM".into()),
),
(
"-99999999999999999999999999999999999999",
Value::Number(EndorNumber::integer("-99999999999999999999999999999999999999").unwrap()),
),
("--00042", Value::Number(42_i64.into())),
(
"-0.000",
Value::Number(EndorNumber::decimal("-0.000").unwrap()),
),
] {
let mut vm = Vm::new().unwrap();
let code = compile(text, ParseMode::Expression).load(&mut vm).unwrap();
let globals = vm.new_dict().unwrap();
let value = vm.execute(code, globals).unwrap();
assert_eq!(value, expected);
vm.release_value(value).unwrap();
cleanup(&mut vm, code, globals);
}
}
#[test]
fn scope_analysis_resolves_local_shadowing_and_forward_globals() {
let source = "function main(target: Callable): String { let copy = target return later(copy) } function later(value: String): String { return value }";
let root = parse_ast(source, ParseMode::Module).unwrap();
let symbols = analyze(&root, &CompileOptions::default()).unwrap();
assert_eq!(symbols.functions[0].layout.parameters, ["target"]);
assert_eq!(symbols.functions[0].layout.locals, ["target", "copy"]);
assert_eq!(
symbols.functions[0]
.references
.iter()
.map(|reference| reference.binding)
.collect::<Vec<_>>(),
[
NameBinding::Local(0),
NameBinding::Global(0),
NameBinding::Local(1)
]
);
assert!(
symbols
.functions
.iter()
.all(|scope| scope.layout.free_variables.is_empty())
);
}
#[test]
fn semantic_errors_prevent_loading_and_keep_unicode_locations() {
for (text, fragment) in [
(
"function f(): String { return missing }",
"undefined name: missing",
),
("function f(x: T, x: T): T { return x }", "declaration: x"),
(
"function f(x: T): T { let x = 1 return x }",
"declaration: x",
),
(
"function f(): T { let x = 1 let x = 2 return x }",
"declaration: x",
),
(
"function f(): T { return 1 } function f(): T { return 2 }",
"declaration: f",
),
(
"function f(): T { let x = x return x }",
"before initialization: x",
),
(
"function f(): T { let x = later let later = 1 return x }",
"before initialization: later",
),
(
"function later(): T { return 1 } function f(): T { let x = later let later = 1 return x }",
"before initialization: later",
),
] {
let unit = EndorReader::from_text("<invalid>", text);
let error =
compile_source(&unit, ParseMode::Module, &CompileOptions::default()).unwrap_err();
assert_eq!(error.diagnostic.kind, DiagnosticKind::Semantic);
assert!(error.to_string().contains(fragment), "{error}");
}
let unit = EndorReader::from_text("<日本語>", "function 表示(): T {\r\n return 未定義\r\n}");
let error = compile_source(&unit, ParseMode::Module, &CompileOptions::default()).unwrap_err();
assert_eq!((error.location.line, error.location.column), (2, 10));
assert!(error.to_string().starts_with("<日本語>:2:10:"));
}
fn identity(arguments: &[Value]) -> Result<Value, VmError> {
if arguments.len() != 1 {
return Err(VmError::InvalidArgument("identity needs one argument"));
}
Ok(arguments[0].clone())
}
#[test]
fn host_globals_member_calls_and_object_results_keep_owned_roots() {
let options = CompileOptions {
globals: vec!["service".into(), "value".into()],
};
let unit = EndorReader::from_text("<host>", "service.echo(value)");
let compiled = compile_source(&unit, ParseMode::Expression, &options).unwrap();
let mut vm = Vm::new().unwrap();
let native = vm.allocate(NativeFunction::new("echo", identity)).unwrap();
let service = vm.new_object().unwrap();
vm.set_attr(service, "echo", Value::Object(native)).unwrap();
vm.release(native).unwrap();
let object = vm.new_object().unwrap();
let globals = vm.new_dict().unwrap();
vm.dict_set(
globals,
Value::Text("service".into()),
Value::Object(service),
)
.unwrap();
vm.dict_set(globals, Value::Text("value".into()), Value::Object(object))
.unwrap();
vm.release(service).unwrap();
vm.release(object).unwrap();
let code = compiled.load(&mut vm).unwrap();
let result = vm.execute(code, globals).unwrap();
assert_eq!(result, Value::Object(object));
vm.dict_clear(globals).unwrap();
assert!(vm.object(object).is_ok());
vm.release_value(result).unwrap();
assert_eq!(vm.object(object).unwrap_err(), VmError::InvalidHandle);
cleanup(&mut vm, code, globals);
}
#[test]
fn code_templates_load_independently_and_functions_share_loaded_code() {
let compiled = compile(include_str!("../examples/calls.endor"), ParseMode::Module);
let mut left = Vm::new().unwrap();
let mut right = Vm::new().unwrap();
let (left_code, left_globals) = module(&mut left, &compiled);
let (right_code, right_globals) = module(&mut right, &compiled);
assert_eq!(left.object(right_code).unwrap_err(), VmError::ForeignHandle);
let before = left.object_count();
let main = function(&left, left_globals, "main");
for _ in 0..3 {
let result = left.call(main, &[]).unwrap();
left.release_value(result).unwrap();
}
assert_eq!(left.object_count(), before);
cleanup(&mut left, left_code, left_globals);
cleanup(&mut right, right_code, right_globals);
}
#[test]
fn argument_and_recursion_failures_unwind_vm_frames_and_keep_traceback() {
let source =
"\nfunction main(): T { return echo() }\nfunction echo(value: T): T { return value }";
let compiled = compile(source, ParseMode::Module);
let mut vm = Vm::new().unwrap();
let (code, globals) = module(&mut vm, &compiled);
let baseline = vm.object_count();
let main = function(&vm, globals, "main");
assert!(matches!(
vm.call(main, &[]),
Err(VmError::ArgumentCount { provided: 0, .. })
));
assert_eq!(vm.object_count(), baseline);
assert_eq!(vm.last_traceback().last().unwrap().first_line, 2);
cleanup(&mut vm, code, globals);
let mut vm = Vm::new().unwrap();
let (code, globals) = module(
&mut vm,
&compile("function main(): T { return main() }", ParseMode::Module),
);
let main = function(&vm, globals, "main");
assert_eq!(
vm.call_with_limits(
main,
&[],
ExecutionLimits {
max_frames: 4,
max_instructions: 100
}
),
Err(VmError::ExecutionLimit("frames"))
);
assert_eq!(vm.last_traceback().len(), 4);
cleanup(&mut vm, code, globals);
}
#[test]
fn declared_host_names_are_checked_again_at_runtime() {
let source = EndorReader::from_text("<host>", "missing");
let compiled = compile_source(
&source,
ParseMode::Expression,
&CompileOptions {
globals: vec!["missing".into()],
},
)
.unwrap();
let mut vm = Vm::new().unwrap();
let code = compiled.load(&mut vm).unwrap();
let globals = vm.new_dict().unwrap();
assert_eq!(
vm.execute(code, globals),
Err(VmError::NameNotFound("missing".into()))
);
cleanup(&mut vm, code, globals);
}
#[test]
fn interactive_submissions_can_share_a_host_owned_namespace() {
let mut vm = Vm::new().unwrap();
let globals = vm.new_dict().unwrap();
for (text, options, expected) in [
(
"let value = \"保留\"",
CompileOptions::default(),
Value::Nil,
),
(
"value",
CompileOptions {
globals: vec!["value".into()],
},
Value::Text("保留".into()),
),
] {
let source = EndorReader::from_text("<submission>", text);
let compiled = compile_source(&source, ParseMode::Interactive, &options).unwrap();
let code = compiled.load(&mut vm).unwrap();
let result = vm.execute(code, globals).unwrap();
assert_eq!(result, expected);
vm.release_value(result).unwrap();
vm.release(code).unwrap();
}
vm.dict_clear(globals).unwrap();
vm.release(globals).unwrap();
assert_eq!(vm.object_count(), 0);
}
#[test]
fn extended_operands_work_for_large_local_and_constant_tables() {
let mut source = String::from("function main(): Number { ");
for index in 0..270 {
source.push_str(&format!("let value{index} = {index} "));
}
source.push_str("return value269 }");
let mut vm = Vm::new().unwrap();
let (code, globals) = module(&mut vm, &compile(&source, ParseMode::Module));
let main = function(&vm, globals, "main");
let result = vm.call(main, &[]).unwrap();
assert_eq!(result, Value::Number(269_i64.into()));
vm.release_value(result).unwrap();
cleanup(&mut vm, code, globals);
}
#[test]
fn unsupported_execution_features_are_compile_errors_instead_of_fake_results() {
for (text, mode) in [
("1 + 2", ParseMode::Expression),
(".title", ParseMode::Expression),
(
"function f(value: Number): Number { return -value }",
ParseMode::Module,
),
] {
let source = EndorReader::from_text("<unsupported>", text);
let error = compile_source(&source, mode, &CompileOptions::default()).unwrap_err();
assert_eq!(error.diagnostic.kind, DiagnosticKind::Compilation);
}
}
#[test]
fn compiling_ast_rejects_invalid_source_ranges() {
let source: SourceUnit = EndorReader::from_text("<source>", "\"日\"");
let mut root = parse_ast(source.text(), ParseMode::Expression).unwrap();
if let frontend::ast::AstRoot::Expression(expression) = &mut root {
expression.span.end = 2; // Splits the three-byte character.
}
assert!(compile_ast(&root, &source, &CompileOptions::default()).is_err());
}