feat: render top-level Endor scripts through embedded Aster
Verify Tessera GUI / verify (push) Failing after 6m52s

This commit is contained in:
2026-10-20 13:47:29 +08:00
parent 8cb2bf8607
commit 47ab2aa3a6
14 changed files with 695 additions and 89 deletions
+296 -44
View File
@@ -2,12 +2,14 @@
use anyhow::{Result, bail};
use endor_core::{ExecutionLimits, ObjectRef, Value, Vm, VmError};
use frontend::{
EndorReader, ParseMode, SourceUnit, Span,
EndorReader, SourceUnit, Span,
ast::{AstRoot, Decl, DeclKind, Expr, ExprKind, Spanned, Stmt, StmtKind, visitor::Visitor},
};
use std::collections::BTreeSet;
use crate::{
document::{CodeNode, RenderDocument},
endor_script::{self, SourcePlan},
layout, ui_bridge,
};
@@ -24,47 +26,64 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
bail!("source exceeds the 1 MiB limit");
}
let source = EndorReader::from_text(format!("{namespace} [submission {submission}]"), source);
let ast = frontend::parse_source_ast(&source, ParseMode::Module)?;
AstBudget::default().visit_ast_root(&ast)?;
let compiled = compiler::compile_ast(
&ast,
&source,
&compiler::CompileOptions {
globals: vec!["ui".into()],
},
)
.map_err(|error| source.annotate(error))?;
let root = architecture(&source, &ast, namespace);
let plan = endor_script::parse(&source)?;
let mut budget = AstBudget::default();
for ast in plan.roots() {
budget.visit_ast_root(ast)?;
}
let compiled = compile_plan(&source, &plan)?;
let root = architecture(&source, &plan, namespace, submission);
let mut candidate = Candidate::new()?;
let result: Result<RenderDocument> = (|| {
let globals = candidate.vm.new_dict()?;
candidate.globals = Some(globals);
candidate.roots.push(globals);
let ui = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
let bridge = ui_bridge::install(&mut candidate.vm, &mut candidate.roots)?;
candidate
.vm
.dict_set(globals, Value::Text("ui".into()), Value::Object(ui))?;
let code = compiled.load(&mut candidate.vm)?;
candidate.roots.push(code);
let initialized = candidate
.vm
.execute_with_limits(code, globals, LIMITS)
.map_err(|error| runtime_error(&candidate.vm, error))?;
candidate.vm.release_value(initialized)?;
let entry = candidate
.vm
.dict_get(globals, &Value::Text("main".into()))?
.ok_or_else(|| anyhow::anyhow!("source must declare function main(): View"))?;
let Value::Object(entry) = entry else {
bail!("main must be a callable function");
.dict_set(globals, Value::Text("ui".into()), Value::Object(bridge.ui))?;
let limits = match &plan {
SourcePlan::Module(_) => LIMITS,
SourcePlan::Script(_) => ExecutionLimits {
max_instructions: LIMITS.max_instructions / compiled.len().max(1),
..LIMITS
},
};
for template in &compiled {
let code = template.load(&mut candidate.vm)?;
candidate.roots.push(code);
let value = candidate
.vm
.execute_with_limits(code, globals, limits)
.map_err(|error| runtime_error(&candidate.vm, error))?;
candidate.vm.release_value(value)?;
}
let ui_root = match &plan {
SourcePlan::Script(_) => bridge
.rendered()?
.ok_or_else(|| anyhow::anyhow!("script must call ui.page().render(root)"))?,
SourcePlan::Module(_) => {
let entry = candidate
.vm
.dict_get(globals, &Value::Text("main".into()))?
.ok_or_else(|| {
anyhow::anyhow!("declare main or render a page from a top-level script")
})?;
let Value::Object(entry) = entry else {
bail!("main must be a callable function");
};
let value = candidate
.vm
.call_with_limits(entry, &[], LIMITS)
.map_err(|error| runtime_error(&candidate.vm, error))?;
let snapshot = bridge.rendered().and_then(|rendered| match rendered {
Some(root) => Ok(root),
None => ui_bridge::snapshot(&candidate.vm, &value),
});
candidate.vm.release_value(value)?;
snapshot?
}
};
let returned = candidate
.vm
.call_with_limits(entry, &[], LIMITS)
.map_err(|error| runtime_error(&candidate.vm, error))?;
let snapshot = ui_bridge::snapshot(&candidate.vm, &returned);
candidate.vm.release_value(returned)?;
let ui_root = snapshot?;
let document = RenderDocument {
source: source.text().to_owned(),
root: Some(root),
@@ -82,6 +101,41 @@ pub fn compile(source: &str, namespace: &str, submission: u64) -> Result<RenderD
}
}
fn compile_plan(source: &SourceUnit, plan: &SourcePlan) -> Result<Vec<compiler::CompiledCode>> {
let mut globals = BTreeSet::from(["ui".to_owned()]);
// Match Aster module behavior for function forward references. Bindings are
// added in source order; every executable statement still uses Aster's own
// single-input Interactive compiler and the candidate's shared globals.
for root in plan.roots() {
if let AstRoot::Interactive(input) = root {
for statement in &input.statements {
if let StmtKind::Declaration(decl) = &statement.kind {
let DeclKind::Function(function) = &decl.kind;
globals.insert(function.name.text.clone());
}
}
}
}
let mut compiled = Vec::with_capacity(plan.roots().len());
for root in plan.roots() {
let options = compiler::CompileOptions {
globals: globals.iter().cloned().collect(),
};
compiled.push(
compiler::compile_ast(root, source, &options)
.map_err(|error| source.annotate(error))?,
);
if let AstRoot::Interactive(input) = root {
for statement in &input.statements {
if let StmtKind::Binding(binding) = &statement.kind {
globals.insert(binding.name.text.clone());
}
}
}
}
Ok(compiled)
}
struct Candidate {
vm: Vm,
roots: Vec<ObjectRef>,
@@ -160,20 +214,43 @@ impl Visitor for AstBudget {
}
}
fn architecture(source: &SourceUnit, ast: &AstRoot, namespace: &str) -> CodeNode {
fn architecture(
source: &SourceUnit,
plan: &SourcePlan,
namespace: &str,
submission: u64,
) -> CodeNode {
let mut tree = Architecture {
line_starts: line_starts(source.text()),
next_id: 0,
identity: format!("{namespace}@{submission}"),
};
let AstRoot::Module(program) = ast else {
unreachable!("module parse mode");
let mut children = Vec::new();
for root in plan.roots() {
match root {
AstRoot::Module(program) => children.extend(
program
.declarations
.iter()
.map(|decl| tree.declaration(decl)),
),
AstRoot::Interactive(input) => {
children.extend(input.statements.iter().map(|stmt| tree.statement(stmt)))
}
AstRoot::Expression(expression) => children.push(tree.expression(expression)),
}
}
let roots = plan.roots();
let span = Span::new(
roots.first().map_or(0, |root| root.span().start),
roots.last().map_or(0, |root| root.span().end),
);
let kind = if matches!(plan, SourcePlan::Module(_)) {
"module"
} else {
"script"
};
let children = program
.declarations
.iter()
.map(|decl| tree.declaration(decl))
.collect();
tree.node(namespace.to_owned(), "module", ast.span(), children)
tree.node(namespace.to_owned(), kind, span, children)
}
fn line_starts(source: &str) -> Vec<usize> {
@@ -190,6 +267,7 @@ fn line_starts(source: &str) -> Vec<usize> {
struct Architecture {
line_starts: Vec<usize>,
next_id: usize,
identity: String,
}
impl Architecture {
@@ -198,7 +276,7 @@ impl Architecture {
self.next_id += 1;
let line = |offset| self.line_starts.partition_point(|start| *start <= offset);
CodeNode {
id: format!("ast-{id}"),
id: format!("{}:ast-{id}", self.identity),
name,
kind: kind.into(),
start_line: line(span.start),
@@ -280,6 +358,180 @@ mod tests {
use crate::document::{NamespaceState, RenderCommand};
const EXAMPLE: &str = include_str!("../examples/hello.endor");
const PAGE: &str = include_str!("../examples/page.endor");
#[test]
fn top_level_goal_script_renders_without_a_main_or_synthetic_wrapper() {
let document = compile(PAGE, "app.main", 9).unwrap();
assert_eq!(document.source, PAGE);
let tree = document.root.as_ref().unwrap();
assert_eq!(tree.kind, "script");
assert_eq!(tree.children.len(), 4);
assert_eq!(tree.children[0].name, "heading");
assert_eq!(tree.children[1].name, "rectangle");
assert_eq!(tree.children[2].name, "myui");
assert_eq!(tree.children[2].start_line, 3);
assert_eq!(tree.children[3].start_line, 4);
assert!(tree.id.contains("app.main@9"));
assert_eq!(document.frame.commands.len(), 2);
assert!(
matches!(&document.frame.commands[0], RenderCommand::Text { value, size: 2, x: 24.0, y: 24.0, .. } if value == "Hello Endor")
);
assert!(
matches!(&document.frame.commands[1], RenderCommand::RoundedRect { x: 24.0, y: 52.0, width: 240.0, height: 80.0, radius: 12.0, color } if color == "#DCE8FF")
);
assert_eq!(document.display_list(2.0).unwrap().commands().len(), 3);
let wrapped = compile(include_str!("../examples/main.endor"), "app.main", 10).unwrap();
assert_eq!(
serde_json::to_value(&document.frame).unwrap(),
serde_json::to_value(&wrapped.frame).unwrap()
);
}
#[test]
fn script_helpers_multiline_bindings_calls_and_member_continuations_use_aster() {
let source = r##"let color = "#242422" // comment with ( and )
function greeting(): Text {
return "Hello Endor"
}
function heading(value: Text): View {
return ui.text(value, 2, color)
}
let title =
heading(greeting())
let rectangle = ui.rect(
240, 80, 12,
"#DCE8FF"
)
let page = ui
.page()
page
.render(ui.column(24, 12, title, rectangle))
"##;
let document = compile(source, "app.main", 2).unwrap();
assert_eq!(document.frame.commands.len(), 2);
let tree = document.root.unwrap();
assert_eq!(tree.children[1].name, "greeting");
assert_eq!(tree.children[1].start_line, 2);
assert_eq!(tree.children[2].name, "heading");
assert_eq!(tree.children[2].start_line, 5);
assert_eq!(tree.children[3].start_line, 8);
assert_eq!(tree.children[3].end_line, 9);
assert_eq!(tree.children.last().unwrap().end_line, 17);
}
#[test]
fn script_diagnostics_refer_to_original_unicode_source_and_byte_ranges() {
for ending in ["\n", "\r\n", "\r"] {
let source = format!(
"let title = ui.text(\"中文\"){ending}// comment{ending}let broken = missing{ending}ui.page().render(title)"
);
let error = compile(&source, "app.main", 27).unwrap_err();
let diagnostic = error.downcast_ref::<frontend::SourceDiagnostic>().unwrap();
assert_eq!(diagnostic.location.line, 3);
assert_eq!(diagnostic.location.column, 14);
assert_eq!(diagnostic.diagnostic.span.slice(&source), Some("missing"));
assert!(diagnostic.origin.to_string().contains("submission 27"));
}
let error = compile("let page = ui.page()\npage.render(,)", "app.main", 1).unwrap_err();
let diagnostic = error.downcast_ref::<frontend::SourceDiagnostic>().unwrap();
assert_eq!(diagnostic.location.line, 2);
}
#[test]
fn pages_bind_render_methods_and_last_render_selects_the_snapshot() {
let source = r#"let first = ui.page()
let second = ui.page()
first.render(ui.text("first"))
second.render(ui.text("second"))
let paint = first.render
paint(ui.text("last"))"#;
let document = compile(source, "app.main", 1).unwrap();
assert_eq!(document.frame.commands.len(), 1);
assert!(
matches!(&document.frame.commands[0], RenderCommand::Text { value, .. } if value == "last")
);
}
#[test]
fn page_api_errors_and_late_failures_do_not_publish_partial_snapshots() {
let mut state = NamespaceState::default();
state.submission = 1;
state
.commit(1, compile(PAGE, "app.main", 1).unwrap())
.unwrap();
for source in [
"ui.page()",
"let title = ui.text(\"no render\")",
"let page = ui.page(1)\npage.render(ui.text(\"x\"))",
"let page = ui.page()\npage.render()",
"let page = ui.page()\npage.render(\"not a node\")",
"let page = ui.page()\npage.render(ui.text(\"partial\"))\nui.missing()",
] {
state.submission = state.next_submission().unwrap();
assert!(
compile(source, "app.main", state.submission).is_err(),
"{source}"
);
assert_eq!(state.document.source, PAGE);
assert_eq!(state.revision, 1);
}
}
#[test]
fn page_creation_has_a_separate_bounded_pool() {
let mut source = String::new();
for index in 0..=ui_bridge::MAX_PAGES {
source.push_str(&format!("let page{index} = ui.page()\n"));
}
source.push_str("page0.render(ui.text(\"x\"))");
let error = compile(&source, "app.main", 1).unwrap_err();
assert!(error.to_string().contains("64 page budget"), "{error:#}");
}
#[test]
fn script_execution_is_limited_even_without_creating_ui_nodes() {
let mut source = "function text0(): Text { return \"Hello Endor\" }\n".to_owned();
for index in 1..=16 {
source.push_str(&format!(
"function text{index}(): Text {{ let unused = text{}() return text{}() }}\n",
index - 1,
index - 1
));
}
source.push_str("let title = ui.text(text16())\nui.page().render(title)");
let error = compile(&source, "app.main", 1).unwrap_err();
assert!(
error
.to_string()
.contains("execution limit reached: instructions"),
"{error:#}"
);
}
#[test]
fn literal_string_return_from_aster_can_be_displayed_by_the_host() {
let source = "function main(): Text { return \"Hello Endor\" }\nlet title = ui.text(main())\nui.page().render(title)";
let document = compile(source, "app.main", 1).unwrap();
assert!(
matches!(&document.frame.commands[0], RenderCommand::Text { value, .. } if value == "Hello Endor")
);
}
#[test]
fn developer_selection_resets_to_the_new_source_snapshot() {
let first = compile(PAGE, "app.main", 1).unwrap();
let second = compile(PAGE, "app.main", 2).unwrap();
let mut tools = crate::developer_tools::DeveloperToolsState {
open: true,
selected_node_id: Some(first.root.as_ref().unwrap().children[0].id.clone()),
};
tools.document_updated(&second);
assert_eq!(
tools.selected_node_id.as_deref(),
Some(second.root.as_ref().unwrap().id.as_str())
);
}
#[test]
fn executes_aster_functions_and_renders_after_vm_cleanup() {