nu-engine 0.112.2

Nushell's evaluation engine
Documentation
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use nu_protocol::{
    CompileError, IntoSpanned, RegId, Span, Spanned,
    ast::Pattern,
    ir::{DataSlice, Instruction, IrAstRef, IrBlock, Literal},
};

/// A label identifier. Only exists while building code. Replaced with the actual target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LabelId(pub usize);

/// Builds [`IrBlock`]s progressively by consuming instructions and handles register allocation.
#[derive(Debug)]
pub(crate) struct BlockBuilder {
    pub(crate) block_span: Option<Span>,
    pub(crate) instructions: Vec<Instruction>,
    pub(crate) spans: Vec<Span>,
    /// The actual instruction index that a label refers to. While building IR, branch targets are
    /// specified as indices into this array rather than the true instruction index. This makes it
    /// easier to make modifications to code, as just this array needs to be changed, and it's also
    /// less error prone as during `finish()` we check to make sure all of the used labels have had
    /// an index actually set.
    pub(crate) labels: Vec<Option<usize>>,
    pub(crate) data: Vec<u8>,
    pub(crate) ast: Vec<Option<IrAstRef>>,
    pub(crate) comments: Vec<String>,
    pub(crate) register_allocation_state: Vec<bool>,
    pub(crate) file_count: u32,
    pub(crate) context_stack: ContextStack,
}

impl BlockBuilder {
    /// Starts a new block, with the first register (`%0`) allocated as input.
    pub(crate) fn new(block_span: Option<Span>) -> Self {
        BlockBuilder {
            block_span,
            instructions: vec![],
            spans: vec![],
            labels: vec![],
            data: vec![],
            ast: vec![],
            comments: vec![],
            register_allocation_state: vec![true],
            file_count: 0,
            context_stack: ContextStack::new(),
        }
    }

    /// Get the next unused register for code generation.
    pub(crate) fn next_register(&mut self) -> Result<RegId, CompileError> {
        if let Some(index) = self
            .register_allocation_state
            .iter_mut()
            .position(|is_allocated| {
                if !*is_allocated {
                    *is_allocated = true;
                    true
                } else {
                    false
                }
            })
        {
            Ok(RegId::new(index as u32))
        } else if self.register_allocation_state.len() < (u32::MAX as usize - 2) {
            let reg_id = RegId::new(self.register_allocation_state.len() as u32);
            self.register_allocation_state.push(true);
            Ok(reg_id)
        } else {
            Err(CompileError::RegisterOverflow {
                block_span: self.block_span,
            })
        }
    }

    /// Check if a register is initialized with a value.
    pub(crate) fn is_allocated(&self, reg_id: RegId) -> bool {
        self.register_allocation_state
            .get(reg_id.get() as usize)
            .is_some_and(|state| *state)
    }

    /// Mark a register as initialized.
    pub(crate) fn mark_register(&mut self, reg_id: RegId) -> Result<(), CompileError> {
        if let Some(is_allocated) = self
            .register_allocation_state
            .get_mut(reg_id.get() as usize)
        {
            *is_allocated = true;
            Ok(())
        } else {
            Err(CompileError::RegisterOverflow {
                block_span: self.block_span,
            })
        }
    }

    /// Mark a register as empty, so that it can be used again by something else.
    #[track_caller]
    pub(crate) fn free_register(&mut self, reg_id: RegId) -> Result<(), CompileError> {
        let index = reg_id.get() as usize;

        if self
            .register_allocation_state
            .get(index)
            .is_some_and(|is_allocated| *is_allocated)
        {
            self.register_allocation_state[index] = false;
            Ok(())
        } else {
            log::warn!("register {reg_id} uninitialized, builder = {self:#?}");
            Err(CompileError::RegisterUninitialized {
                reg_id,
                caller: std::panic::Location::caller().to_string(),
            })
        }
    }

    /// Define a label, which can be used by branch instructions. The target can optionally be
    /// specified now.
    pub(crate) fn label(&mut self, target_index: Option<usize>) -> LabelId {
        let label_id = self.labels.len();
        self.labels.push(target_index);
        LabelId(label_id)
    }

    /// Change the target of a label.
    pub(crate) fn set_label(
        &mut self,
        label_id: LabelId,
        target_index: usize,
    ) -> Result<(), CompileError> {
        *self
            .labels
            .get_mut(label_id.0)
            .ok_or(CompileError::UndefinedLabel {
                label_id: label_id.0,
                span: None,
            })? = Some(target_index);
        Ok(())
    }

