swc_ecma_transforms_optimization/
debug.rs

1#![allow(unused)]
2
3use swc_ecma_ast::*;
4use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
5
6/// Assert in debug mode. This is noop in release build.
7#[cfg_attr(not(debug_assertions), inline(always))]
8pub fn debug_assert_valid<N>(node: &N)
9where
10    N: VisitWith<AssertValid>,
11{
12    #[cfg(debug_assertions)]
13    node.visit_with(&mut AssertValid);
14}
15
16#[cfg(debug_assertions)]
17struct Ctx<'a> {
18    v: &'a dyn std::fmt::Debug,
19}
20
21#[cfg(debug_assertions)]
22impl Drop for Ctx<'_> {
23    fn drop(&mut self) {
24        eprintln!("Context: {:?}", self.v);
25    }
26}
27
28pub struct AssertValid;
29
30impl Visit for AssertValid {
31    noop_visit_type!(fail);
32
33    #[cfg(debug_assertions)]
34    fn visit_expr(&mut self, n: &Expr) {
35        let ctx = Ctx { v: n };
36        n.visit_children_with(self);
37        std::mem::forget(ctx);
38    }
39
40    #[cfg(debug_assertions)]
41    fn visit_invalid(&mut self, _: &Invalid) {
42        panic!("Invalid node found");
43    }
44
45    #[cfg(debug_assertions)]
46    fn visit_number(&mut self, n: &Number) {
47        assert!(!n.value.is_nan(), "NaN should be an identifier");
48    }
49
50    #[cfg(debug_assertions)]
51    fn visit_setter_prop(&mut self, p: &SetterProp) {
52        p.body.visit_with(self);
53    }
54
55    #[cfg(debug_assertions)]
56    fn visit_stmt(&mut self, n: &Stmt) {
57        let ctx = Ctx { v: n };
58        n.visit_children_with(self);
59        std::mem::forget(ctx);
60    }
61
62    #[cfg(debug_assertions)]
63    fn visit_tpl(&mut self, l: &Tpl) {
64        l.visit_children_with(self);
65
66        assert_eq!(l.exprs.len() + 1, l.quasis.len());
67    }
68
69    #[cfg(debug_assertions)]
70    fn visit_var_declarators(&mut self, v: &[VarDeclarator]) {
71        v.visit_children_with(self);
72
73        if v.is_empty() {
74            panic!("Found empty var declarators");
75        }
76    }
77
78    #[cfg(debug_assertions)]
79    fn visit_seq_expr(&mut self, v: &SeqExpr) {
80        v.visit_children_with(self);
81
82        // TODO(kdy1): Make parser does not create invalid sequential
83        // expressions and uncomment this
84
85        // assert!(
86        //     v.exprs.len() >= 2,
87        //     "SeqExpr(len = {}) is invalid",
88        //     v.exprs.len()
89        // );
90    }
91}