tinymist-debug 0.15.4-rc1

Tinymist debug support for Typst.
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Tinymist breakpoint support for Typst.

mod instr;

use std::sync::Arc;

use comemo::Tracked;
use parking_lot::RwLock;
use tinymist_analysis::location::{PositionEncoding, to_lsp_position};
use tinymist_std::hash::{FxHashMap, FxHashSet};
use tinymist_world::vfs::FileId;
use typst::World;
use typst::diag::FileResult;
use typst::engine::Engine;
use typst::foundations::{Binding, Context, Dict, Scopes, func};
use typst::syntax::{Source, Span};
use typst_shim::syntax::source_range;

use crate::instrument::Instrumenter;

#[derive(Default)]
pub struct BreakpointInstr {}

/// The kind of breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointKind {
    // Expr,
    // Line,
    /// A call breakpoint.
    CallStart,
    /// A call breakpoint.
    CallEnd,
    /// A function breakpoint.
    Function,
    /// A break breakpoint.
    Break,
    /// A continue breakpoint.
    Continue,
    /// A return breakpoint.
    Return,
    /// A block start breakpoint.
    BlockStart,
    /// A block end breakpoint.
    BlockEnd,
    /// A show start breakpoint.
    ShowStart,
    /// A show end breakpoint.
    ShowEnd,
    /// A doc start breakpoint.
    DocStart,
    /// A doc end breakpoint.
    DocEnd,
    /// A before compile breakpoint.
    BeforeCompile,
    /// A after compile breakpoint.
    AfterCompile,
}

impl BreakpointKind {
    /// Converts the breakpoint kind to a string.
    pub fn to_str(self) -> &'static str {
        match self {
            BreakpointKind::CallStart => "call_start",
            BreakpointKind::CallEnd => "call_end",
            BreakpointKind::Function => "function",
            BreakpointKind::Break => "break",
            BreakpointKind::Continue => "continue",
            BreakpointKind::Return => "return",
            BreakpointKind::BlockStart => "block_start",
            BreakpointKind::BlockEnd => "block_end",
            BreakpointKind::ShowStart => "show_start",
            BreakpointKind::ShowEnd => "show_end",
            BreakpointKind::DocStart => "doc_start",
            BreakpointKind::DocEnd => "doc_end",
            BreakpointKind::BeforeCompile => "before_compile",
            BreakpointKind::AfterCompile => "after_compile",
        }
    }
}

#[derive(Default)]
pub struct BreakpointInfo {
    pub meta: Vec<BreakpointItem>,
}

pub struct BreakpointItem {
    pub kind: BreakpointKind,
    pub function_name: Option<String>,
    pub origin_span: Span,
}

/// A source breakpoint requested by line and optional column.
///
/// Lines and columns are zero-based. Columns are measured as UTF-16 code units.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SourceBreakpoint {
    /// The requested source line.
    pub line: u32,
    /// The requested source column.
    pub column: Option<u32>,
}

/// The result of resolving a source breakpoint to a structural breakpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceBreakpointResolution {
    /// The original requested breakpoint.
    pub requested: SourceBreakpoint,
    /// The structural breakpoint this request maps to, if any.
    pub resolved: Option<ResolvedSourceBreakpoint>,
    /// Whether the source breakpoint is waiting for instrumentation metadata.
    pub pending: bool,
}

/// A structural breakpoint selected for a source breakpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedSourceBreakpoint {
    /// The structural breakpoint id within the instrumented source metadata.
    pub id: usize,
    /// The kind of structural breakpoint.
    pub kind: BreakpointKind,
    /// The resolved zero-based source line.
    pub line: u32,
    /// The resolved zero-based UTF-16 source column.
    pub column: u32,
}

static DEBUG_SESSION: RwLock<Option<DebugSession>> = RwLock::new(None);

/// The debug session handler.
pub trait DebugSessionHandler: Send + Sync {
    /// Called when a breakpoint is hit.
    fn on_breakpoint(
        &self,
        engine: &Engine,
        context: Tracked<Context>,
        scopes: Scopes,
        span: Span,
        kind: BreakpointKind,
        function_name: Option<String>,
    );
}

/// The debug session.
pub struct DebugSession {
    enabled_function_breakpoints: FxHashSet<(FileId, usize, BreakpointKind)>,
    enabled_source_breakpoints: FxHashSet<(FileId, usize, BreakpointKind)>,
    function_breakpoints: FxHashSet<String>,
    source_breakpoints: FxHashMap<FileId, Vec<SourceBreakpoint>>,
    /// The breakpoint meta.
    breakpoints: FxHashMap<FileId, Arc<BreakpointInfo>>,

