yara-x-parser 1.11.0

A parsing library for YARA rules.
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! A module for traversing an expression's AST using a depth-first search
//! (DFS) algorithm.
//!
//! This module provides [`DFSIter`], an iterator that walks an expression's
//! Abstract Syntax Tree (AST) and emits [`DFSEvent`]s for each node in the
//! tree. There are two types of events: `Enter` and `Leave`. An `Enter` event
//! is emitted when a node is visited for the first time, before visiting its
//! children. A `Leave` event is emitted after all the node's children have
//! been visited.
//!
//! For each visited node, the iterator also provides a [`DFSContext`] that
//! describes the relationship between the visited node and its parent.
//!
//! # Example
//!
//! The following example shows how to use [`DFSIter`] to collect all the
//! pattern identifiers used in a YARA rule's condition.
//!
//! ```rust
//! use yara_x_parser::Parser;
//! use yara_x_parser::ast::*;
//! use yara_x_parser::ast::dfs::{DFSIter, DFSEvent};
//!
//! // Parse a YARA rule from a string.
//! let mut rules = r#"
//! rule test {
//!   strings:
//!     $a = "some string"
//!     $b = "another string"
//!   condition:
//!     ($a at 100) and $b
//! }
//! "#;
//!
//! // The AST object is the root of the AST.
//! let ast = AST::from(rules);
//!
//! // Get the condition of the first rule.
//! let condition = &ast.rules().next().unwrap().condition;
//!
//! // Create a new iterator that will traverse the condition's AST.
//! let mut iter = DFSIter::new(condition);
//!
//! // A vector that will store the identifiers found in the condition.
//! let mut identifiers = Vec::new();
//!
//! // Iterate over the events produced by the iterator.
//! while let Some(event) = iter.next() {
//!     if let DFSEvent::Enter(expr) = event {
//!         if let Expr::PatternMatch(pattern_match) = expr {
//!             identifiers.push(pattern_match.identifier.name);
//!         }
//!     }
//! }
//!
//! assert_eq!(identifiers, vec!["$a", "$b"]);
//! ```
//!
//! The example below does the same as the one above, but it also demonstrates
//! how to use [`DFSIter::prune`] for preventing the iterator from visiting
//! certain nodes. In this case we are not interested in the expression used
//! in the `at` operator, so we prune the traversal after finding a
//! `PatternMatch` expression with an `at` anchor.
//!
//! ```rust
//! # use yara_x_parser::Parser;
//! # use yara_x_parser::ast::*;
//! # use yara_x_parser::ast::dfs::{DFSIter, DFSEvent};
//! #
//! # let rules = r#"
//! # rule test {
//! #   strings:
//! #     $a = "some string"
//! #     $b = "another string"
//! #   condition:
//! #     ($a at 100) and $b
//! # }
//! # "#;
//! #
//! # let ast = AST::from(rules);
//! # let condition = &ast.rules().next().unwrap().condition;
//! #
//! let mut iter = DFSIter::new(condition);
//! let mut identifiers = Vec::new();
//!
//! while let Some(event) = iter.next() {
//!     if let DFSEvent::Enter(expr) = event {
//!         match expr {
//!             Expr::PatternMatch(pattern_match) => {
//!                 identifiers.push(pattern_match.identifier.name);
//!                 // The `at` anchor has an expression that we are not interested
//!                 // in, so we can prune the traversal to avoid visiting it.
//!                 if pattern_match.anchor.is_some() {
//!                     iter.prune();
//!                 }
//!             }
//!             // We are only interested in `PatternMatch` expressions, for any
//!             // other expression we do nothing. The iterator will continue
//!             // the traversal normally.
//!             _ => {}
//!         }
//!     }
//! }
//!
//! assert_eq!(identifiers, vec!["$a", "$b"]);
//! ```
use crate::ast::*;

/// Events yielded by [`DFSIter`].
#[derive(Debug)]
pub enum DFSEvent<T> {
    Enter(T),
    Leave(T),
}