    /// Insert an instruction into the block, automatically marking any registers populated by
    /// the instruction, and freeing any registers consumed by the instruction.
    #[track_caller]
    pub(crate) fn push(&mut self, instruction: Spanned<Instruction>) -> Result<(), CompileError> {
        // Free read registers, and mark write registers.
        //
        // If a register is both read and written, it should be on both sides, so that we can verify
        // that the register was in the right state beforehand.
        let mut allocate = |read: &[RegId], write: &[RegId]| -> Result<(), CompileError> {
            for reg in read {
                self.free_register(*reg)?;
            }
            for reg in write {
                self.mark_register(*reg)?;
            }
            Ok(())
        };

        let allocate_result = match &instruction.item {
            Instruction::Unreachable => Ok(()),
            Instruction::LoadLiteral { dst, lit } => {
                allocate(&[], &[*dst]).and(
                    // Free any registers on the literal
                    match lit {
                        Literal::Range {
                            start,
                            step,
                            end,
                            inclusion: _,
                        } => allocate(&[*start, *step, *end], &[]),
                        Literal::Bool(_)
                        | Literal::Int(_)
                        | Literal::Float(_)
                        | Literal::Filesize(_)
                        | Literal::Duration(_)
                        | Literal::Binary(_)
                        | Literal::Block(_)
                        | Literal::Closure(_)
                        | Literal::RowCondition(_)
                        | Literal::List { capacity: _ }
                        | Literal::Record { capacity: _ }
                        | Literal::Filepath {
                            val: _,
                            no_expand: _,
                        }
                        | Literal::Directory {
                            val: _,
                            no_expand: _,
                        }
                        | Literal::GlobPattern {
                            val: _,
                            no_expand: _,
                        }
                        | Literal::String(_)
                        | Literal::RawString(_)
                        | Literal::CellPath(_)
                        | Literal::Date(_)
                        | Literal::Nothing
                        | Literal::Empty => Ok(()),
                    },
                )
            }
            Instruction::LoadValue { dst, val: _ } => allocate(&[], &[*dst]),
            Instruction::Move { dst, src } => allocate(&[*src], &[*dst]),
            Instruction::Clone { dst, src } => allocate(&[*src], &[*dst, *src]),
            Instruction::Collect { src_dst } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::TryCollect { src_dst } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::Span { src_dst } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::Drop { src } => allocate(&[*src], &[]),
            Instruction::Drain { src } => allocate(&[*src], &[]),
            Instruction::DrainIfEnd { src } => allocate(&[*src], &[]),
            Instruction::LoadVariable { dst, var_id: _ } => allocate(&[], &[*dst]),
            Instruction::StoreVariable { var_id: _, src } => allocate(&[*src], &[*src]),
            Instruction::DropVariable { var_id: _ } => Ok(()),
            Instruction::LoadEnv { dst, key: _ } => allocate(&[], &[*dst]),
            Instruction::LoadEnvOpt { dst, key: _ } => allocate(&[], &[*dst]),
            Instruction::StoreEnv { key: _, src } => allocate(&[*src], &[]),
            Instruction::PushPositional { src } => allocate(&[*src], &[]),
            Instruction::AppendRest { src } => allocate(&[*src], &[]),
            Instruction::PushFlag { name: _ } => Ok(()),
            Instruction::PushShortFlag { short: _ } => Ok(()),
            Instruction::PushNamed { name: _, src } => allocate(&[*src], &[]),
            Instruction::PushShortNamed { short: _, src } => allocate(&[*src], &[]),
            Instruction::PushParserInfo { name: _, info: _ } => Ok(()),
            Instruction::RedirectOut { mode: _ } => Ok(()),
            Instruction::RedirectErr { mode: _ } => Ok(()),
            Instruction::CheckErrRedirected { src } => allocate(&[*src], &[*src]),
            Instruction::OpenFile {
                file_num: _,
                path,
                append: _,
            } => allocate(&[*path], &[]),
            Instruction::WriteFile { file_num: _, src } => allocate(&[*src], &[]),
            Instruction::CloseFile { file_num: _ } => Ok(()),
            Instruction::Call {
                decl_id: _,
                src_dst,
            } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::StringAppend { src_dst, val } => allocate(&[*src_dst, *val], &[*src_dst]),
            Instruction::GlobFrom {
                src_dst,
                no_expand: _,
            } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::ListPush { src_dst, item } => allocate(&[*src_dst, *item], &[*src_dst]),
            Instruction::ListSpread { src_dst, items } => {
                allocate(&[*src_dst, *items], &[*src_dst])
            }
            Instruction::RecordInsert { src_dst, key, val } => {
                allocate(&[*src_dst, *key, *val], &[*src_dst])
            }
            Instruction::RecordSpread { src_dst, items } => {
                allocate(&[*src_dst, *items], &[*src_dst])
            }
            Instruction::Not { src_dst } => allocate(&[*src_dst], &[*src_dst]),
            Instruction::BinaryOp {
                lhs_dst,
                op: _,
                rhs,
            } => allocate(&[*lhs_dst, *rhs], &[*lhs_dst]),
            Instruction::FollowCellPath { src_dst, path } => {
                allocate(&[*src_dst, *path], &[*src_dst])
            }
            Instruction::CloneCellPath { dst, src, path } => {
                allocate(&[*src, *path], &[*src, *dst])
            }
            Instruction::UpsertCellPath {
                src_dst,
                path,
                new_value,
            } => allocate(&[*src_dst, *path, *new_value], &[*src_dst]),
            Instruction::Jump { index: _ } => Ok(()),
            Instruction::BranchIf { cond, index: _ } => allocate(&[*cond], &[]),
            Instruction::BranchIfEmpty { src, index: _ } => allocate(&[*src], &[*src]),
            Instruction::Match {
                pattern: _,
                src,
                index: _,
            } => allocate(&[*src], &[*src]),
            Instruction::CheckMatchGuard { src } => allocate(&[*src], &[*src]),
            Instruction::Iterate {
                dst,
                stream,
                end_index: _,
            } => allocate(&[*stream], &[*dst, *stream]),
            Instruction::OnError { index: _ } => Ok(()),
            Instruction::Finally { index: _ } => Ok(()),
            Instruction::OnErrorInto { index: _, dst } => allocate(&[], &[*dst]),
            Instruction::FinallyInto { index: _, dst } => allocate(&[], &[*dst]),
            Instruction::PopErrorHandler => Ok(()),
            Instruction::PopFinallyRun => Ok(()),
            Instruction::ReturnEarly { src } => allocate(&[*src], &[]),
            Instruction::Return { src } => allocate(&[*src], &[]),
        };

        // Add more context to the error
        match allocate_result {
            Ok(()) => (),
            Err(CompileError::RegisterUninitialized { reg_id, caller }) => {
                return Err(CompileError::RegisterUninitializedWhilePushingInstruction {
                    reg_id,
                    caller,
                    instruction: format!("{:?}", instruction.item),
                    span: instruction.span,
                });
            }
            Err(err) => return Err(err),
        }

        self.instructions.push(instruction.item);
        self.spans.push(instruction.span);
        self.ast.push(None);
        self.comments.push(String::new());
        Ok(())
    }

