feat: establish Lyra CLI with pinned Aster engine and remote CI
Verify Lyra CLI / verify (push) Failing after 1s

This commit is contained in:
2026-10-20 01:10:02 +08:00
commit af5c5f7a25
27 changed files with 1164 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "cli"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[[bin]]
name = "lyra"
path = "src/main.rs"
[dependencies]
compiler.workspace = true
core.workspace = true
frontend.workspace = true
[lints]
workspace = true
+11
View File
@@ -0,0 +1,11 @@
# CLI 包
Cargo 包名 cli,二进制 lyra。提供 bootstrap、run、eval、parse 和 help;JSON 文件信息管理由 Hestia 负责。
| 入口 | 内容 |
| --- | --- |
| Cargo.toml | 库依赖来自根工作区的固定 Aster 子模块 |
| [src](src/README.md) | 命令分发与源码执行 |
| [tests](tests/README.md) | 进程输出、来源诊断与失败退出检查 |
只在 ces-control 验证,不在本地运行。返回 [crates](../README.md)。
+3
View File
@@ -0,0 +1,3 @@
# CLI 源码
main.rs 处理命令、对象引导和 parse 输出;execute.rs 处理 run/eval、入口查找、结果格式、traceback 和候选命名空间清理。二进制名 lyra。返回 [包入口](../README.md)。
+105
View File
@@ -0,0 +1,105 @@
use std::error::Error;
use compiler::{CompileOptions, compile_source};
use endor_core::{Value, Vm};
use frontend::{EndorReader, ParseMode, SourceUnit};
pub(super) fn run_command(arguments: &[&str]) -> Result<(), Box<dyn Error>> {
let mut entry = "main";
let mut path = None;
let mut arguments = arguments.iter().copied();
while let Some(argument) = arguments.next() {
match argument {
"--entry" => {
entry = arguments
.next()
.filter(|name| !name.is_empty() && !name.starts_with("--"))
.ok_or(super::USAGE)?;
}
value if !value.starts_with("--") && path.is_none() => path = Some(value),
_ => return Err(super::USAGE.into()),
}
}
let source = read(path.ok_or(super::USAGE)?)?;
let output = execute(&source, ParseMode::Module, Some(entry))?;
println!("{output}");
Ok(())
}
pub(super) fn eval_command(path: &str) -> Result<(), Box<dyn Error>> {
let source = read(path)?;
let output = execute(&source, ParseMode::Expression, None)?;
println!("{output}");
Ok(())
}
fn read(path: &str) -> Result<SourceUnit, Box<dyn Error>> {
Ok(if path == "-" {
EndorReader::from_stream("<stdin>", std::io::stdin().lock())?
} else {
EndorReader::from_file(path)?
})
}
fn execute(
source: &SourceUnit,
mode: ParseMode,
entry: Option<&str>,
) -> Result<String, Box<dyn Error>> {
let compiled = compile_source(source, mode, &CompileOptions::default())?;
let mut vm = Vm::new()?;
let code = compiled.load(&mut vm)?;
let globals = match vm.new_dict() {
Ok(globals) => globals,
Err(error) => {
vm.release(code)?;
return Err(error.into());
}
};
let result = (|| -> Result<String, Box<dyn Error>> {
let mut value = vm.execute(code, globals)?;
if let Some(entry) = entry {
vm.release_value(value)?;
let Some(Value::Object(function)) = vm.dict_get(globals, &Value::Text(entry.into()))?
else {
return Err(format!("entry function not found: {entry}").into());
};
value = vm.call(function, &[])?;
}
let output = format_value(&vm, &value);
vm.release_value(value)?;
output
})();
// Copy traceback metadata before cleanup. This is the entry location of
// each code object plus bytecode offset, not a per-instruction source map.
let result = result.map_err(|error| {
let mut message = format!("{}: {error}", source.origin());
for location in vm.last_traceback() {
message.push_str(&format!(
"\n at {} ({}:{}, code unit {})",
location.function,
location.filename,
location.first_line,
location.instruction_offset
));
}
Box::<dyn Error>::from(message)
});
vm.release(code)?;
// CLI owns this fresh namespace. Clearing it breaks function↔globals
// cycles on both success and failure; embedders choose their own lifetime.
vm.dict_clear(globals)?;
vm.release(globals)?;
vm.collect_cycles();
result
}
fn format_value(vm: &Vm, value: &Value) -> Result<String, Box<dyn Error>> {
Ok(match value {
Value::Nil => "nil".into(),
Value::Bool(value) => value.to_string(),
Value::Text(value) => value.clone(),
Value::Number(value) => value.to_string(),
Value::Object(reference) => vm.str(*reference)?,
})
}
+92
View File
@@ -0,0 +1,92 @@
use std::error::Error;
use std::process::ExitCode;
use endor_core::{Value, Vm};
use frontend::ast::AstDocument;
use frontend::{EndorReader, ParseMode, parse_source_ast};
mod execute;
const USAGE: &str = "Usage: lyra [bootstrap | run [--entry name] <file|-> | eval <file|-> | parse [--mode module|expression|interactive] [--json] <file|-> | help]";
fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("lyra: {error}");
ExitCode::FAILURE
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
match args
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.as_slice()
{
[] | ["bootstrap"] => {
let mut vm = Vm::new()?;
let first = vm.new_object()?;
let second = vm.new_object()?;
vm.set_attr(
first,
"message",
Value::Text("Hello from EndorObject".into()),
)?;
println!("runtime=EndorObject type_system=disabled");
println!(
"objects_distinct={} heap_objects={}",
first != second,
vm.object_count()
);
vm.release(first)?;
vm.release(second)?;
println!("released heap_objects={}", vm.object_count());
println!("bootstrap uses no database");
}
["help"] | ["--help"] | ["-h"] => println!("{USAGE}"),
["parse", arguments @ ..] => parse_command(arguments)?,
["run", arguments @ ..] => execute::run_command(arguments)?,
["eval", path] => execute::eval_command(path)?,
_ => return Err(USAGE.into()),
}
Ok(())
}
fn parse_command(arguments: &[&str]) -> Result<(), Box<dyn Error>> {
let mut mode = ParseMode::Module;
let mut json = false;
let mut path = None;
let mut arguments = arguments.iter().copied();
while let Some(argument) = arguments.next() {
match argument {
"--json" => json = true,
"--mode" => {
mode = match arguments.next() {
Some("module") => ParseMode::Module,
Some("expression") => ParseMode::Expression,
Some("interactive") => ParseMode::Interactive,
_ => return Err(USAGE.into()),
}
}
value if !value.starts_with("--") && path.is_none() => path = Some(value),
_ => return Err(USAGE.into()),
}
}
let path = path.ok_or(USAGE)?;
let source = if path == "-" {
EndorReader::from_stream("<stdin>", std::io::stdin().lock())?
} else {
EndorReader::from_file(path)?
};
let root = parse_source_ast(&source, mode)?;
if json {
println!("{}", AstDocument::new(root)?.to_json()?);
} else {
println!("{root:#?}");
}
Ok(())
}
+3
View File
@@ -0,0 +1,3 @@
# CLI 进程检查
execute.rs 检查固定 Aster 子模块中的五个真实 Endor 文件、stdin、入口选择、错误阶段和退出码;parse.rs 检查来源、UTF-8、AST/JSON 和非法输入。仅远端执行,不在本地运行。返回 [包入口](../README.md)。
+136
View File
@@ -0,0 +1,136 @@
use std::io::Write;
use std::process::{Command, Output, Stdio};
fn stdin_command(arguments: &[&str], source: &[u8]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lyra"))
.args(arguments)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
child.stdin.take().unwrap().write_all(source).unwrap();
child.wait_with_output().unwrap()
}
#[test]
fn run_executes_real_endor_files_and_prints_entry_results() {
for (file, expected) in [
("hello.endor", "你好,Endor 🌱\n"),
("calls.endor", "函数调用已接通\n"),
("shadowing.endor", "局部名称优先\n"),
("number.endor", "-123456789012345678901234567890.00100\n"),
] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../vendor/aster/crates/compiler/examples")
.join(file);
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.arg("run")
.arg(path)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(String::from_utf8(output.stdout).unwrap(), expected);
assert!(output.stderr.is_empty());
}
}
#[test]
fn eval_and_run_read_stdin_and_support_explicit_entry_names() {
let output = stdin_command(&["eval", "-"], "\"表达式🌱\"".as_bytes());
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(String::from_utf8(output.stdout).unwrap(), "表达式🌱\n");
let output = stdin_command(
&["run", "--entry", "greet", "-"],
b"function greet(): String { return \"ok\" }",
);
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(String::from_utf8(output.stdout).unwrap(), "ok\n");
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../vendor/aster/crates/compiler/examples/literal.endor");
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.arg("eval")
.arg(path)
.output()
.unwrap();
assert!(output.status.success());
assert_eq!(
String::from_utf8(output.stdout).unwrap(),
"表达式 → 字节码 → VM\n"
);
}
#[test]
fn execution_errors_fail_without_success_output_and_report_their_stage() {
for (arguments, source, expected) in [
(
vec!["run", "-"],
"function main(): T {\n return missing\n}",
"<stdin>:2:10: undefined name: missing",
),
(
vec!["run", "-"],
"function main(): T { return f() } function f(x: T): T { return x }",
"positional arguments",
),
(
vec!["run", "-"],
"function other(): T { return 1 }",
"entry function not found: main",
),
(
vec!["eval", "-"],
"1 + 2",
"arithmetic bytecode is not implemented",
),
(vec!["eval", "-"], "1()", "does not support call"),
(
vec!["run", "-"],
"function main(): T { return ) }",
"expected",
),
] {
let output = stdin_command(&arguments, source.as_bytes());
assert!(!output.status.success());
assert!(output.stdout.is_empty());
let error = String::from_utf8(output.stderr).unwrap();
assert!(error.contains(expected), "{error}");
if expected == "positional arguments" {
assert!(error.contains("at main (<stdin>:1, code unit"));
}
}
let output = stdin_command(&["eval", "-"], &[0xff]);
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)
.unwrap()
.contains("invalid UTF-8")
);
for arguments in [
vec!["run"],
vec!["run", "--entry"],
vec!["run", "--unknown", "-"],
vec!["eval"],
vec!["eval", "-", "extra"],
] {
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.args(arguments)
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
assert!(String::from_utf8(output.stderr).unwrap().contains("Usage:"));
}
}
+139
View File
@@ -0,0 +1,139 @@
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_FILE: AtomicUsize = AtomicUsize::new(0);
struct SourceFile(PathBuf);
impl SourceFile {
fn new(content: &[u8]) -> Self {
let path = std::env::temp_dir().join(format!(
"aster-parse-{}-{}.endor",
std::process::id(),
NEXT_FILE.fetch_add(1, Ordering::Relaxed)
));
std::fs::write(&path, content).unwrap();
Self(path)
}
}
impl Drop for SourceFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
#[test]
fn parse_command_prints_ast_without_executing_source() {
let source = SourceFile::new("function 表示(): String { return 未定義() }".as_bytes());
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.arg("parse")
.arg(&source.0)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let stdout = String::from_utf8(output.stdout).unwrap();
assert!(stdout.contains("表示"));
assert!(stdout.contains("未定義"));
assert!(stdout.contains("Call"));
}
#[test]
fn parse_command_reports_source_locations_and_rejects_invalid_utf8() {
let source = SourceFile::new(b"function f(): Number {\n return )\n}");
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.arg("parse")
.arg(&source.0)
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.contains(":2:10:"), "{stderr}");
assert!(stderr.contains("expected"));
let source = SourceFile::new(&[0xff]);
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.arg("parse")
.arg(&source.0)
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
}
fn parse_stdin(source: &[u8]) -> std::process::Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_lyra"))
.args(["parse", "-"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
stdin.write_all(source).unwrap();
drop(stdin);
child.wait_with_output().unwrap()
}
#[test]
fn parse_command_reads_stdin_to_eof_and_reports_its_origin() {
let output = parse_stdin("function 表示(): String { return \"日\" }".as_bytes());
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
assert!(String::from_utf8(output.stdout).unwrap().contains("表示"));
let output = parse_stdin(b"function f(): Number {\n return )\n}");
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)
.unwrap()
.contains("<stdin>:2:10:")
);
let output = parse_stdin(&[0xff]);
assert!(!output.status.success());
assert!(
String::from_utf8(output.stderr)
.unwrap()
.contains("<stdin>: invalid UTF-8 at byte 0")
);
}
#[test]
fn parse_command_exports_versioned_json_for_expression_and_interactive_inputs() {
for (mode, source) in [("expression", "f(\"日\")"), ("interactive", "let x = 1")] {
let source = SourceFile::new(source.as_bytes());
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.args(["parse", "--json", "--mode", mode])
.arg(&source.0)
.output()
.unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
let document =
frontend::ast::AstDocument::from_json(std::str::from_utf8(&output.stdout).unwrap())
.unwrap();
assert_eq!(document.schema, frontend::ast::AST_SCHEMA_ID);
match (mode, document.root) {
("expression", frontend::ast::AstRoot::Expression(_))
| ("interactive", frontend::ast::AstRoot::Interactive(_)) => {}
_ => panic!("incorrect parse mode"),
}
}
let output = Command::new(env!("CARGO_BIN_EXE_lyra"))
.args(["parse", "--mode", "unknown", "-"])
.output()
.unwrap();
assert!(!output.status.success());
assert!(output.stdout.is_empty());
}