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
use std::hash::Hash;
#[cfg(feature = "cse")]
use std::hash::Hasher;

use super::*;
use crate::constants::{get_len_name, LITERAL_NAME};

#[derive(Default, Debug, Clone, Hash, PartialEq, Eq)]
pub enum OutputName {
    #[default]
    None,
    LiteralLhs(ColumnName),
    ColumnLhs(ColumnName),
    Alias(ColumnName),
}

impl OutputName {
    fn unwrap(&self) -> &ColumnName {
        match self {
            OutputName::Alias(name) => name,
            OutputName::ColumnLhs(name) => name,
            OutputName::LiteralLhs(name) => name,
            OutputName::None => panic!("no output name set"),
        }
    }

    pub(crate) fn is_none(&self) -> bool {
        matches!(self, OutputName::None)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExprIR {
    /// Output name of this expression.
    output_name: OutputName,
    /// Reduced expression.
    /// This expression is pruned from `alias` and already expanded.
    node: Node,
}

impl ExprIR {
    pub fn new(node: Node, output_name: OutputName) -> Self {
        debug_assert!(!output_name.is_none());
        ExprIR { output_name, node }
    }

    pub fn from_node(node: Node, arena: &Arena<AExpr>) -> Self {
        let mut out = Self {
            node,
            output_name: OutputName::None,
        };
        out.node = node;
        for (_, ae) in arena.iter(node) {
            match ae {
                AExpr::Column(name) => {
                    out.output_name = OutputName::ColumnLhs(name.clone());
                    break;
                },
                AExpr::Literal(lv) => {
                    if let LiteralValue::Series(s) = lv {
                        out.output_name = OutputName::LiteralLhs(s.name().into());
                    } else {
                        out.output_name = OutputName::LiteralLhs(LITERAL_NAME.into());
                    }
                    break;
                },
                AExpr::Function {
                    input, function, ..
                } => {
                    if input.is_empty() {
                        out.output_name =
                            OutputName::LiteralLhs(ColumnName::from(format!("{}", function)));
                    } else {
                        out.output_name = input[0].output_name.clone();
                    }
                    break;
                },
                AExpr::AnonymousFunction { input, options, .. } => {
                    if input.is_empty() {
                        out.output_name = OutputName::LiteralLhs(ColumnName::from(options.fmt_str));
                    } else {
                        out.output_name = input[0].output_name.clone();
                    }
                    break;
                },
                AExpr::Len => out.output_name = OutputName::LiteralLhs(get_len_name()),
                AExpr::Alias(_, _) => {
                    // Should be removed during conversion.
                    #[cfg(debug_assertions)]
                    {
                        unreachable!()
                    }
                },
                _ => {},
            }
        }
        debug_assert!(!out.output_name.is_none());
        out
    }

    #[inline]
    pub fn node(&self) -> Node {
        self.node
    }

    pub(crate) fn set_node(&mut self, node: Node) {
        self.node = node;
    }

    #[cfg(feature = "cse")]
    pub(crate) fn set_alias(&mut self, name: ColumnName) {
        self.output_name = OutputName::Alias(name)
    }

    pub(crate) fn output_name_inner(&self) -> &OutputName {
        &self.output_name
    }

    pub(crate) fn output_name_arc(&self) -> &Arc<str> {
        self.output_name.unwrap()
    }

    pub fn output_name(&self) -> &str {
        self.output_name_arc().as_ref()
    }

    pub fn to_expr(&self, expr_arena: &Arena<AExpr>) -> Expr {
        let out = node_to_expr(self.node, expr_arena);

        match &self.output_name {
            OutputName::Alias(name) => out.alias(name.as_ref()),
            _ => out,
        }
    }

    pub fn get_alias(&self) -> Option<&ColumnName> {
        match &self.output_name {
            OutputName::Alias(name) => Some(name),
            _ => None,
        }
    }

    // Utility for debugging.
    #[cfg(debug_assertions)]
    #[allow(dead_code)]
    pub(crate) fn print(&self, expr_arena: &Arena<AExpr>) {
        eprintln!("{:?}", self.to_expr(expr_arena))
    }

    pub(crate) fn has_alias(&self) -> bool {
        matches!(self.output_name, OutputName::Alias(_))
    }

    #[cfg(feature = "cse")]
    pub(crate) fn traverse_and_hash<H: Hasher>(&self, expr_arena: &Arena<AExpr>, state: &mut H) {
        traverse_and_hash_aexpr(self.node, expr_arena, state);
        if let Some(alias) = self.get_alias() {
            alias.hash(state)
        }
    }
}

impl AsRef<ExprIR> for ExprIR {
    fn as_ref(&self) -> &ExprIR {
        self
    }
}

/// A Node that is restricted to `AExpr::Column`
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct ColumnNode(pub(crate) Node);

impl From<ColumnNode> for Node {
    fn from(value: ColumnNode) -> Self {
        value.0
    }
}
impl From<&ExprIR> for Node {
    fn from(value: &ExprIR) -> Self {
        value.node()
    }
}

pub(crate) fn name_to_expr_ir(name: &str, expr_arena: &mut Arena<AExpr>) -> ExprIR {
    let name = ColumnName::from(name);
    let node = expr_arena.add(AExpr::Column(name.clone()));
    ExprIR::new(node, OutputName::ColumnLhs(name))
}

pub(crate) fn names_to_expr_irs<I: IntoIterator<Item = S>, S: AsRef<str>>(
    names: I,
    expr_arena: &mut Arena<AExpr>,
) -> Vec<ExprIR> {
    names
        .into_iter()
        .map(|name| {
            let name = name.as_ref();
            name_to_expr_ir(name, expr_arena)
        })
        .collect()
}