File size: 1,945 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use swc_core::quote;
use turbo_tasks::{NonLocalValue, Vc, debug::ValueDebugFormat, trace::TraceRawVcs};
use turbopack_core::chunk::ChunkingContext;

use super::AstPath;
use crate::{
    code_gen::{CodeGen, CodeGeneration},
    create_visitor,
};

#[derive(
    Copy, Clone, Hash, PartialEq, Eq, Debug, Serialize, Deserialize, TraceRawVcs, NonLocalValue,
)]
pub enum ConstantConditionValue {
    Truthy,
    Falsy,
    Nullish,
}

#[derive(PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, ValueDebugFormat, NonLocalValue)]
pub struct ConstantConditionCodeGen {
    value: ConstantConditionValue,
    path: AstPath,
}

impl ConstantConditionCodeGen {
    pub fn new(value: ConstantConditionValue, path: AstPath) -> Self {
        ConstantConditionCodeGen { value, path }
    }

    pub async fn code_generation(
        &self,
        _chunking_context: Vc<Box<dyn ChunkingContext>>,
    ) -> Result<CodeGeneration> {
        let value = self.value;
        let visitors = [create_visitor!(
            exact,
            self.path,
            visit_mut_expr,
            |expr: &mut Expr| {
                *expr = match value {
                    ConstantConditionValue::Truthy => {
                        quote!("(\"TURBOPACK compile-time truthy\", 1)" as Expr)
                    }
                    ConstantConditionValue::Falsy => {
                        quote!("(\"TURBOPACK compile-time falsy\", 0)" as Expr)
                    }
                    ConstantConditionValue::Nullish => {
                        quote!("(\"TURBOPACK compile-time nullish\", null)" as Expr)
                    }
                };
            }
        )]
        .into();

        Ok(CodeGeneration::visitors(visitors))
    }
}

impl From<ConstantConditionCodeGen> for CodeGen {
    fn from(val: ConstantConditionCodeGen) -> Self {
        CodeGen::ConstantConditionCodeGen(val)
    }
}