/// Describes the context in which an expression is being visited during a
/// depth-first search traversal of the AST.
///
/// The context provides information about the relationship between the
/// expression being visited and its parent.
pub enum DFSContext<'src> {
    /// The visited expression is the one that was used for starting the
    /// traversal.
    Root,
    /// The visited expression is the body of a `for`, or `with` expression.
    /// The associated [`Expr`] is the `for` or `with` expression itself.
    Body(&'src Expr<'src>),
    /// The visited expression is the quantifier of a `for` or `of` expression.
    /// The associated [`Expr`] is the `for` or `of` expression itself.
    Quantifier(&'src Expr<'src>),
    /// The visited expression is an operand of a unary or binary expression.
    /// The associated [`Expr`] is the unary or binary expression itself.
    Operand(&'src Expr<'src>),
    /// The visited expression is part of the declarations in a `with`
    /// statement.
    WithDeclaration(&'src Expr<'src>),
    /// The visited expression is the lower or upper bound of a range.
    /// The associated [`Expr`] is the expression that contains the range.
    /// For example, in `#a in (0..10)`, the expressions `0` and `10` are
    /// visited with this context.
    Range(&'src Expr<'src>),
    /// The visited expression is an anchor that specifies where a pattern
    /// should be found. The associated [`Expr`] is the expression that
    /// contains the anchor. For example, in `$a at 10`, the expression `10`
    /// is visited with this context.
    Anchor(&'src Expr<'src>),
    /// The visited expression is one of the items in a `for..in` or `of`
    /// expression. The associated [`Expr`] is the `for..in` or `of`
    /// expression itself.
    Items(&'src Expr<'src>),
    /// The visited expression is being used as an index. The associated
    /// [`Expr`] is the expression that contains the index. For example, in
    /// `@a[i]`, the expression `i` is visited with this context.
    Index(&'src Expr<'src>),
    /// The visited expression is an argument in a function call. The
    /// associated [`Expr`] is the [`Expr::FuncCall`] itself.
    FuncArg(&'src Expr<'src>),
    /// The visited expression is the object on which a method is being
    /// called. The associated [`Expr`] is the [`Expr::FuncCall`] itself.
    FuncSelf(&'src Expr<'src>),
}

/// An iterator that performs a depth-first search traversal of the AST.
///
/// This iterator yields an [`DFSEvent::Enter`] when entering an AST node and a
/// [`DFSEvent::Leave`] when leaving it. For leaf nodes, the `Enter` and `Leave`
/// events are emitted consecutively.
pub struct DFSIter<'src> {
    stack: Vec<DFSEvent<(&'src Expr<'src>, DFSContext<'src>)>>,
    recently_left_context: Option<DFSContext<'src>>,
}

impl<'src> DFSIter<'src> {
    /// Creates a new [`DFSIter`] that traverses the tree starting at the
    /// given expression.
    pub fn new(expr: &'src Expr<'src>) -> Self {
        Self {
            stack: vec![DFSEvent::Enter((expr, DFSContext::Root))],
            recently_left_context: None,
        }
    }

    /// Returns an iterator that yields the contexts corresponding to the
    /// expressions currently being visited.
    ///
    /// When traversing an expression tree, this method returns an iterator
    /// that walks the stack of expressions being visited, from the expression
    /// currently being visited to the root of the traversal, and provides
    /// the context in which each of them is being visited.
    ///
    /// The returned iterator yields [`DFSContext`] items. The first item is
    /// the context of the expression that is currently being visited, and the
    /// last one is always [`DFSContext::Root`].
    ///
    /// # Example
    ///
    /// ```rust
    /// # use yara_x_parser::Parser;
    /// # use yara_x_parser::ast::{AST, Expr};
    /// # use yara_x_parser::ast::dfs::{DFSIter, DFSEvent, DFSContext};
    /// let rules = r#"
    /// rule test {
    ///   condition:
    ///     (1 + 2) > 3
    /// }
    /// "#;
    ///
    /// let ast = AST::from(rules);
    /// let mut iter = DFSIter::new(&ast.rules().next().unwrap().condition);
    ///
    /// // iter enters `(1 + 2) > 3`
    /// iter.next();
    /// // iter enters `1 + 2`
    /// iter.next();
    /// // iter enters `1`
    /// iter.next();
    ///
    /// // The iterator is currently in at `1` expression, let's iterate
    /// // the contexts...
    /// let mut contexts = iter.contexts();
    ///
    /// // The first context indicates that `1` is an operand of the `Add`
    /// // expression.
    /// assert!(matches!(
    ///     contexts.next(),
    ///     Some(DFSContext::Operand(Expr::Add(_)))
    /// ));
    ///
    /// // The second context indicates that the `Add` expression is an operand
    /// // of the `Gt` expression.
    /// assert!(matches!(
    ///     contexts.next(),
    ///     Some(DFSContext::Operand(Expr::Gt(_)))
    /// ));
    ///
    /// // The last context indicates that the `Gt` expression is the root one.
    /// assert!(matches!(
    ///     contexts.next(),
    ///     Some(DFSContext::Root)
    /// ));
    ///
    /// assert!(contexts.next().is_none());
    /// ```
    pub fn contexts(
        &self,
    ) -> impl DoubleEndedIterator<Item = &DFSContext<'src>> {
        itertools::chain(
            self.recently_left_context.iter(),
            self.stack.iter().rev().filter_map(|event| match event {
                DFSEvent::Enter(_) => None,
                DFSEvent::Leave((_, ctx)) => Some(ctx),
            }),
        )
    }

    /// Prunes the search tree, preventing the traversal from visiting the
    /// children of the current node.
    ///
    /// The effect of this function depends on the current position in the tree
    /// For example, if `prune` is called immediately after an [`DFSEvent::Enter`],
    /// the current node is the one that was just entered. In this scenario,
    /// pruning ensures that none of this node's children are visited, and the
    /// next event will be the corresponding [`DFSEvent::Leave`] for the node
    /// that was entered.
    ///
    /// Conversely, if `prune` is called right after an [`DFSEvent::Leave`], the
    /// current node is the parent of the node that was just left. In this
    /// case, pruning prevents any remaining children of the current node
    /// (i.e., the siblings of the node that was just left) from being visited.
    /// The next event will then be the [`DFSEvent::Leave`] for the parent of
    /// the node that was exited.
    pub fn prune(&mut self) {
        // Remove all DFSEvent::Enter from the stack until finding a
        // DFSEvent::Leave.
        while let Some(DFSEvent::Enter(_)) = self.stack.last() {
            self.stack.pop();
        }
    }
}

