summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLaurenz <laurmaedje@gmail.com>2023-02-13 17:44:14 +0100
committerLaurenz <laurmaedje@gmail.com>2023-02-13 17:45:08 +0100
commit17e9805b34562781d514ba6b0df31155c8d39824 (patch)
treec5c4761f59d6ffa57755660f51e88621ddcff689 /src
parent5233b1c50a4a671fdc38cf0d40868f8c075d9ed7 (diff)
Let `eval` take code instead of markup
Diffstat (limited to 'src')
-rw-r--r--src/model/eval.rs38
-rw-r--r--src/syntax/node.rs2
2 files changed, 38 insertions, 2 deletions
diff --git a/src/model/eval.rs b/src/model/eval.rs
index 1fbf4125..6e118f8a 100644
--- a/src/model/eval.rs
+++ b/src/model/eval.rs
@@ -16,7 +16,9 @@ use crate::diag::{
bail, error, At, SourceError, SourceResult, StrResult, Trace, Tracepoint,
};
use crate::syntax::ast::AstNode;
-use crate::syntax::{ast, Source, SourceId, Span, Spanned, SyntaxKind, SyntaxNode};
+use crate::syntax::{
+ ast, parse_code, Source, SourceId, Span, Spanned, SyntaxKind, SyntaxNode,
+};
use crate::util::PathExt;
use crate::World;
@@ -63,6 +65,40 @@ pub fn eval(
Ok(Module::new(name).with_scope(vm.scopes.top).with_content(result?))
}
+/// Evaluate a string as code and return the resulting value.
+///
+/// Everything in the output is associated with the given `span`.
+#[comemo::memoize]
+pub fn eval_code_str(
+ world: Tracked<dyn World>,
+ text: &str,
+ span: Span,
+) -> SourceResult<Value> {
+ let mut root = parse_code(text);
+ root.synthesize(span);
+
+ let errors = root.errors();
+ if !errors.is_empty() {
+ return Err(Box::new(errors));
+ }
+
+ let id = SourceId::detached();
+ let library = world.library();
+ let scopes = Scopes::new(Some(library));
+ let route = Route::default();
+ let mut tracer = Tracer::default();
+ let mut vm = Vm::new(world, route.track(), tracer.track_mut(), id, scopes, 0);
+ let code = root.cast::<ast::Code>().unwrap();
+ let result = code.eval(&mut vm);
+
+ // Handle control flow.
+ if let Some(flow) = vm.flow {
+ bail!(flow.forbidden());
+ }
+
+ result
+}
+
/// A virtual machine.
///
/// Holds the state needed to [evaluate](eval) Typst sources. A new
diff --git a/src/syntax/node.rs b/src/syntax/node.rs
index 1fdb0a83..e153b0bf 100644
--- a/src/syntax/node.rs
+++ b/src/syntax/node.rs
@@ -175,7 +175,7 @@ impl SyntaxNode {
}
/// Set a synthetic span for the node and all its descendants.
- pub(super) fn synthesize(&mut self, span: Span) {
+ pub(crate) fn synthesize(&mut self, span: Span) {
match &mut self.0 {
Repr::Leaf(leaf) => leaf.span = span,
Repr::Inner(inner) => Arc::make_mut(inner).synthesize(span),