nu_engine/
eval.rs

1use crate::eval_ir::eval_ir_block;
2#[allow(deprecated)]
3use crate::get_full_help;
4use nu_protocol::{
5    BlockId, Config, ENV_VARIABLE_ID, IntoPipelineData, PipelineData, PipelineExecutionData,
6    ShellError, Span, Value, VarId,
7    ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument, PathMember},
8    debugger::DebugContext,
9    engine::{Closure, EngineState, Stack},
10    eval_base::Eval,
11};
12use nu_utils::IgnoreCaseExt;
13use std::sync::Arc;
14
15pub fn eval_call<D: DebugContext>(
16    engine_state: &EngineState,
17    caller_stack: &mut Stack,
18    call: &Call,
19    input: PipelineData,
20) -> Result<PipelineData, ShellError> {
21    engine_state.signals().check(&call.head)?;
22    let decl = engine_state.get_decl(call.decl_id);
23
24    if !decl.is_known_external() && call.named_iter().any(|(flag, _, _)| flag.item == "help") {
25        let help = get_full_help(decl, engine_state, caller_stack);
26        Ok(Value::string(help, call.head).into_pipeline_data())
27    } else if let Some(block_id) = decl.block_id() {
28        let block = engine_state.get_block(block_id);
29
30        let mut callee_stack = caller_stack.gather_captures(engine_state, &block.captures);
31
32        // Rust does not check recursion limits outside of const evaluation.
33        // But nu programs run in the same process as the shell.
34        // To prevent a stack overflow in user code from crashing the shell,
35        // we limit the recursion depth of function calls.
36        // Picked 50 arbitrarily, should work on all architectures.
37        let maximum_call_stack_depth: u64 = engine_state.config.recursion_limit as u64;
38        callee_stack.recursion_count += 1;
39        if callee_stack.recursion_count > maximum_call_stack_depth {
40            callee_stack.recursion_count = 0;
41            return Err(ShellError::RecursionLimitReached {
42                recursion_limit: maximum_call_stack_depth,
43                span: block.span,
44            });
45        }
46
47        for (param_idx, (param, required)) in decl
48            .signature()
49            .required_positional
50            .iter()
51            .map(|p| (p, true))
52            .chain(
53                decl.signature()
54                    .optional_positional
55                    .iter()
56                    .map(|p| (p, false)),
57            )
58            .enumerate()
59        {
60            let var_id = param
61                .var_id
62                .expect("internal error: all custom parameters must have var_ids");
63
64            if let Some(arg) = call.positional_nth(param_idx) {
65                let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
66                let param_type = param.shape.to_type();
67                if required && !result.is_subtype_of(&param_type) {
68                    return Err(ShellError::CantConvert {
69                        to_type: param.shape.to_type().to_string(),
70                        from_type: result.get_type().to_string(),
71                        span: result.span(),
72                        help: None,
73                    });
74                }
75                callee_stack.add_var(var_id, result);
76            } else if let Some(value) = &param.default_value {
77                callee_stack.add_var(var_id, value.to_owned());
78            } else {
79                callee_stack.add_var(var_id, Value::nothing(call.head));
80            }
81        }
82
83        if let Some(rest_positional) = decl.signature().rest_positional {
84            let mut rest_items = vec![];
85
86            for result in call.rest_iter_flattened(
87                decl.signature().required_positional.len()
88                    + decl.signature().optional_positional.len(),
89                |expr| eval_expression::<D>(engine_state, caller_stack, expr),
90            )? {
91                rest_items.push(result);
92            }
93
94            let span = if let Some(rest_item) = rest_items.first() {
95                rest_item.span()
96            } else {
97                call.head
98            };
99
100            callee_stack.add_var(
101                rest_positional
102                    .var_id
103                    .expect("Internal error: rest positional parameter lacks var_id"),
104                Value::list(rest_items, span),
105            )
106        }
107
108        for named in decl.signature().named {
109            if let Some(var_id) = named.var_id {
110                let mut found = false;
111                for call_named in call.named_iter() {
112                    if let (Some(spanned), Some(short)) = (&call_named.1, named.short) {
113                        if spanned.item == short.to_string() {
114                            if let Some(arg) = &call_named.2 {
115                                let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
116
117                                callee_stack.add_var(var_id, result);
118                            } else if let Some(value) = &named.default_value {
119                                callee_stack.add_var(var_id, value.to_owned());
120                            } else {
121                                callee_stack.add_var(var_id, Value::bool(true, call.head))
122                            }
123                            found = true;
124                        }
125                    } else if call_named.0.item == named.long {
126                        if let Some(arg) = &call_named.2 {
127                            let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
128
129                            callee_stack.add_var(var_id, result);
130                        } else if let Some(value) = &named.default_value {
131                            callee_stack.add_var(var_id, value.to_owned());
132                        } else {
133                            callee_stack.add_var(var_id, Value::bool(true, call.head))
134                        }
135                        found = true;
136                    }
137                }
138
139                if !found {
140                    if named.arg.is_none() {
141                        callee_stack.add_var(var_id, Value::bool(false, call.head))
142                    } else if let Some(value) = named.default_value {
143                        callee_stack.add_var(var_id, value);
144                    } else {
145                        callee_stack.add_var(var_id, Value::nothing(call.head))
146                    }
147                }
148            }
149        }
150
151        let result =
152            eval_block_with_early_return::<D>(engine_state, &mut callee_stack, block, input)
153                .map(|p| p.body);
154
155        if block.redirect_env {
156            redirect_env(engine_state, caller_stack, &callee_stack);
157        }
158
159        result
160    } else {
161        // We pass caller_stack here with the knowledge that internal commands
162        // are going to be specifically looking for global state in the stack
163        // rather than any local state.
164        decl.run(engine_state, caller_stack, &call.into(), input)
165    }
166}
167
168/// Redirect the environment from callee to the caller.
169pub fn redirect_env(engine_state: &EngineState, caller_stack: &mut Stack, callee_stack: &Stack) {
170    // Grab all environment variables from the callee
171    let caller_env_vars = caller_stack.get_env_var_names(engine_state);
172
173    // remove env vars that are present in the caller but not in the callee
174    // (the callee hid them)
175    for var in caller_env_vars.iter() {
176        if !callee_stack.has_env_var(engine_state, var) {
177            caller_stack.remove_env_var(engine_state, var);
178        }
179    }
180
181    // add new env vars from callee to caller
182    for (var, value) in callee_stack.get_stack_env_vars() {
183        caller_stack.add_env_var(var, value);
184    }
185
186    // set config to callee config, to capture any updates to that
187    caller_stack.config.clone_from(&callee_stack.config);
188}
189
190fn eval_external(
191    engine_state: &EngineState,
192    stack: &mut Stack,
193    head: &Expression,
194    args: &[ExternalArgument],
195    input: PipelineData,
196) -> Result<PipelineData, ShellError> {
197    let decl_id = engine_state
198        .find_decl("run-external".as_bytes(), &[])
199        .ok_or(ShellError::ExternalNotSupported {
200            span: head.span(&engine_state),
201        })?;
202
203    let command = engine_state.get_decl(decl_id);
204
205    let mut call = Call::new(head.span(&engine_state));
206
207    call.add_positional(head.clone());
208
209    for arg in args {
210        match arg {
211            ExternalArgument::Regular(expr) => call.add_positional(expr.clone()),
212            ExternalArgument::Spread(expr) => call.add_spread(expr.clone()),
213        }
214    }
215
216    command.run(engine_state, stack, &(&call).into(), input)
217}
218
219pub fn eval_expression<D: DebugContext>(
220    engine_state: &EngineState,
221    stack: &mut Stack,
222    expr: &Expression,
223) -> Result<Value, ShellError> {
224    let stack = &mut stack.start_collect_value();
225    <EvalRuntime as Eval>::eval::<D>(engine_state, stack, expr)
226}
227
228/// Checks the expression to see if it's a internal or external call. If so, passes the input
229/// into the call and gets out the result
230/// Otherwise, invokes the expression
231///
232/// It returns PipelineData with a boolean flag, indicating if the external failed to run.
233/// The boolean flag **may only be true** for external calls, for internal calls, it always to be false.
234pub fn eval_expression_with_input<D: DebugContext>(
235    engine_state: &EngineState,
236    stack: &mut Stack,
237    expr: &Expression,
238    mut input: PipelineData,
239) -> Result<PipelineData, ShellError> {
240    match &expr.expr {
241        Expr::Call(call) => {
242            input = eval_call::<D>(engine_state, stack, call, input)?;
243        }
244        Expr::ExternalCall(head, args) => {
245            input = eval_external(engine_state, stack, head, args, input)?;
246        }
247
248        Expr::Collect(var_id, expr) => {
249            input = eval_collect::<D>(engine_state, stack, *var_id, expr, input)?;
250        }
251
252        Expr::Subexpression(block_id) => {
253            let block = engine_state.get_block(*block_id);
254            // FIXME: protect this collect with ctrl-c
255            input = eval_subexpression::<D>(engine_state, stack, block, input)?;
256        }
257
258        Expr::FullCellPath(full_cell_path) => match &full_cell_path.head {
259            Expression {
260                expr: Expr::Subexpression(block_id),
261                span,
262                ..
263            } => {
264                let block = engine_state.get_block(*block_id);
265
266                if !full_cell_path.tail.is_empty() {
267                    let stack = &mut stack.start_collect_value();
268                    // FIXME: protect this collect with ctrl-c
269                    input = eval_subexpression::<D>(engine_state, stack, block, input)?
270                        .into_value(*span)?
271                        .follow_cell_path(&full_cell_path.tail)?
272                        .into_owned()
273                        .into_pipeline_data()
274                } else {
275                    input = eval_subexpression::<D>(engine_state, stack, block, input)?;
276                }
277            }
278            _ => {
279                input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data();
280            }
281        },
282
283        _ => {
284            input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data();
285        }
286    };
287
288    Ok(input)
289}
290
291pub fn eval_block<D: DebugContext>(
292    engine_state: &EngineState,
293    stack: &mut Stack,
294    block: &Block,
295    input: PipelineData,
296) -> Result<PipelineExecutionData, ShellError> {
297    let result = eval_ir_block::<D>(engine_state, stack, block, input);
298    if let Err(err) = &result {
299        stack.set_last_error(err);
300    }
301    result
302}
303
304pub fn eval_block_with_early_return<D: DebugContext>(
305    engine_state: &EngineState,
306    stack: &mut Stack,
307    block: &Block,
308    input: PipelineData,
309) -> Result<PipelineExecutionData, ShellError> {
310    match eval_block::<D>(engine_state, stack, block, input) {
311        Err(ShellError::Return { span: _, value }) => Ok(PipelineExecutionData::from(
312            PipelineData::value(*value, None),
313        )),
314        x => x,
315    }
316}
317
318pub fn eval_collect<D: DebugContext>(
319    engine_state: &EngineState,
320    stack: &mut Stack,
321    var_id: VarId,
322    expr: &Expression,
323    input: PipelineData,
324) -> Result<PipelineData, ShellError> {
325    // Evaluate the expression with the variable set to the collected input
326    let span = input.span().unwrap_or(Span::unknown());
327
328    let metadata = input.metadata().and_then(|m| m.for_collect());
329
330    let input = input.into_value(span)?;
331
332    stack.add_var(var_id, input.clone());
333
334    let result = eval_expression_with_input::<D>(
335        engine_state,
336        stack,
337        expr,
338        // We still have to pass it as input
339        input.into_pipeline_data_with_metadata(metadata),
340    );
341
342    stack.remove_var(var_id);
343
344    result
345}
346
347pub fn eval_subexpression<D: DebugContext>(
348    engine_state: &EngineState,
349    stack: &mut Stack,
350    block: &Block,
351    input: PipelineData,
352) -> Result<PipelineData, ShellError> {
353    eval_block::<D>(engine_state, stack, block, input).map(|p| p.body)
354}
355
356pub fn eval_variable(
357    engine_state: &EngineState,
358    stack: &Stack,
359    var_id: VarId,
360    span: Span,
361) -> Result<Value, ShellError> {
362    match var_id {
363        // $nu
364        nu_protocol::NU_VARIABLE_ID => {
365            if let Some(val) = engine_state.get_constant(var_id) {
366                Ok(val.clone())
367            } else {
368                Err(ShellError::VariableNotFoundAtRuntime { span })
369            }
370        }
371        // $env
372        ENV_VARIABLE_ID => {
373            let env_vars = stack.get_env_vars(engine_state);
374            let env_columns = env_vars.keys();
375            let env_values = env_vars.values();
376
377            let mut pairs = env_columns
378                .map(|x| x.to_string())
379                .zip(env_values.cloned())
380                .collect::<Vec<(String, Value)>>();
381
382            pairs.sort_by(|a, b| a.0.cmp(&b.0));
383
384            Ok(Value::record(pairs.into_iter().collect(), span))
385        }
386        var_id => stack.get_var(var_id, span),
387    }
388}
389
390struct EvalRuntime;
391
392impl Eval for EvalRuntime {
393    type State<'a> = &'a EngineState;
394
395    type MutState = Stack;
396
397    fn get_config(engine_state: Self::State<'_>, stack: &mut Stack) -> Arc<Config> {
398        stack.get_config(engine_state)
399    }
400
401    fn eval_var(
402        engine_state: &EngineState,
403        stack: &mut Stack,
404        var_id: VarId,
405        span: Span,
406    ) -> Result<Value, ShellError> {
407        eval_variable(engine_state, stack, var_id, span)
408    }
409
410    fn eval_call<D: DebugContext>(
411        engine_state: &EngineState,
412        stack: &mut Stack,
413        call: &Call,
414        _: Span,
415    ) -> Result<Value, ShellError> {
416        // FIXME: protect this collect with ctrl-c
417        eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.into_value(call.head)
418    }
419
420    fn eval_external_call(
421        engine_state: &EngineState,
422        stack: &mut Stack,
423        head: &Expression,
424        args: &[ExternalArgument],
425        _: Span,
426    ) -> Result<Value, ShellError> {
427        let span = head.span(&engine_state);
428        // FIXME: protect this collect with ctrl-c
429        eval_external(engine_state, stack, head, args, PipelineData::empty())?.into_value(span)
430    }
431
432    fn eval_collect<D: DebugContext>(
433        engine_state: &EngineState,
434        stack: &mut Stack,
435        var_id: VarId,
436        expr: &Expression,
437    ) -> Result<Value, ShellError> {
438        // It's a little bizarre, but the expression can still have some kind of result even with
439        // nothing input
440        eval_collect::<D>(engine_state, stack, var_id, expr, PipelineData::empty())?
441            .into_value(expr.span)
442    }
443
444    fn eval_subexpression<D: DebugContext>(
445        engine_state: &EngineState,
446        stack: &mut Stack,
447        block_id: BlockId,
448        span: Span,
449    ) -> Result<Value, ShellError> {
450        let block = engine_state.get_block(block_id);
451        // FIXME: protect this collect with ctrl-c
452        eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?.into_value(span)
453    }
454
455    fn regex_match(
456        engine_state: &EngineState,
457        op_span: Span,
458        lhs: &Value,
459        rhs: &Value,
460        invert: bool,
461        expr_span: Span,
462    ) -> Result<Value, ShellError> {
463        lhs.regex_match(engine_state, op_span, rhs, invert, expr_span)
464    }
465
466    fn eval_assignment<D: DebugContext>(
467        engine_state: &EngineState,
468        stack: &mut Stack,
469        lhs: &Expression,
470        rhs: &Expression,
471        assignment: Assignment,
472        op_span: Span,
473        _expr_span: Span,
474    ) -> Result<Value, ShellError> {
475        let rhs = eval_expression::<D>(engine_state, stack, rhs)?;
476
477        let rhs = match assignment {
478            Assignment::Assign => rhs,
479            Assignment::AddAssign => {
480                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
481                lhs.add(op_span, &rhs, op_span)?
482            }
483            Assignment::SubtractAssign => {
484                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
485                lhs.sub(op_span, &rhs, op_span)?
486            }
487            Assignment::MultiplyAssign => {
488                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
489                lhs.mul(op_span, &rhs, op_span)?
490            }
491            Assignment::DivideAssign => {
492                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
493                lhs.div(op_span, &rhs, op_span)?
494            }
495            Assignment::ConcatenateAssign => {
496                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
497                lhs.concat(op_span, &rhs, op_span)?
498            }
499        };
500
501        match &lhs.expr {
502            Expr::Var(var_id) | Expr::VarDecl(var_id) => {
503                let var_info = engine_state.get_var(*var_id);
504                if var_info.mutable {
505                    stack.add_var(*var_id, rhs);
506                    Ok(Value::nothing(lhs.span(&engine_state)))
507                } else {
508                    Err(ShellError::AssignmentRequiresMutableVar {
509                        lhs_span: lhs.span(&engine_state),
510                    })
511                }
512            }
513            Expr::FullCellPath(cell_path) => {
514                match &cell_path.head.expr {
515                    Expr::Var(var_id) | Expr::VarDecl(var_id) => {
516                        // The $env variable is considered "mutable" in Nushell.
517                        // As such, give it special treatment here.
518                        let is_env = var_id == &ENV_VARIABLE_ID;
519                        if is_env || engine_state.get_var(*var_id).mutable {
520                            let mut lhs =
521                                eval_expression::<D>(engine_state, stack, &cell_path.head)?;
522                            if is_env {
523                                // Reject attempts to assign to the entire $env
524                                if cell_path.tail.is_empty() {
525                                    return Err(ShellError::CannotReplaceEnv {
526                                        span: cell_path.head.span(&engine_state),
527                                    });
528                                }
529
530                                // Updating environment variables should be case-preserving,
531                                // so we need to figure out the original key before we do anything.
532                                let (key, span) = match &cell_path.tail[0] {
533                                    PathMember::String { val, span, .. } => (val.to_string(), span),
534                                    PathMember::Int { val, span, .. } => (val.to_string(), span),
535                                };
536                                let original_key = if let Value::Record { val: record, .. } = &lhs {
537                                    record
538                                        .iter()
539                                        .rev()
540                                        .map(|(k, _)| k)
541                                        .find(|x| x.eq_ignore_case(&key))
542                                        .cloned()
543                                        .unwrap_or(key)
544                                } else {
545                                    key
546                                };
547
548                                // Retrieve the updated environment value.
549                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
550                                let value = lhs.follow_cell_path(&[{
551                                    let mut pm = cell_path.tail[0].clone();
552                                    pm.make_insensitive();
553                                    pm
554                                }])?;
555
556                                // Reject attempts to set automatic environment variables.
557                                if is_automatic_env_var(&original_key) {
558                                    return Err(ShellError::AutomaticEnvVarSetManually {
559                                        envvar_name: original_key,
560                                        span: *span,
561                                    });
562                                }
563
564                                let is_config = original_key == "config";
565
566                                stack.add_env_var(original_key, value.into_owned());
567
568                                // Trigger the update to config, if we modified that.
569                                if is_config {
570                                    stack.update_config(engine_state)?;
571                                }
572                            } else {
573                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
574                                stack.add_var(*var_id, lhs);
575                            }
576                            Ok(Value::nothing(cell_path.head.span(&engine_state)))
577                        } else {
578                            Err(ShellError::AssignmentRequiresMutableVar {
579                                lhs_span: lhs.span(&engine_state),
580                            })
581                        }
582                    }
583                    _ => Err(ShellError::AssignmentRequiresVar {
584                        lhs_span: lhs.span(&engine_state),
585                    }),
586                }
587            }
588            _ => Err(ShellError::AssignmentRequiresVar {
589                lhs_span: lhs.span(&engine_state),
590            }),
591        }
592    }
593
594    fn eval_row_condition_or_closure(
595        engine_state: &EngineState,
596        stack: &mut Stack,
597        block_id: BlockId,
598        span: Span,
599    ) -> Result<Value, ShellError> {
600        let captures = engine_state
601            .get_block(block_id)
602            .captures
603            .iter()
604            .map(|(id, span)| {
605                stack
606                    .get_var(*id, *span)
607                    .or_else(|_| {
608                        engine_state
609                            .get_var(*id)
610                            .const_val
611                            .clone()
612                            .ok_or(ShellError::VariableNotFoundAtRuntime { span: *span })
613                    })
614                    .map(|var| (*id, var))
615            })
616            .collect::<Result<_, _>>()?;
617
618        Ok(Value::closure(Closure { block_id, captures }, span))
619    }
620
621    fn eval_overlay(engine_state: &EngineState, span: Span) -> Result<Value, ShellError> {
622        let name = String::from_utf8_lossy(engine_state.get_span_contents(span)).to_string();
623
624        Ok(Value::string(name, span))
625    }
626
627    fn unreachable(engine_state: &EngineState, expr: &Expression) -> Result<Value, ShellError> {
628        Ok(Value::nothing(expr.span(&engine_state)))
629    }
630}
631
632/// Returns whether a string, when used as the name of an environment variable,
633/// is considered an automatic environment variable.
634///
635/// An automatic environment variable cannot be assigned to by user code.
636/// Current there are three of them: $env.PWD, $env.FILE_PWD, $env.CURRENT_FILE
637pub(crate) fn is_automatic_env_var(var: &str) -> bool {
638    let names = ["PWD", "FILE_PWD", "CURRENT_FILE"];
639    names.iter().any(|&name| {
640        if cfg!(windows) {
641            name.eq_ignore_case(var)
642        } else {
643            name.eq(var)
644        }
645    })
646}