    /// Set the AST of the last instruction. Separate method because it's rarely used.
    pub(crate) fn set_last_ast(&mut self, ast_ref: Option<IrAstRef>) {
        *self.ast.last_mut().expect("no last instruction") = ast_ref;
    }

    /// Add a comment to the last instruction.
    pub(crate) fn add_comment(&mut self, comment: impl std::fmt::Display) {
        add_comment(
            self.comments.last_mut().expect("no last instruction"),
            comment,
        )
    }

    /// Load a register with a literal.
    pub(crate) fn load_literal(
        &mut self,
        reg_id: RegId,
        literal: Spanned<Literal>,
    ) -> Result<(), CompileError> {
        self.push(
            Instruction::LoadLiteral {
                dst: reg_id,
                lit: literal.item,
            }
            .into_spanned(literal.span),
        )?;
        Ok(())
    }

    /// Allocate a new register and load a literal into it.
    pub(crate) fn literal(&mut self, literal: Spanned<Literal>) -> Result<RegId, CompileError> {
        let reg_id = self.next_register()?;
        self.load_literal(reg_id, literal)?;
        Ok(reg_id)
    }

    /// Deallocate a register and set it to `Empty`, if it is allocated
    pub(crate) fn drop_reg(&mut self, reg_id: RegId) -> Result<(), CompileError> {
        if self.is_allocated(reg_id) {
            // try using the block Span if available, since that's slightly more helpful than Span::unknown
            let span = self.block_span.unwrap_or(Span::unknown());
            self.push(Instruction::Drop { src: reg_id }.into_spanned(span))?;
        }
        Ok(())
    }

