nu_engine/
eval.rs

1use crate::eval_ir_block;
2#[allow(deprecated)]
3use crate::get_full_help;
4use nu_protocol::{
5    BlockId, Config, DataSource, ENV_VARIABLE_ID, IntoPipelineData, PipelineData, PipelineMetadata,
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
154        if block.redirect_env {
155            redirect_env(engine_state, caller_stack, &callee_stack);
156        }
157
158        result
159    } else {
160        // We pass caller_stack here with the knowledge that internal commands
161        // are going to be specifically looking for global state in the stack
162        // rather than any local state.
163        decl.run(engine_state, caller_stack, &call.into(), input)
164    }
165}
166
167/// Redirect the environment from callee to the caller.
168pub fn redirect_env(engine_state: &EngineState, caller_stack: &mut Stack, callee_stack: &Stack) {
169    // Grab all environment variables from the callee
170    let caller_env_vars = caller_stack.get_env_var_names(engine_state);
171
172    // remove env vars that are present in the caller but not in the callee
173    // (the callee hid them)
174    for var in caller_env_vars.iter() {
175        if !callee_stack.has_env_var(engine_state, var) {
176            caller_stack.remove_env_var(engine_state, var);
177        }
178    }
179
180    // add new env vars from callee to caller
181    for (var, value) in callee_stack.get_stack_env_vars() {
182        caller_stack.add_env_var(var, value);
183    }
184
185    // set config to callee config, to capture any updates to that
186    caller_stack.config.clone_from(&callee_stack.config);
187}
188
189fn eval_external(
190    engine_state: &EngineState,
191    stack: &mut Stack,
192    head: &Expression,
193    args: &[ExternalArgument],
194    input: PipelineData,
195) -> Result<PipelineData, ShellError> {
196    let decl_id = engine_state
197        .find_decl("run-external".as_bytes(), &[])
198        .ok_or(ShellError::ExternalNotSupported {
199            span: head.span(&engine_state),
200        })?;
201
202    let command = engine_state.get_decl(decl_id);
203
204    let mut call = Call::new(head.span(&engine_state));
205
206    call.add_positional(head.clone());
207
208    for arg in args {
209        match arg {
210            ExternalArgument::Regular(expr) => call.add_positional(expr.clone()),
211            ExternalArgument::Spread(expr) => call.add_spread(expr.clone()),
212        }
213    }
214
215    command.run(engine_state, stack, &(&call).into(), input)
216}
217
218pub fn eval_expression<D: DebugContext>(
219    engine_state: &EngineState,
220    stack: &mut Stack,
221    expr: &Expression,
222) -> Result<Value, ShellError> {
223    let stack = &mut stack.start_collect_value();
224    <EvalRuntime as Eval>::eval::<D>(engine_state, stack, expr)
225}
226
227/// Checks the expression to see if it's a internal or external call. If so, passes the input
228/// into the call and gets out the result
229/// Otherwise, invokes the expression
230///
231/// It returns PipelineData with a boolean flag, indicating if the external failed to run.
232/// The boolean flag **may only be true** for external calls, for internal calls, it always to be false.
233pub fn eval_expression_with_input<D: DebugContext>(
234    engine_state: &EngineState,
235    stack: &mut Stack,
236    expr: &Expression,
237    mut input: PipelineData,
238) -> Result<PipelineData, ShellError> {
239    match &expr.expr {
240        Expr::Call(call) => {
241            input = eval_call::<D>(engine_state, stack, call, input)?;
242        }
243        Expr::ExternalCall(head, args) => {
244            input = eval_external(engine_state, stack, head, args, input)?;
245        }
246
247        Expr::Collect(var_id, expr) => {
248            input = eval_collect::<D>(engine_state, stack, *var_id, expr, input)?;
249        }
250
251        Expr::Subexpression(block_id) => {
252            let block = engine_state.get_block(*block_id);
253            // FIXME: protect this collect with ctrl-c
254            input = eval_subexpression::<D>(engine_state, stack, block, input)?;
255        }
256
257        Expr::FullCellPath(full_cell_path) => match &full_cell_path.head {
258            Expression {
259                expr: Expr::Subexpression(block_id),
260                span,
261                ..
262            } => {
263                let block = engine_state.get_block(*block_id);
264
265                if !full_cell_path.tail.is_empty() {
266                    let stack = &mut stack.start_collect_value();
267                    // FIXME: protect this collect with ctrl-c
268                    input = eval_subexpression::<D>(engine_state, stack, block, input)?
269                        .into_value(*span)?
270                        .follow_cell_path(&full_cell_path.tail)?
271                        .into_owned()
272                        .into_pipeline_data()
273                } else {
274                    input = eval_subexpression::<D>(engine_state, stack, block, input)?;
275                }
276            }
277            _ => {
278                input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data();
279            }
280        },
281
282        _ => {
283            input = eval_expression::<D>(engine_state, stack, expr)?.into_pipeline_data();
284        }
285    };
286
287    Ok(input)
288}
289
290pub fn eval_block_with_early_return<D: DebugContext>(
291    engine_state: &EngineState,
292    stack: &mut Stack,
293    block: &Block,
294    input: PipelineData,
295) -> Result<PipelineData, ShellError> {
296    match eval_block::<D>(engine_state, stack, block, input) {
297        Err(ShellError::Return { span: _, value }) => Ok(PipelineData::value(*value, None)),
298        x => x,
299    }
300}
301
302pub fn eval_block<D: DebugContext>(
303    engine_state: &EngineState,
304    stack: &mut Stack,
305    block: &Block,
306    input: PipelineData,
307) -> Result<PipelineData, ShellError> {
308    let result = eval_ir_block::<D>(engine_state, stack, block, input);
309    if let Err(err) = &result {
310        stack.set_last_error(err);
311    }
312    result
313}
314
315pub fn eval_collect<D: DebugContext>(
316    engine_state: &EngineState,
317    stack: &mut Stack,
318    var_id: VarId,
319    expr: &Expression,
320    input: PipelineData,
321) -> Result<PipelineData, ShellError> {
322    // Evaluate the expression with the variable set to the collected input
323    let span = input.span().unwrap_or(Span::unknown());
324
325    let metadata = match input.metadata() {
326        // Remove the `FilePath` metadata, because after `collect` it's no longer necessary to
327        // check where some input came from.
328        Some(PipelineMetadata {
329            data_source: DataSource::FilePath(_),
330            content_type: None,
331        }) => None,
332        other => other,
333    };
334
335    let input = input.into_value(span)?;
336
337    stack.add_var(var_id, input.clone());
338
339    let result = eval_expression_with_input::<D>(
340        engine_state,
341        stack,
342        expr,
343        // We still have to pass it as input
344        input.into_pipeline_data_with_metadata(metadata),
345    );
346
347    stack.remove_var(var_id);
348
349    result
350}
351
352pub fn eval_subexpression<D: DebugContext>(
353    engine_state: &EngineState,
354    stack: &mut Stack,
355    block: &Block,
356    input: PipelineData,
357) -> Result<PipelineData, ShellError> {
358    eval_block::<D>(engine_state, stack, block, input)
359}
360
361pub fn eval_variable(
362    engine_state: &EngineState,
363    stack: &Stack,
364    var_id: VarId,
365    span: Span,
366) -> Result<Value, ShellError> {
367    match var_id {
368        // $nu
369        nu_protocol::NU_VARIABLE_ID => {
370            if let Some(val) = engine_state.get_constant(var_id) {
371                Ok(val.clone())
372            } else {
373                Err(ShellError::VariableNotFoundAtRuntime { span })
374            }
375        }
376        // $env
377        ENV_VARIABLE_ID => {
378            let env_vars = stack.get_env_vars(engine_state);
379            let env_columns = env_vars.keys();
380            let env_values = env_vars.values();
381
382            let mut pairs = env_columns
383                .map(|x| x.to_string())
384                .zip(env_values.cloned())
385                .collect::<Vec<(String, Value)>>();
386
387            pairs.sort_by(|a, b| a.0.cmp(&b.0));
388
389            Ok(Value::record(pairs.into_iter().collect(), span))
390        }
391        var_id => stack.get_var(var_id, span),
392    }
393}
394
395struct EvalRuntime;
396
397impl Eval for EvalRuntime {
398    type State<'a> = &'a EngineState;
399
400    type MutState = Stack;
401
402    fn get_config(engine_state: Self::State<'_>, stack: &mut Stack) -> Arc<Config> {
403        stack.get_config(engine_state)
404    }
405
406    fn eval_var(
407        engine_state: &EngineState,
408        stack: &mut Stack,
409        var_id: VarId,
410        span: Span,
411    ) -> Result<Value, ShellError> {
412        eval_variable(engine_state, stack, var_id, span)
413    }
414
415    fn eval_call<D: DebugContext>(
416        engine_state: &EngineState,
417        stack: &mut Stack,
418        call: &Call,
419        _: Span,
420    ) -> Result<Value, ShellError> {
421        // FIXME: protect this collect with ctrl-c
422        eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.into_value(call.head)
423    }
424
425    fn eval_external_call(
426        engine_state: &EngineState,
427        stack: &mut Stack,
428        head: &Expression,
429        args: &[ExternalArgument],
430        _: Span,
431    ) -> Result<Value, ShellError> {
432        let span = head.span(&engine_state);
433        // FIXME: protect this collect with ctrl-c
434        eval_external(engine_state, stack, head, args, PipelineData::empty())?.into_value(span)
435    }
436
437    fn eval_collect<D: DebugContext>(
438        engine_state: &EngineState,
439        stack: &mut Stack,
440        var_id: VarId,
441        expr: &Expression,
442    ) -> Result<Value, ShellError> {
443        // It's a little bizarre, but the expression can still have some kind of result even with
444        // nothing input
445        eval_collect::<D>(engine_state, stack, var_id, expr, PipelineData::empty())?
446            .into_value(expr.span)
447    }
448
449    fn eval_subexpression<D: DebugContext>(
450        engine_state: &EngineState,
451        stack: &mut Stack,
452        block_id: BlockId,
453        span: Span,
454    ) -> Result<Value, ShellError> {
455        let block = engine_state.get_block(block_id);
456        // FIXME: protect this collect with ctrl-c
457        eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?.into_value(span)
458    }
459
460    fn regex_match(
461        engine_state: &EngineState,
462        op_span: Span,
463        lhs: &Value,
464        rhs: &Value,
465        invert: bool,
466        expr_span: Span,
467    ) -> Result<Value, ShellError> {
468        lhs.regex_match(engine_state, op_span, rhs, invert, expr_span)
469    }
470
471    fn eval_assignment<D: DebugContext>(
472        engine_state: &EngineState,
473        stack: &mut Stack,
474        lhs: &Expression,
475        rhs: &Expression,
476        assignment: Assignment,
477        op_span: Span,
478        _expr_span: Span,
479    ) -> Result<Value, ShellError> {
480        let rhs = eval_expression::<D>(engine_state, stack, rhs)?;
481
482        let rhs = match assignment {
483            Assignment::Assign => rhs,
484            Assignment::AddAssign => {
485                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
486                lhs.add(op_span, &rhs, op_span)?
487            }
488            Assignment::SubtractAssign => {
489                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
490                lhs.sub(op_span, &rhs, op_span)?
491            }
492            Assignment::MultiplyAssign => {
493                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
494                lhs.mul(op_span, &rhs, op_span)?
495            }
496            Assignment::DivideAssign => {
497                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
498                lhs.div(op_span, &rhs, op_span)?
499            }
500            Assignment::ConcatenateAssign => {
501                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
502                lhs.concat(op_span, &rhs, op_span)?
503            }
504        };
505
506        match &lhs.expr {
507            Expr::Var(var_id) | Expr::VarDecl(var_id) => {
508                let var_info = engine_state.get_var(*var_id);
509                if var_info.mutable {
510                    stack.add_var(*var_id, rhs);
511                    Ok(Value::nothing(lhs.span(&engine_state)))
512                } else {
513                    Err(ShellError::AssignmentRequiresMutableVar {
514                        lhs_span: lhs.span(&engine_state),
515                    })
516                }
517            }
518            Expr::FullCellPath(cell_path) => {
519                match &cell_path.head.expr {
520                    Expr::Var(var_id) | Expr::VarDecl(var_id) => {
521                        // The $env variable is considered "mutable" in Nushell.
522                        // As such, give it special treatment here.
523                        let is_env = var_id == &ENV_VARIABLE_ID;
524                        if is_env || engine_state.get_var(*var_id).mutable {
525                            let mut lhs =
526                                eval_expression::<D>(engine_state, stack, &cell_path.head)?;
527                            if is_env {
528                                // Reject attempts to assign to the entire $env
529                                if cell_path.tail.is_empty() {
530                                    return Err(ShellError::CannotReplaceEnv {
531                                        span: cell_path.head.span(&engine_state),
532                                    });
533                                }
534
535                                // Updating environment variables should be case-preserving,
536                                // so we need to figure out the original key before we do anything.
537                                let (key, span) = match &cell_path.tail[0] {
538                                    PathMember::String { val, span, .. } => (val.to_string(), span),
539                                    PathMember::Int { val, span, .. } => (val.to_string(), span),
540                                };
541                                let original_key = if let Value::Record { val: record, .. } = &lhs {
542                                    record
543                                        .iter()
544                                        .rev()
545                                        .map(|(k, _)| k)
546                                        .find(|x| x.eq_ignore_case(&key))
547                                        .cloned()
548                                        .unwrap_or(key)
549                                } else {
550                                    key
551                                };
552
553                                // Retrieve the updated environment value.
554                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
555                                let value = lhs.follow_cell_path(&[{
556                                    let mut pm = cell_path.tail[0].clone();
557                                    pm.make_insensitive();
558                                    pm
559                                }])?;
560
561                                // Reject attempts to set automatic environment variables.
562                                if is_automatic_env_var(&original_key) {
563                                    return Err(ShellError::AutomaticEnvVarSetManually {
564                                        envvar_name: original_key,
565                                        span: *span,
566                                    });
567                                }
568
569                                let is_config = original_key == "config";
570
571                                stack.add_env_var(original_key, value.into_owned());
572
573                                // Trigger the update to config, if we modified that.
574                                if is_config {
575                                    stack.update_config(engine_state)?;
576                                }
577                            } else {
578                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
579                                stack.add_var(*var_id, lhs);
580                            }
581                            Ok(Value::nothing(cell_path.head.span(&engine_state)))
582                        } else {
583                            Err(ShellError::AssignmentRequiresMutableVar {
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            _ => Err(ShellError::AssignmentRequiresVar {
594                lhs_span: lhs.span(&engine_state),
595            }),
596        }
597    }
598
599    fn eval_row_condition_or_closure(
600        engine_state: &EngineState,
601        stack: &mut Stack,
602        block_id: BlockId,
603        span: Span,
604    ) -> Result<Value, ShellError> {
605        let captures = engine_state
606            .get_block(block_id)
607            .captures
608            .iter()
609            .map(|(id, span)| {
610                stack
611                    .get_var(*id, *span)
612                    .or_else(|_| {
613                        engine_state
614                            .get_var(*id)
615                            .const_val
616                            .clone()
617                            .ok_or(ShellError::VariableNotFoundAtRuntime { span: *span })
618                    })
619                    .map(|var| (*id, var))
620            })
621            .collect::<Result<_, _>>()?;
622
623        Ok(Value::closure(Closure { block_id, captures }, span))
624    }
625
626    fn eval_overlay(engine_state: &EngineState, span: Span) -> Result<Value, ShellError> {
627        let name = String::from_utf8_lossy(engine_state.get_span_contents(span)).to_string();
628
629        Ok(Value::string(name, span))
630    }
631
632    fn unreachable(engine_state: &EngineState, expr: &Expression) -> Result<Value, ShellError> {
633        Ok(Value::nothing(expr.span(&engine_state)))
634    }
635}
636
637/// Returns whether a string, when used as the name of an environment variable,
638/// is considered an automatic environment variable.
639///
640/// An automatic environment variable cannot be assigned to by user code.
641/// Current there are three of them: $env.PWD, $env.FILE_PWD, $env.CURRENT_FILE
642pub(crate) fn is_automatic_env_var(var: &str) -> bool {
643    let names = ["PWD", "FILE_PWD", "CURRENT_FILE"];
644    names.iter().any(|&name| {
645        if cfg!(windows) {
646            name.eq_ignore_case(var)
647        } else {
648            name.eq(var)
649        }
650    })
651}