Skip to main content

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