    /// The handler.
    pub handler: Arc<dyn DebugSessionHandler>,
}

impl DebugSession {
    /// Creates a new debug session.
    pub fn new(handler: Arc<dyn DebugSessionHandler>) -> Self {
        Self {
            enabled_function_breakpoints: FxHashSet::default(),
            enabled_source_breakpoints: FxHashSet::default(),
            function_breakpoints: FxHashSet::default(),
            source_breakpoints: FxHashMap::default(),
            breakpoints: FxHashMap::default(),
            handler,
        }
    }

    /// Replaces the currently enabled function breakpoints by name.
    pub fn set_function_breakpoints(&mut self, names: impl IntoIterator<Item = String>) {
        self.function_breakpoints = names.into_iter().collect();
        self.enabled_function_breakpoints.clear();

        for (fid, info) in self.breakpoints.clone() {
            self.enable_function_breakpoints_for(fid, &info);
        }
    }

    /// Replaces source breakpoints for a file id.
    pub fn set_source_breakpoints(
        &mut self,
        fid: FileId,
        breakpoints: impl IntoIterator<Item = SourceBreakpoint>,
    ) {
        let breakpoints = breakpoints.into_iter().collect::<Vec<_>>();

        if breakpoints.is_empty() {
            self.source_breakpoints.remove(&fid);
        } else {
            self.source_breakpoints.insert(fid, breakpoints);
        }

        self.enabled_source_breakpoints
            .retain(|(enabled_fid, _, _)| *enabled_fid != fid);
    }

    /// Replaces source breakpoints for a source and resolves them if metadata is available.
    pub fn set_source_breakpoints_for(
        &mut self,
        source: &Source,
        breakpoints: impl IntoIterator<Item = SourceBreakpoint>,
    ) -> Vec<SourceBreakpointResolution> {
        let fid = source.id();
        self.set_source_breakpoints(fid, breakpoints);

        let Some(info) = self.breakpoints.get(&fid).cloned() else {
            return self.pending_source_breakpoints(fid);
        };

        self.enable_source_breakpoints_for(source, &info)
    }

    fn enable_breakpoints_for(
        &mut self,
        source: &Source,
        info: &BreakpointInfo,
    ) -> Vec<SourceBreakpointResolution> {
        let fid = source.id();
        self.enable_function_breakpoints_for(fid, info);
        self.enable_source_breakpoints_for(source, info)
    }

    fn enable_function_breakpoints_for(&mut self, fid: FileId, info: &BreakpointInfo) {
        for (id, item) in info.meta.iter().enumerate() {
            if !matches!(item.kind, BreakpointKind::Function) {
                continue;
            }

            if item
                .function_name
                .as_ref()
                .is_some_and(|name| self.function_breakpoints.contains(name))
            {
                self.enabled_function_breakpoints
                    .insert((fid, id, BreakpointKind::Function));
            }
        }
    }

    fn enable_source_breakpoints_for(
        &mut self,
        source: &Source,
        info: &BreakpointInfo,
    ) -> Vec<SourceBreakpointResolution> {
        let fid = source.id();
        self.enabled_source_breakpoints
            .retain(|(enabled_fid, _, _)| *enabled_fid != fid);

        let Some(breakpoints) = self.source_breakpoints.get(&fid).cloned() else {
            return vec![];
        };

        let candidates = SourceBreakpointCandidate::collect(source, info);

        breakpoints
            .into_iter()
            .map(|requested| {
                let resolved =
                    best_source_breakpoint_candidate(&requested, &candidates).map(|candidate| {
                        self.enabled_source_breakpoints
                            .insert((fid, candidate.id, candidate.kind));

                        ResolvedSourceBreakpoint {
                            id: candidate.id,
                            kind: candidate.kind,
                            line: candidate.line,
                            column: candidate.column,
                        }
                    });

                SourceBreakpointResolution {
                    requested,
                    resolved,
                    pending: false,
                }
            })
            .collect()
    }

    fn pending_source_breakpoints(&self, fid: FileId) -> Vec<SourceBreakpointResolution> {
        self.source_breakpoints
            .get(&fid)
            .into_iter()
            .flatten()
            .cloned()
            .map(|requested| SourceBreakpointResolution {
                requested,
                resolved: None,
                pending: true,
            })
            .collect()
    }

    fn breakpoint_enabled(&self, bp: &(FileId, usize, BreakpointKind)) -> bool {
        self.enabled_function_breakpoints.contains(bp)
            || self.enabled_source_breakpoints.contains(bp)
    }
}

