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 nu_protocol::{
    ast::{Expr, Expression, RecordItem},
    Span, Value,
};

use crate::{IntoValue, NewEmpty};

pub trait IntoExpression {
    fn into_expression(self) -> Expression;
}

pub trait ValueIntoExpression {
    fn into_expression(self) -> Expression;
    fn into_expr(self) -> Expr;
}

impl<V: IntoValue> IntoExpression for V {
    #[inline]
    fn into_expression(self) -> Expression {
        self.into_value().into_expression()
    }
}

impl ValueIntoExpression for Value {
    fn into_expression(self) -> Expression {
        let ty = self.get_type();

        Expression {
            expr: self.into_expr(),
            span: Span::empty(),
            ty,
            custom_completion: None,
        }
    }

    fn into_expr(self) -> Expr {
        match self {
            Value::Bool { val, .. } => Expr::Bool(val),
            Value::Int { val, .. } => Expr::Int(val),
            Value::Float { val, .. } => Expr::Float(val),
            Value::Filesize { val, .. } => Expr::Int(val),
            Value::Duration { val, .. } => Expr::Int(val),
            Value::Date { val, .. } => Expr::DateTime(val),
            Value::String { val, .. } => Expr::String(val),
            Value::Record { val, .. } => {
                let entries = val
                    .into_iter()
                    .map(|(col, val)| {
                        RecordItem::Pair(col.into_expression(), val.into_expression())
                    })
                    .collect();

                Expr::Record(entries)
            }
            Value::List { vals, .. } => {
                let vals = vals.into_iter().map(|v| v.into_expression()).collect();
                Expr::List(vals)
            }
            Value::Block { val, .. } => Expr::Block(val),
            Value::Nothing { .. } => Expr::Nothing,
            Value::Error { error, .. } => Expr::String(error.to_string()),
            Value::Binary { val, .. } => Expr::Binary(val),
            Value::CellPath { val, .. } => Expr::CellPath(val),
            _ => Expr::Nothing,
        }
    }
}