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
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
    Category, Example, IntoPipelineData, LazyRecord, PipelineData, ShellError, Signature, Span,
    Spanned, SyntaxShape, Type, Value,
};

#[derive(Clone)]
pub struct LazyMake;

impl Command for LazyMake {
    fn name(&self) -> &str {
        "lazy make"
    }

    fn signature(&self) -> Signature {
        Signature::build("lazy make")
            .input_output_types(vec![(Type::Nothing, Type::Record(vec![]))])
            .required_named(
                "columns",
                SyntaxShape::List(Box::new(SyntaxShape::String)),
                "Closure that gets called when the LazyRecord needs to list the available column names",
                Some('c')
            )
            .required_named(
                "get-value",
                SyntaxShape::Closure(Some(vec![SyntaxShape::String])),
                "Closure to call when a value needs to be produced on demand",
                Some('g')
            )
            .category(Category::Core)
    }

    fn usage(&self) -> &str {
        "Create a lazy record."
    }

    fn extra_usage(&self) -> &str {
        "Lazy records are special records that only evaluate their values once the property is requested.
        For example, when printing a lazy record, all of its fields will be collected. But when accessing
        a specific property, only it will be evaluated.

        Note that this is unrelated to the lazyframes feature bundled with dataframes."
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["deferred", "record", "procedural"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        _input: PipelineData,
    ) -> Result<PipelineData, ShellError> {
        let span = call.head;
        let columns: Vec<Spanned<String>> = call
            .get_flag(engine_state, stack, "columns")?
            .expect("required flag");

        let get_value: Closure = call
            .get_flag(engine_state, stack, "get-value")?
            .expect("required flag");

        let mut unique = HashMap::with_capacity(columns.len());

        for col in &columns {
            match unique.entry(&col.item) {
                Entry::Occupied(entry) => {
                    return Err(ShellError::ColumnDefinedTwice {
                        col_name: col.item.clone(),
                        second_use: col.span,
                        first_use: *entry.get(),
                    });
                }
                Entry::Vacant(entry) => {
                    entry.insert(col.span);
                }
            }
        }

        Ok(Value::lazy_record(
            Box::new(NuLazyRecord {
                engine_state: engine_state.clone(),
                stack: Arc::new(Mutex::new(stack.clone())),
                columns: columns.into_iter().map(|s| s.item).collect(),
                get_value,
                span,
            }),
            span,
        )
        .into_pipeline_data())
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            // TODO: Figure out how to "test" these examples, or leave results as None
            Example {
                description: "Create a lazy record",
                example: r#"lazy make --columns ["haskell", "futures", "nushell"] --get-value { |lazything| $lazything + "!" }"#,
                result: None,
            },
            Example {
                description: "Test the laziness of lazy records",
                example: r#"lazy make --columns ["hello"] --get-value { |key| print $"getting ($key)!"; $key | str upcase }"#,
                result: None,
            },
        ]
    }
}

#[derive(Clone)]
struct NuLazyRecord {
    engine_state: EngineState,
    stack: Arc<Mutex<Stack>>,
    columns: Vec<String>,
    get_value: Closure,
    span: Span,
}

impl std::fmt::Debug for NuLazyRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NuLazyRecord").finish()
    }
}

impl<'a> LazyRecord<'a> for NuLazyRecord {
    fn column_names(&'a self) -> Vec<&'a str> {
        self.columns.iter().map(|column| column.as_str()).collect()
    }

    fn get_column_value(&self, column: &str) -> Result<Value, ShellError> {
        let block = self.engine_state.get_block(self.get_value.block_id);
        let mut stack = self.stack.lock().expect("lock must not be poisoned");
        let column_value = Value::string(column, self.span);

        if let Some(var) = block.signature.get_positional(0) {
            if let Some(var_id) = &var.var_id {
                stack.add_var(*var_id, column_value.clone());
            }
        }

        let pipeline_result = eval_block(
            &self.engine_state,
            &mut stack,
            block,
            PipelineData::Value(column_value, None),
            false,
            false,
        );

        pipeline_result.map(|data| match data {
            PipelineData::Value(value, ..) => value,
            // TODO: Proper error handling.
            _ => Value::nothing(self.span),
        })
    }

    fn span(&self) -> Span {
        self.span
    }

    fn clone_value(&self, span: Span) -> Value {
        Value::lazy_record(Box::new((*self).clone()), span)
    }
}