typst_shim/stable/
eval.rs

1//! Typst Evaluation
2
3use comemo::Track;
4use typst::World;
5use typst::diag::SourceResult;
6use typst::engine::{Engine, Route, Sink, Traced};
7use typst::foundations::{Context, Func, Module, Value};
8use typst::introspection::Introspector;
9use typst::syntax::Source;
10
11pub use typst_eval::*;
12
13/// Evaluates a source file and return the resulting module.
14pub fn eval_compat(world: &dyn World, source: &Source) -> SourceResult<Module> {
15    let route = Route::default();
16    let traced = Traced::default();
17    let mut sink = Sink::default();
18
19    typst_eval::eval(
20        &typst::ROUTINES,
21        world.track(),
22        traced.track(),
23        sink.track_mut(),
24        route.track(),
25        source,
26    )
27}
28
29/// The Typst Engine.
30pub struct TypstEngine<'a> {
31    /// The introspector to be queried for elements and their positions.
32    pub introspector: Introspector,
33    /// May hold a span that is currently under inspection.
34    pub traced: Traced,
35    /// The route the engine took during compilation. This is used to detect
36    /// cyclic imports and excessive nesting.
37    pub route: Route<'static>,
38    ///  A push-only sink for delayed errors, warnings, and traced values.
39    ///
40    /// All tracked methods of this type are of the form `(&mut self, ..) ->
41    /// ()`, so in principle they do not need validation (though that
42    /// optimization is not yet implemented in comemo).
43    pub sink: Sink,
44    /// The environment in which typesetting occurs.
45    pub world: &'a dyn World,
46}
47
48impl<'a> TypstEngine<'a> {
49    /// Creates a new Typst Engine.
50    pub fn new(world: &'a dyn World) -> Self {
51        Self {
52            introspector: Introspector::default(),
53            traced: Traced::default(),
54            route: Route::default(),
55            sink: Sink::default(),
56            world,
57        }
58    }
59
60    /// Creates the engine.
61    pub fn as_engine(&'a mut self) -> Engine<'a> {
62        Engine {
63            routines: &typst::ROUTINES,
64            world: self.world.track(),
65            introspector: self.introspector.track(),
66            traced: self.traced.track(),
67            sink: self.sink.track_mut(),
68            route: self.route.clone(),
69        }
70    }
71
72    /// Applies a function.
73    pub fn apply(&'a mut self, func: &Func, ctx: Context, args: Vec<Value>) -> SourceResult<Value> {
74        func.call(&mut self.as_engine(), ctx.track(), args)
75    }
76
77    /// Calls a function.
78    pub fn call(&'a mut self, func: &Func, ctx: Context) -> SourceResult<Value> {
79        self.apply(func, ctx, vec![])
80    }
81}