#[derive(Debug, Clone, Copy)]
struct SourceBreakpointCandidate {
    id: usize,
    kind: BreakpointKind,
    line: u32,
    column: u32,
}

impl SourceBreakpointCandidate {
    fn collect(source: &Source, info: &BreakpointInfo) -> Vec<Self> {
        info.meta
            .iter()
            .enumerate()
            .filter_map(|(id, item)| {
                if !is_source_breakpoint_target(item.kind) {
                    return None;
                }

                let range = source_range(source, item.origin_span)?;
                let position = to_lsp_position(range.start, PositionEncoding::Utf16, source);

                Some(Self {
                    id,
                    kind: item.kind,
                    line: position.line,
                    column: position.character,
                })
            })
            .collect()
    }
}

fn best_source_breakpoint_candidate(
    breakpoint: &SourceBreakpoint,
    candidates: &[SourceBreakpointCandidate],
) -> Option<SourceBreakpointCandidate> {
    candidates
        .iter()
        .min_by_key(|candidate| {
            let line_bucket = if matches!(candidate.kind, BreakpointKind::BlockEnd) {
                3
            } else if candidate.line == breakpoint.line {
                0
            } else if candidate.line > breakpoint.line {
                1
            } else {
                2
            };
            let column = breakpoint.column.unwrap_or(0);

            (
                line_bucket,
                candidate.line.abs_diff(breakpoint.line),
                source_breakpoint_kind_priority(candidate.kind),
                candidate.column.abs_diff(column),
                candidate.id,
            )
        })
        .copied()
}

fn is_source_breakpoint_target(kind: BreakpointKind) -> bool {
    matches!(
        kind,
        BreakpointKind::Function
            | BreakpointKind::BlockStart
            | BreakpointKind::ShowStart
            | BreakpointKind::Return
            | BreakpointKind::BlockEnd
    )
}

fn source_breakpoint_kind_priority(kind: BreakpointKind) -> u8 {
    match kind {
        BreakpointKind::Function => 0,
        BreakpointKind::BlockStart => 1,
        BreakpointKind::ShowStart => 2,
        BreakpointKind::Return => 3,
        BreakpointKind::BlockEnd => 4,
        _ => 5,
    }
}

/// Runs function with the debug session.
pub fn with_debug_session<F, R>(f: F) -> Option<R>
where
    F: FnOnce(&DebugSession) -> R,
{
    Some(f(DEBUG_SESSION.read().as_ref()?))
}

/// Sets the debug session.
pub fn set_debug_session(session: Option<DebugSession>) -> bool {
    let mut lock = DEBUG_SESSION.write();

    if session.is_some() && lock.is_some() {
        return false;
    }

    let _ = std::mem::replace(&mut *lock, session);
    true
}

/// Updates function breakpoints for the active debug session, if any.
pub fn set_debug_function_breakpoints(names: impl IntoIterator<Item = String>) -> bool {
    let mut session = DEBUG_SESSION.write();
    let Some(session) = session.as_mut() else {
        return false;
    };

    session.set_function_breakpoints(names);
    true
}

/// Updates source breakpoints for an active debug session, if any.
pub fn set_debug_source_breakpoints(
    source: Source,
    breakpoints: impl IntoIterator<Item = SourceBreakpoint>,
) -> Option<Vec<SourceBreakpointResolution>> {
    let mut session = DEBUG_SESSION.write();
    let session = session.as_mut()?;

    Some(session.set_source_breakpoints_for(&source, breakpoints))
}

/// Software breakpoints
fn check_soft_breakpoint(span: Span, id: usize, kind: BreakpointKind) -> Option<bool> {
    let fid = span.id()?;

    let session = DEBUG_SESSION.read();
    let session = session.as_ref()?;

    let bp_feature = (fid, id, kind);
    Some(session.breakpoint_enabled(&bp_feature))
}

/// Software breakpoints
fn soft_breakpoint_handle(
    engine: &Engine,
    context: Tracked<Context>,
    span: Span,
    id: usize,
    kind: BreakpointKind,
    scope: Option<Dict>,
) -> Option<()> {
    let fid = span.id()?;

    let (handler, origin_span, function_name) = {
        let session = DEBUG_SESSION.read();
        let session = session.as_ref()?;

        let bp_feature = (fid, id, kind);
        if !session.breakpoint_enabled(&bp_feature) {
            return None;
        }

        let item = session.breakpoints.get(&fid)?.meta.get(id)?;
        (
            session.handler.clone(),
            item.origin_span,
            item.function_name.clone(),
        )
    };

    let mut scopes = Scopes::new(Some(engine.world.library()));
    if let Some(scope) = scope {
        for (key, value) in scope.into_iter() {
            scopes.top.bind(key.into(), Binding::detached(value));
        }
    }

    handler.on_breakpoint(engine, context, scopes, origin_span, kind, function_name);
    Some(())
}