    /// Set a register to `Empty`, but mark it as in-use, e.g. for input
    pub(crate) fn load_empty(&mut self, reg_id: RegId) -> Result<(), CompileError> {
        self.push(
            Instruction::LoadLiteral {
                dst: reg_id,
                lit: Literal::Empty,
            }
            .into_spanned(self.block_span.unwrap_or(Span::unknown())),
        )?;
        Ok(())
    }

    /// Drain the stream in a register (fully consuming it)
    pub(crate) fn drain(&mut self, src: RegId, span: Span) -> Result<(), CompileError> {
        self.push(Instruction::Drain { src }.into_spanned(span))
    }

    /// Add data to the `data` array and return a [`DataSlice`] referencing it.
    pub(crate) fn data(&mut self, data: impl AsRef<[u8]>) -> Result<DataSlice, CompileError> {
        let data = data.as_ref();
        let start = self.data.len();
        if data.is_empty() {
            Ok(DataSlice::empty())
        } else if start + data.len() < u32::MAX as usize {
            let slice = DataSlice {
                start: start as u32,
                len: data.len() as u32,
            };
            self.data.extend_from_slice(data);
            Ok(slice)
        } else {
            Err(CompileError::DataOverflow {
                block_span: self.block_span,
            })
        }
    }

    /// Clone a register with a `clone` instruction.
    pub(crate) fn clone_reg(&mut self, src: RegId, span: Span) -> Result<RegId, CompileError> {
        let dst = self.next_register()?;
        self.push(Instruction::Clone { dst, src }.into_spanned(span))?;
        Ok(dst)
    }

    /// Add a `branch-if` instruction
    pub(crate) fn branch_if(
        &mut self,
        cond: RegId,
        label_id: LabelId,
        span: Span,
    ) -> Result<(), CompileError> {
        self.push(
            Instruction::BranchIf {
                cond,
                index: label_id.0,
            }
            .into_spanned(span),
        )
    }

    /// Add a `branch-if-empty` instruction
    pub(crate) fn branch_if_empty(
        &mut self,
        src: RegId,
        label_id: LabelId,
        span: Span,
    ) -> Result<(), CompileError> {
        self.push(
            Instruction::BranchIfEmpty {
                src,
                index: label_id.0,
            }
            .into_spanned(span),
        )
    }

    /// Add a `jump` instruction
    pub(crate) fn jump(&mut self, label_id: LabelId, span: Span) -> Result<(), CompileError> {
        self.push(Instruction::Jump { index: label_id.0 }.into_spanned(span))
    }

