tinymist_dap/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
//! Fast debugger implementation for typst.

//       this._runtime = new MockRuntime(fileAccessor);

//       this._runtime.on("breakpointValidated", (bp: IRuntimeBreakpoint) => {
//         this.sendEvent(
//           new BreakpointEvent("changed", {
//             verified: bp.verified,
//             id: bp.id,
//           } as DebugProtocol.Breakpoint),
//         );
//       });
//       this._runtime.on("end", () => {
//         this.sendEvent(new TerminatedEvent());
//       });

pub use tinymist_debug::BreakpointKind;

use std::sync::{mpsc, Arc};

use comemo::Track;
use comemo::Tracked;
use parking_lot::Mutex;
use tinymist_debug::{set_debug_session, DebugSession, DebugSessionHandler};
use tinymist_std::typst_shim::eval::{Eval, Vm};
use tinymist_world::{CompilerFeat, CompilerWorld};
use typst::{
    diag::{SourceResult, Warned},
    engine::{Engine, Route, Sink, Traced},
    foundations::{Context, Scopes, Value},
    introspection::Introspector,
    layout::PagedDocument,
    syntax::{ast, parse_code, Span},
    World, __bail as bail,
};

type RequestId = i64;

/// A debug request.
pub enum DebugRequest {
    /// Evaluates an expression.
    Evaluate(RequestId, String),
    /// Continues the execution.
    Continue,
}

/// A handler for debug events.
pub trait DebugAdaptor: Send + Sync {
    /// Called before the compilation.
    fn before_compile(&self);
    /// Called after the compilation.
    fn after_compile(&self, result: Warned<SourceResult<PagedDocument>>);
    /// Terminates the debug session.
    fn terminate(&self);
    /// Responds to a debug request.
    fn stopped(&self, ctx: &BreakpointContext);
    /// Responds to a debug request.
    fn respond(&self, id: RequestId, result: SourceResult<Value>);
}

/// Starts a debug session.
pub fn start_session<F: CompilerFeat>(
    base: CompilerWorld<F>,
    adaptor: Arc<dyn DebugAdaptor>,
    rx: mpsc::Receiver<DebugRequest>,
) {
    let context = Arc::new(DebugContext {});

    std::thread::spawn(move || {
        let world = tinymist_debug::instr_breakpoints(&base);

        if !set_debug_session(Some(DebugSession::new(context))) {
            adaptor.terminate();
            return None;
        }

        let _lock = ResourceLock::new(adaptor.clone(), rx);

        adaptor.before_compile();
        step_global(BreakpointKind::BeforeCompile, &world);

        let result = typst::compile::<PagedDocument>(&world);

        adaptor.after_compile(result);
        step_global(BreakpointKind::AfterCompile, &world);

        *RESOURCES.lock() = None;
        set_debug_session(None);

        adaptor.terminate();
        Some(())
    });
}

static RESOURCES: Mutex<Option<Resource>> = Mutex::new(None);

struct Resource {
    adaptor: Arc<dyn DebugAdaptor>,
    rx: mpsc::Receiver<DebugRequest>,
}

struct ResourceLock;

impl ResourceLock {
    fn new(adaptor: Arc<dyn DebugAdaptor>, rx: mpsc::Receiver<DebugRequest>) -> Self {
        RESOURCES.lock().replace(Resource { adaptor, rx });

        Self
    }
}

impl Drop for ResourceLock {
    fn drop(&mut self) {
        *RESOURCES.lock() = None;
    }
}

fn step_global(kind: BreakpointKind, world: &dyn World) {
    let mut resource = RESOURCES.lock();

    let introspector = Introspector::default();
    let traced = Traced::default();
    let mut sink = Sink::default();
    let route = Route::default();

    let engine = Engine {
        routines: &typst::ROUTINES,
        world: world.track(),
        introspector: introspector.track(),
        traced: traced.track(),
        sink: sink.track_mut(),
        route,
    };

    let context = Context::default();

    let span = Span::detached();

    let context = BreakpointContext {
        engine: &engine,
        context: context.track(),
        scopes: Scopes::new(Some(world.library())),
        span,
        kind,
    };

    step(&context, resource.as_mut().unwrap());
}

/// A breakpoint context.
pub struct BreakpointContext<'a, 'b, 'c> {
    /// The breakpoint kind.
    pub kind: BreakpointKind,

    engine: &'a Engine<'c>,
    context: Tracked<'a, Context<'b>>,
    scopes: Scopes<'a>,
    span: Span,
}

impl BreakpointContext<'_, '_, '_> {
    fn evaluate(&self, expr: &str) -> SourceResult<Value> {
        let mut root = parse_code(expr);
        root.synthesize(self.span);

        // Check for well-formedness.
        let errors = root.errors();
        if !errors.is_empty() {
            return Err(errors.into_iter().map(Into::into).collect());
        }

        // Prepare VM.
        let mut sink = Sink::new();
        let engine = Engine {
            world: self.engine.world,
            introspector: self.engine.introspector,
            traced: self.engine.traced,
            routines: self.engine.routines,
            sink: sink.track_mut(),
            route: self.engine.route.clone(),
        };
        let mut vm = Vm::new(engine, self.context, self.scopes.clone(), root.span());

        // Evaluate the code.
        let output = root.cast::<ast::Code>().unwrap().eval(&mut vm)?;

        // Handle control flow.
        if let Some(flow) = vm.flow {
            bail!(flow.forbidden());
        }

        Ok(output)
    }
}

fn step(ctx: &BreakpointContext, resource: &mut Resource) {
    resource.adaptor.stopped(ctx);
    loop {
        match resource.rx.recv() {
            Ok(DebugRequest::Evaluate(id, expr)) => {
                let res = ctx.evaluate(&expr);
                eprintln!("evaluate: {expr} => {res:?}");
                resource.adaptor.respond(id, res);
            }
            Ok(DebugRequest::Continue) => {
                break;
            }
            Err(mpsc::RecvError) => {
                break;
            }
        }
    }
}

struct DebugContext {}

impl DebugSessionHandler for DebugContext {
    fn on_breakpoint(
        &self,
        engine: &Engine,
        context: Tracked<Context>,
        scopes: Scopes,
        span: Span,
        kind: BreakpointKind,
    ) {
        let mut resource = RESOURCES.lock();
        let context = BreakpointContext {
            engine,
            context,
            scopes,
            span,
            kind,
        };
        step(&context, resource.as_mut().unwrap());
    }
}