pub mod breakpoints {

    use super::*;

    macro_rules! bp_handler {
        ($name:ident, $name2:expr, $name3:ident, $name4:expr, $title:expr, $kind:ident) => {
            #[func(name = $name2, title = $title)]
            pub fn $name(span: Span, id: usize) -> bool {
                check_soft_breakpoint(span, id, BreakpointKind::$kind).unwrap_or_default()
            }
            #[func(name = $name4, title = $title)]
            pub fn $name3(
                engine: &Engine,
                context: Tracked<Context>,
                span: Span,
                id: usize,
                scope: Option<Dict>,
            ) {
                soft_breakpoint_handle(engine, context, span, id, BreakpointKind::$kind, scope);
            }
        };
    }

    bp_handler!(
        __breakpoint_call_start,
        "__breakpoint_call_start",
        __breakpoint_call_start_handle,
        "__breakpoint_call_start_handle",
        "A Software Breakpoint at the start of a call.",
        CallStart
    );
    bp_handler!(
        __breakpoint_call_end,
        "__breakpoint_call_end",
        __breakpoint_call_end_handle,
        "__breakpoint_call_end_handle",
        "A Software Breakpoint at the end of a call.",
        CallEnd
    );
    bp_handler!(
        __breakpoint_function,
        "__breakpoint_function",
        __breakpoint_function_handle,
        "__breakpoint_function_handle",
        "A Software Breakpoint at the start of a function.",
        Function
    );
    bp_handler!(
        __breakpoint_break,
        "__breakpoint_break",
        __breakpoint_break_handle,
        "__breakpoint_break_handle",
        "A Software Breakpoint at a break.",
        Break
    );
    bp_handler!(
        __breakpoint_continue,
        "__breakpoint_continue",
        __breakpoint_continue_handle,
        "__breakpoint_continue_handle",
        "A Software Breakpoint at a continue.",
        Continue
    );
    bp_handler!(
        __breakpoint_return,
        "__breakpoint_return",
        __breakpoint_return_handle,
        "__breakpoint_return_handle",
        "A Software Breakpoint at a return.",
        Return
    );
    bp_handler!(
        __breakpoint_block_start,
        "__breakpoint_block_start",
        __breakpoint_block_start_handle,
        "__breakpoint_block_start_handle",
        "A Software Breakpoint at the start of a block.",
        BlockStart
    );
    bp_handler!(
        __breakpoint_block_end,
        "__breakpoint_block_end",
        __breakpoint_block_end_handle,
        "__breakpoint_block_end_handle",
        "A Software Breakpoint at the end of a block.",
        BlockEnd
    );
    bp_handler!(
        __breakpoint_show_start,
        "__breakpoint_show_start",
        __breakpoint_show_start_handle,
        "__breakpoint_show_start_handle",
        "A Software Breakpoint at the start of a show.",
        ShowStart
    );
    bp_handler!(
        __breakpoint_show_end,
        "__breakpoint_show_end",
        __breakpoint_show_end_handle,
        "__breakpoint_show_end_handle",
        "A Software Breakpoint at the end of a show.",
        ShowEnd
    );
    bp_handler!(
        __breakpoint_doc_start,
        "__breakpoint_doc_start",
        __breakpoint_doc_start_handle,
        "__breakpoint_doc_start_handle",
        "A Software Breakpoint at the start of a doc.",
        DocStart
    );
    bp_handler!(
        __breakpoint_doc_end,
        "__breakpoint_doc_end",
        __breakpoint_doc_end_handle,
        "__breakpoint_doc_end_handle",
        "A Software Breakpoint at the end of a doc.",
        DocEnd
    );
    bp_handler!(
        __breakpoint_before_compile,
        "__breakpoint_before_compile",
        __breakpoint_before_compile_handle,
        "__breakpoint_before_compile_handle",
        "A Software Breakpoint before compilation.",
        BeforeCompile
    );
    bp_handler!(
        __breakpoint_after_compile,
        "__breakpoint_after_compile",
        __breakpoint_after_compile_handle,
        "__breakpoint_after_compile_handle",
        "A Software Breakpoint after compilation.",
        AfterCompile
    );
}