impl<'src> Iterator for DFSIter<'src> {
    type Item = DFSEvent<&'src Expr<'src>>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.stack.pop()? {
            DFSEvent::Enter((expr, context)) => {
                self.recently_left_context = None;
                self.stack.push(DFSEvent::Leave((expr, context)));
                dfs_enter(expr, &mut self.stack);
                Some(DFSEvent::Enter(expr))
            }
            DFSEvent::Leave((expr, context)) => {
                self.recently_left_context = Some(context);
                Some(DFSEvent::Leave(expr))
            }
        }
    }
}

fn dfs_enter<'a>(
    expr: &'a Expr,
    stack: &mut Vec<DFSEvent<(&'a Expr<'a>, DFSContext<'a>)>>,
) {
    match expr {
        Expr::True { .. }
        | Expr::False { .. }
        | Expr::Filesize { .. }
        | Expr::Entrypoint { .. }
        | Expr::LiteralString(_)
        | Expr::LiteralInteger(_)
        | Expr::LiteralFloat(_)
        | Expr::Regexp(_)
        | Expr::Ident(_) => {}

        Expr::PatternCount(p) => {
            if let Some(r) = &p.range {
                stack.push(DFSEvent::Enter((
                    &r.upper_bound,
                    DFSContext::Range(expr),
                )));
                stack.push(DFSEvent::Enter((
                    &r.lower_bound,
                    DFSContext::Range(expr),
                )));
            }
        }

        Expr::PatternOffset(p) | Expr::PatternLength(p) => {
            if let Some(index) = &p.index {
                stack.push(DFSEvent::Enter((index, DFSContext::Index(expr))));
            }
        }

        Expr::PatternMatch(m) => {
            if let Some(anchor) = &m.anchor {
                match anchor {
                    MatchAnchor::At(at) => {
                        stack.push(DFSEvent::Enter((
                            &at.expr,
                            DFSContext::Anchor(expr),
                        )));
                    }
                    MatchAnchor::In(in_expr) => {
                        stack.push(DFSEvent::Enter((
                            &in_expr.range.upper_bound,
                            DFSContext::Anchor(expr),
                        )));
                        stack.push(DFSEvent::Enter((
                            &in_expr.range.lower_bound,
                            DFSContext::Anchor(expr),
                        )));
                    }
                }
            }
        }

        Expr::Lookup(lookup) => {
            stack.push(DFSEvent::Enter((
                &lookup.index,
                DFSContext::Index(expr),
            )));
            stack.push(DFSEvent::Enter((
                &lookup.primary,
                DFSContext::Operand(expr),
            )));
        }

        Expr::FieldAccess(e) => {
            for operand in e.operands.iter().rev() {
                stack.push(DFSEvent::Enter((
                    operand,
                    DFSContext::Operand(expr),
                )));
            }
        }

        Expr::FuncCall(func) => {
            for arg in func.args.iter().rev() {
                stack.push(DFSEvent::Enter((arg, DFSContext::FuncArg(expr))));
            }
            if let Some(obj) = &func.object {
                stack.push(DFSEvent::Enter((obj, DFSContext::FuncSelf(expr))));
            }
        }

        Expr::Defined(e)
        | Expr::Not(e)
        | Expr::Minus(e)
        | Expr::BitwiseNot(e) => {
            stack.push(DFSEvent::Enter((
                &e.operand,
                DFSContext::Operand(expr),
            )));
        }

        Expr::And(e) | Expr::Or(e) => {
            for operand in e.operands.iter().rev() {
                stack.push(DFSEvent::Enter((
                    operand,
                    DFSContext::Operand(expr),
                )));
            }
        }

        Expr::Add(e)
        | Expr::Sub(e)
        | Expr::Mul(e)
        | Expr::Div(e)
        | Expr::Mod(e) => {
            for operand in e.operands.iter().rev() {
                stack.push(DFSEvent::Enter((
                    operand,
                    DFSContext::Operand(expr),
                )));
            }
        }

        Expr::Shl(e)
        | Expr::Shr(e)
        | Expr::BitwiseAnd(e)
        | Expr::BitwiseOr(e)
        | Expr::BitwiseXor(e)
        | Expr::Eq(e)
        | Expr::Ne(e)
        | Expr::Lt(e)
        | Expr::Gt(e)
        | Expr::Le(e)
        | Expr::Ge(e)
        | Expr::Contains(e)
        | Expr::IContains(e)
        | Expr::StartsWith(e)
        | Expr::IStartsWith(e)
        | Expr::EndsWith(e)
        | Expr::IEndsWith(e)
        | Expr::IEquals(e)
        | Expr::Matches(e) => {
            stack.push(DFSEvent::Enter((&e.rhs, DFSContext::Operand(expr))));
            stack.push(DFSEvent::Enter((&e.lhs, DFSContext::Operand(expr))));
        }

        Expr::Of(of) => {
            if let Some(anchor) = &of.anchor {
                match anchor {
                    MatchAnchor::At(at) => {
                        stack.push(DFSEvent::Enter((
                            &at.expr,
                            DFSContext::Anchor(expr),
                        )));
                    }
                    MatchAnchor::In(in_expr) => {
                        stack.push(DFSEvent::Enter((
                            &in_expr.range.upper_bound,
                            DFSContext::Anchor(expr),
                        )));
                        stack.push(DFSEvent::Enter((
                            &in_expr.range.lower_bound,
                            DFSContext::Anchor(expr),
                        )));
                    }
                }
            }
            if let OfItems::BoolExprTuple(tuple) = &of.items {
                for item in tuple.iter().rev() {
                    stack.push(DFSEvent::Enter((
                        item,
                        DFSContext::Items(expr),
                    )));
                }
            }
            match &of.quantifier {
                Quantifier::Percentage(quantifier)
                | Quantifier::Expr(quantifier) => {
                    stack.push(DFSEvent::Enter((
                        quantifier,
                        DFSContext::Quantifier(expr),
                    )));
                }
                _ => {}
            }
        }

        Expr::ForOf(for_of) => {
            stack
                .push(DFSEvent::Enter((&for_of.body, DFSContext::Body(expr))));
            match &for_of.quantifier {
                Quantifier::Percentage(quantifier)
                | Quantifier::Expr(quantifier) => {
                    stack.push(DFSEvent::Enter((
                        quantifier,
                        DFSContext::Quantifier(expr),
                    )));
                }
                _ => {}
            }
        }

        Expr::ForIn(for_in) => {
            stack
                .push(DFSEvent::Enter((&for_in.body, DFSContext::Body(expr))));
            match &for_in.iterable {
                Iterable::Range(range) => {
                    stack.push(DFSEvent::Enter((
                        &range.upper_bound,
                        DFSContext::Items(expr),
                    )));
                    stack.push(DFSEvent::Enter((
                        &range.lower_bound,
                        DFSContext::Items(expr),
                    )));
                }
                Iterable::ExprTuple(tuple) => {
                    for item in tuple.iter().rev() {
                        stack.push(DFSEvent::Enter((
                            item,
                            DFSContext::Items(expr),
                        )));
                    }
                }
                Iterable::Expr(iterable_expr) => {
                    stack.push(DFSEvent::Enter((
                        iterable_expr,
                        DFSContext::Items(expr),
                    )));
                }
            }
            match &for_in.quantifier {
                Quantifier::Percentage(quantifier)
                | Quantifier::Expr(quantifier) => {
                    stack.push(DFSEvent::Enter((
                        quantifier,
                        DFSContext::Quantifier(expr),
                    )));
                }
                _ => {}
            }
        }
        Expr::With(with) => {
            stack.push(DFSEvent::Enter((&with.body, DFSContext::Body(expr))));
            for declaration in with.declarations.iter().rev() {
                stack.push(DFSEvent::Enter((
                    &declaration.expression,
                    DFSContext::WithDeclaration(expr),
                )));
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::ast::dfs::{DFSContext, DFSEvent, DFSIter};
    use crate::ast::{Expr, AST};

    #[test]
    fn dfs() {
        let source = br#"
            rule test {
                condition:
                    (true and false) or (1 + 2 > 5)
            }
            "#;

        let ast = AST::from(source.as_slice());
        let mut dfs = DFSIter::new(&ast.rules().next().unwrap().condition);

        // enter: (true and false) or (1 + 2 > 5)
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::Or(_)))));
        // enter: true and false
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::And(_)))));

        // Prune the tree, children of the current node won't be visited.
        dfs.prune();

        // leave: true and false
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::And(_)))));
        // enter: 1 + 2 > 5
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::Gt(_)))));
        // enter: 1 + 2
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::Add(_)))));
        // enter: 1
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Enter(Expr::LiteralInteger(_)))
        ));
        // leave: 1
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Leave(Expr::LiteralInteger(_)))
        ));

        // Prune the tree. Siblings of 1 won't be traversed.
        dfs.prune();

        // leave: 1 + 2
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::Add(_)))));
        // enter: 5
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Enter(Expr::LiteralInteger(_)))
        ));
        // leave: 5
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Leave(Expr::LiteralInteger(_)))
        ));
        // leave: 1 + 2 > 5
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::Gt(_)))));
        // leave: (true and false) or (1 + 2 > 5)
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::Or(_)))));

        assert!(dfs.next().is_none());
    }

    #[test]
    fn dfs_contexts() {
        let source = r#"
            rule test {
                strings:
                    $a = "foo"
                condition:
                    for 1 of ($a) : (
                        with i = 1 : (
                            i == 1
                        )
                    )
            }
            "#;

        let ast = AST::from(source);
        let mut dfs = DFSIter::new(&ast.rules().next().unwrap().condition);
        assert!(dfs.contexts().next().is_none());

        // enter `for 1 of ($a) : (...)`
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::ForOf(_)))));

        let mut contexts = dfs.contexts();
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // enter `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Enter(Expr::LiteralInteger(_)))
        ));

        let mut contexts = dfs.contexts();
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Quantifier(Expr::ForOf(_)))
        ));
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // leave `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Leave(Expr::LiteralInteger(_)))
        ));

        let mut contexts = dfs.contexts();
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Quantifier(Expr::ForOf(_)))
        ));
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // enter `with i = 1 : ( i == 1 )`
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::With(_)))));

        let mut contexts = dfs.contexts();
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Body(Expr::ForOf(_)))
        ));
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // enter `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Enter(Expr::LiteralInteger(_)))
        ));
        // leave `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Leave(Expr::LiteralInteger(_)))
        ));

        // enter `i == 1`
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::Eq(_)))));

        let mut contexts = dfs.contexts();
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Body(Expr::With(_)))
        ));
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Body(Expr::ForOf(_)))
        ));
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // enter `i`
        assert!(matches!(dfs.next(), Some(DFSEvent::Enter(Expr::Ident(_)))));

        let mut contexts = dfs.contexts();
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Operand(Expr::Eq(_)))
        ));
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Body(Expr::With(_)))
        ));
        assert!(matches!(
            contexts.next(),
            Some(DFSContext::Body(Expr::ForOf(_)))
        ));
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
        drop(contexts);

        // leave `i`
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::Ident(_)))));

        // enter `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Enter(Expr::LiteralInteger(_)))
        ));
        // leave `1`
        assert!(matches!(
            dfs.next(),
            Some(DFSEvent::Leave(Expr::LiteralInteger(_)))
        ));

        // leave `i == 1`
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::Eq(_)))));
        // leave `with i = 1 : ( i == 1 )`
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::With(_)))));
        // leave `for 1 of ($a) : (...)`
        assert!(matches!(dfs.next(), Some(DFSEvent::Leave(Expr::ForOf(_)))));

        let mut contexts = dfs.contexts();
        assert!(matches!(contexts.next(), Some(DFSContext::Root)));
        assert!(contexts.next().is_none());
    }
}