    /// Add a `match` instruction
    pub(crate) fn r#match(
        &mut self,
        pattern: Pattern,
        src: RegId,
        label_id: LabelId,
        span: Span,
    ) -> Result<(), CompileError> {
        self.push(
            Instruction::Match {
                pattern: Box::new(pattern),
                src,
                index: label_id.0,
            }
            .into_spanned(span),
        )
    }

    /// The index that the next instruction [`.push()`](Self::push)ed will have.
    pub(crate) fn here(&self) -> usize {
        self.instructions.len()
    }

    /// Allocate a new file number, for redirection.
    pub(crate) fn next_file_num(&mut self) -> Result<u32, CompileError> {
        let next = self.file_count;
        self.file_count = self
            .file_count
            .checked_add(1)
            .ok_or(CompileError::FileOverflow {
                block_span: self.block_span,
            })?;
        Ok(next)
    }

    /// Push a new loop state onto the builder. Creates new labels that must be set.
    pub(crate) fn begin_loop(&mut self) -> Loop {
        let loop_ = Loop {
            break_label: self.label(None),
            continue_label: self.label(None),
        };
        self.context_stack.push_loop(loop_);
        loop_
    }

    /// True if we are currently in a loop.
    pub(crate) fn is_in_loop(&self) -> bool {
        self.context_stack.is_in_loop()
    }

    /// Add a loop breaking jump instruction.
    pub(crate) fn push_break(&mut self, span: Span) -> Result<(), CompileError> {
        let loop_ = self
            .context_stack
            .current_loop()
            .ok_or_else(|| CompileError::NotInALoop {
                msg: "`break` called from outside of a loop".into(),
                span: Some(span),
            })?;
        self.jump(loop_.break_label, span)
    }

    /// Add a loop continuing jump instruction.
    pub(crate) fn push_continue(&mut self, span: Span) -> Result<(), CompileError> {
        let loop_ = self
            .context_stack
            .current_loop()
            .ok_or_else(|| CompileError::NotInALoop {
                msg: "`continue` called from outside of a loop".into(),
                span: Some(span),
            })?;
        self.jump(loop_.continue_label, span)
    }

    /// Pop the loop state. Checks that the loop being ended is the same one that was expected.
    pub(crate) fn end_loop(&mut self, loop_: Loop) -> Result<(), CompileError> {
        let context_block = self
            .context_stack
            .pop()
            .ok_or_else(|| CompileError::NotInALoop {
                msg: "end_loop() called outside of a loop".into(),
                span: None,
            })?;

        match context_block {
            ContextBlock::Loop(ended_loop) if ended_loop == loop_ => Ok(()),
            _ => Err(CompileError::IncoherentLoopState {
                block_span: self.block_span,
            }),
        }
    }

    /// Mark an unreachable code path. Produces an error at runtime if executed.
    #[allow(dead_code)] // currently unused, but might be used in the future.
    pub(crate) fn unreachable(&mut self, span: Span) -> Result<(), CompileError> {
        self.push(Instruction::Unreachable.into_spanned(span))
    }

    /// Consume the builder and produce the final [`IrBlock`].
    pub(crate) fn finish(mut self) -> Result<IrBlock, CompileError> {
        // Add comments to label targets
        for (index, label_target) in self.labels.iter().enumerate() {
            if let Some(label_target) = label_target {
                add_comment(
                    &mut self.comments[*label_target],
                    format_args!("label({index})"),
                );
            }
        }

        // Populate the actual target indices of labels into the instructions
        for ((index, instruction), span) in
            self.instructions.iter_mut().enumerate().zip(&self.spans)
        {
            if let Some(label_id) = instruction.branch_target() {
                let target_index = self.labels.get(label_id).cloned().flatten().ok_or(
                    CompileError::UndefinedLabel {
                        label_id,
                        span: Some(*span),
                    },
                )?;
                // Add a comment to the target index that we come from here
                add_comment(
                    &mut self.comments[target_index],
                    format_args!("from({index}:)"),
                );
                instruction.set_branch_target(target_index).map_err(|_| {
                    CompileError::SetBranchTargetOfNonBranchInstruction {
                        instruction: format!("{instruction:?}"),
                        span: *span,
                    }
                })?;
            }
        }

        Ok(IrBlock {
            instructions: self.instructions,
            spans: self.spans,
            data: self.data.into(),
            ast: self.ast,
            comments: self.comments.into_iter().map(|s| s.into()).collect(),
            register_count: self
                .register_allocation_state
                .len()
                .try_into()
                .expect("register count overflowed in finish() despite previous checks"),
            file_count: self.file_count,
        })
    }

    pub(crate) fn begin_try(&mut self) {
        self.context_stack.push_try();
    }

    pub(crate) fn end_try(&mut self) -> Result<(), CompileError> {
        match self.context_stack.pop() {
            Some(ContextBlock::Try) => Ok(()),
            _ => Err(CompileError::NotInATry {
                msg: "end_try() called outside of a try block".into(),
                span: None,
            }),
        }
    }
}

/// Keeps track of the `break` and `continue` target labels for a loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Loop {
    pub(crate) break_label: LabelId,
    pub(crate) continue_label: LabelId,
}

/// Blocks that modify/define behavior for the instructions they contain.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContextBlock {
    Loop(Loop),
    Try,
}

#[derive(Debug, Clone)]
pub(crate) struct ContextStack(Vec<ContextBlock>);

impl ContextStack {
    pub const fn new() -> Self {
        Self(Vec::new())
    }

    pub fn push_loop(&mut self, r#loop: Loop) {
        self.0.push(ContextBlock::Loop(r#loop));
    }

    pub fn push_try(&mut self) {
        self.0.push(ContextBlock::Try);
    }

    pub fn pop(&mut self) -> Option<ContextBlock> {
        self.0.pop()
    }

    pub fn current_loop(&self) -> Option<&Loop> {
        self.0.iter().rev().find_map(|cb| match cb {
            ContextBlock::Loop(r#loop) => Some(r#loop),
            _ => None,
        })
    }

    pub fn try_block_depth_from_loop(&self) -> usize {
        self.0
            .iter()
            .rev()
            .take_while(|&cb| matches!(cb, ContextBlock::Try))
            .count()
    }

    pub fn is_in_loop(&self) -> bool {
        self.current_loop().is_some()
    }
}

/// Add a new comment to an existing one
fn add_comment(comment: &mut String, new_comment: impl std::fmt::Display) {
    use std::fmt::Write;
    write!(
        comment,
        "{}{}",
        if comment.is_empty() { "" } else { ", " },
        new_comment
    )
    .expect("formatting failed");
}