nu_engine/
eval.rs

1use crate::eval_ir_block;
2#[allow(deprecated)]
3use crate::get_full_help;
4use nu_path::{expand_path_with, AbsolutePathBuf};
5use nu_protocol::{
6    ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument, PathMember},
7    debugger::DebugContext,
8    engine::{Closure, EngineState, Stack},
9    eval_base::Eval,
10    BlockId, Config, DataSource, IntoPipelineData, PipelineData, PipelineMetadata, ShellError,
11    Span, Value, VarId, ENV_VARIABLE_ID,
12};
13use nu_utils::IgnoreCaseExt;
14use std::sync::Arc;
15
16pub fn eval_call<D: DebugContext>(
17    engine_state: &EngineState,
18    caller_stack: &mut Stack,
19    call: &Call,
20    input: PipelineData,
21) -> Result<PipelineData, ShellError> {
22    engine_state.signals().check(call.head)?;
23    let decl = engine_state.get_decl(call.decl_id);
24
25    if !decl.is_known_external() && call.named_iter().any(|(flag, _, _)| flag.item == "help") {
26        let help = get_full_help(decl, engine_state, caller_stack);
27        Ok(Value::string(help, call.head).into_pipeline_data())
28    } else if let Some(block_id) = decl.block_id() {
29        let block = engine_state.get_block(block_id);
30
31        let mut callee_stack = caller_stack.gather_captures(engine_state, &block.captures);
32
33        // Rust does not check recursion limits outside of const evaluation.
34        // But nu programs run in the same process as the shell.
35        // To prevent a stack overflow in user code from crashing the shell,
36        // we limit the recursion depth of function calls.
37        // Picked 50 arbitrarily, should work on all architectures.
38        let maximum_call_stack_depth: u64 = engine_state.config.recursion_limit as u64;
39        callee_stack.recursion_count += 1;
40        if callee_stack.recursion_count > maximum_call_stack_depth {
41            callee_stack.recursion_count = 0;
42            return Err(ShellError::RecursionLimitReached {
43                recursion_limit: maximum_call_stack_depth,
44                span: block.span,
45            });
46        }
47
48        for (param_idx, (param, required)) in decl
49            .signature()
50            .required_positional
51            .iter()
52            .map(|p| (p, true))
53            .chain(
54                decl.signature()
55                    .optional_positional
56                    .iter()
57                    .map(|p| (p, false)),
58            )
59            .enumerate()
60        {
61            let var_id = param
62                .var_id
63                .expect("internal error: all custom parameters must have var_ids");
64
65            if let Some(arg) = call.positional_nth(param_idx) {
66                let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
67                let param_type = param.shape.to_type();
68                if required && !result.is_subtype_of(&param_type) {
69                    return Err(ShellError::CantConvert {
70                        to_type: param.shape.to_type().to_string(),
71                        from_type: result.get_type().to_string(),
72                        span: result.span(),
73                        help: None,
74                    });
75                }
76                callee_stack.add_var(var_id, result);
77            } else if let Some(value) = &param.default_value {
78                callee_stack.add_var(var_id, value.to_owned());
79            } else {
80                callee_stack.add_var(var_id, Value::nothing(call.head));
81            }
82        }
83
84        if let Some(rest_positional) = decl.signature().rest_positional {
85            let mut rest_items = vec![];
86
87            for result in call.rest_iter_flattened(
88                decl.signature().required_positional.len()
89                    + decl.signature().optional_positional.len(),
90                |expr| eval_expression::<D>(engine_state, caller_stack, expr),
91            )? {
92                rest_items.push(result);
93            }
94
95            let span = if let Some(rest_item) = rest_items.first() {
96                rest_item.span()
97            } else {
98                call.head
99            };
100
101            callee_stack.add_var(
102                rest_positional
103                    .var_id
104                    .expect("Internal error: rest positional parameter lacks var_id"),
105                Value::list(rest_items, span),
106            )
107        }
108
109        for named in decl.signature().named {
110            if let Some(var_id) = named.var_id {
111                let mut found = false;
112                for call_named in call.named_iter() {
113                    if let (Some(spanned), Some(short)) = (&call_named.1, named.short) {
114                        if spanned.item == short.to_string() {
115                            if let Some(arg) = &call_named.2 {
116                                let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
117
118                                callee_stack.add_var(var_id, result);
119                            } else if let Some(value) = &named.default_value {
120                                callee_stack.add_var(var_id, value.to_owned());
121                            } else {
122                                callee_stack.add_var(var_id, Value::bool(true, call.head))
123                            }
124                            found = true;
125                        }
126                    } else if call_named.0.item == named.long {
127                        if let Some(arg) = &call_named.2 {
128                            let result = eval_expression::<D>(engine_state, caller_stack, arg)?;
129
130                            callee_stack.add_var(var_id, result);
131                        } else if let Some(value) = &named.default_value {
132                            callee_stack.add_var(var_id, value.to_owned());
133                        } else {
134                            callee_stack.add_var(var_id, Value::bool(true, call.head))
135                        }
136                        found = true;
137                    }
138                }
139
140                if !found {
141                    if named.arg.is_none() {
142                        callee_stack.add_var(var_id, Value::bool(false, call.head))
143                    } else if let Some(value) = named.default_value {
144                        callee_stack.add_var(var_id, value);
145                    } else {
146                        callee_stack.add_var(var_id, Value::nothing(call.head))
147                    }
148                }
149            }
150        }
151
152        let result =
153            eval_block_with_early_return::<D>(engine_state, &mut callee_stack, block, input);
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, false)?
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_filepath(
407        engine_state: &EngineState,
408        stack: &mut Stack,
409        path: String,
410        quoted: bool,
411        span: Span,
412    ) -> Result<Value, ShellError> {
413        if quoted {
414            Ok(Value::string(path, span))
415        } else {
416            let cwd = engine_state.cwd(Some(stack))?;
417            let path = expand_path_with(path, cwd, true);
418
419            Ok(Value::string(path.to_string_lossy(), span))
420        }
421    }
422
423    fn eval_directory(
424        engine_state: Self::State<'_>,
425        stack: &mut Self::MutState,
426        path: String,
427        quoted: bool,
428        span: Span,
429    ) -> Result<Value, ShellError> {
430        if path == "-" {
431            Ok(Value::string("-", span))
432        } else if quoted {
433            Ok(Value::string(path, span))
434        } else {
435            let cwd = engine_state
436                .cwd(Some(stack))
437                .map(AbsolutePathBuf::into_std_path_buf)
438                .unwrap_or_default();
439            let path = expand_path_with(path, cwd, true);
440
441            Ok(Value::string(path.to_string_lossy(), span))
442        }
443    }
444
445    fn eval_var(
446        engine_state: &EngineState,
447        stack: &mut Stack,
448        var_id: VarId,
449        span: Span,
450    ) -> Result<Value, ShellError> {
451        eval_variable(engine_state, stack, var_id, span)
452    }
453
454    fn eval_call<D: DebugContext>(
455        engine_state: &EngineState,
456        stack: &mut Stack,
457        call: &Call,
458        _: Span,
459    ) -> Result<Value, ShellError> {
460        // FIXME: protect this collect with ctrl-c
461        eval_call::<D>(engine_state, stack, call, PipelineData::empty())?.into_value(call.head)
462    }
463
464    fn eval_external_call(
465        engine_state: &EngineState,
466        stack: &mut Stack,
467        head: &Expression,
468        args: &[ExternalArgument],
469        _: Span,
470    ) -> Result<Value, ShellError> {
471        let span = head.span(&engine_state);
472        // FIXME: protect this collect with ctrl-c
473        eval_external(engine_state, stack, head, args, PipelineData::empty())?.into_value(span)
474    }
475
476    fn eval_collect<D: DebugContext>(
477        engine_state: &EngineState,
478        stack: &mut Stack,
479        var_id: VarId,
480        expr: &Expression,
481    ) -> Result<Value, ShellError> {
482        // It's a little bizarre, but the expression can still have some kind of result even with
483        // nothing input
484        eval_collect::<D>(engine_state, stack, var_id, expr, PipelineData::empty())?
485            .into_value(expr.span)
486    }
487
488    fn eval_subexpression<D: DebugContext>(
489        engine_state: &EngineState,
490        stack: &mut Stack,
491        block_id: BlockId,
492        span: Span,
493    ) -> Result<Value, ShellError> {
494        let block = engine_state.get_block(block_id);
495        // FIXME: protect this collect with ctrl-c
496        eval_subexpression::<D>(engine_state, stack, block, PipelineData::empty())?.into_value(span)
497    }
498
499    fn regex_match(
500        engine_state: &EngineState,
501        op_span: Span,
502        lhs: &Value,
503        rhs: &Value,
504        invert: bool,
505        expr_span: Span,
506    ) -> Result<Value, ShellError> {
507        lhs.regex_match(engine_state, op_span, rhs, invert, expr_span)
508    }
509
510    fn eval_assignment<D: DebugContext>(
511        engine_state: &EngineState,
512        stack: &mut Stack,
513        lhs: &Expression,
514        rhs: &Expression,
515        assignment: Assignment,
516        op_span: Span,
517        _expr_span: Span,
518    ) -> Result<Value, ShellError> {
519        let rhs = eval_expression::<D>(engine_state, stack, rhs)?;
520
521        let rhs = match assignment {
522            Assignment::Assign => rhs,
523            Assignment::AddAssign => {
524                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
525                lhs.add(op_span, &rhs, op_span)?
526            }
527            Assignment::SubtractAssign => {
528                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
529                lhs.sub(op_span, &rhs, op_span)?
530            }
531            Assignment::MultiplyAssign => {
532                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
533                lhs.mul(op_span, &rhs, op_span)?
534            }
535            Assignment::DivideAssign => {
536                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
537                lhs.div(op_span, &rhs, op_span)?
538            }
539            Assignment::ConcatenateAssign => {
540                let lhs = eval_expression::<D>(engine_state, stack, lhs)?;
541                lhs.concat(op_span, &rhs, op_span)?
542            }
543        };
544
545        match &lhs.expr {
546            Expr::Var(var_id) | Expr::VarDecl(var_id) => {
547                let var_info = engine_state.get_var(*var_id);
548                if var_info.mutable {
549                    stack.add_var(*var_id, rhs);
550                    Ok(Value::nothing(lhs.span(&engine_state)))
551                } else {
552                    Err(ShellError::AssignmentRequiresMutableVar {
553                        lhs_span: lhs.span(&engine_state),
554                    })
555                }
556            }
557            Expr::FullCellPath(cell_path) => {
558                match &cell_path.head.expr {
559                    Expr::Var(var_id) | Expr::VarDecl(var_id) => {
560                        // The $env variable is considered "mutable" in Nushell.
561                        // As such, give it special treatment here.
562                        let is_env = var_id == &ENV_VARIABLE_ID;
563                        if is_env || engine_state.get_var(*var_id).mutable {
564                            let mut lhs =
565                                eval_expression::<D>(engine_state, stack, &cell_path.head)?;
566                            if is_env {
567                                // Reject attempts to assign to the entire $env
568                                if cell_path.tail.is_empty() {
569                                    return Err(ShellError::CannotReplaceEnv {
570                                        span: cell_path.head.span(&engine_state),
571                                    });
572                                }
573
574                                // Updating environment variables should be case-preserving,
575                                // so we need to figure out the original key before we do anything.
576                                let (key, span) = match &cell_path.tail[0] {
577                                    PathMember::String { val, span, .. } => (val.to_string(), span),
578                                    PathMember::Int { val, span, .. } => (val.to_string(), span),
579                                };
580                                let original_key = if let Value::Record { val: record, .. } = &lhs {
581                                    record
582                                        .iter()
583                                        .rev()
584                                        .map(|(k, _)| k)
585                                        .find(|x| x.eq_ignore_case(&key))
586                                        .cloned()
587                                        .unwrap_or(key)
588                                } else {
589                                    key
590                                };
591
592                                // Retrieve the updated environment value.
593                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
594                                let value =
595                                    lhs.follow_cell_path(&[cell_path.tail[0].clone()], true)?;
596
597                                // Reject attempts to set automatic environment variables.
598                                if is_automatic_env_var(&original_key) {
599                                    return Err(ShellError::AutomaticEnvVarSetManually {
600                                        envvar_name: original_key,
601                                        span: *span,
602                                    });
603                                }
604
605                                let is_config = original_key == "config";
606
607                                stack.add_env_var(original_key, value);
608
609                                // Trigger the update to config, if we modified that.
610                                if is_config {
611                                    stack.update_config(engine_state)?;
612                                }
613                            } else {
614                                lhs.upsert_data_at_cell_path(&cell_path.tail, rhs)?;
615                                stack.add_var(*var_id, lhs);
616                            }
617                            Ok(Value::nothing(cell_path.head.span(&engine_state)))
618                        } else {
619                            Err(ShellError::AssignmentRequiresMutableVar {
620                                lhs_span: lhs.span(&engine_state),
621                            })
622                        }
623                    }
624                    _ => Err(ShellError::AssignmentRequiresVar {
625                        lhs_span: lhs.span(&engine_state),
626                    }),
627                }
628            }
629            _ => Err(ShellError::AssignmentRequiresVar {
630                lhs_span: lhs.span(&engine_state),
631            }),
632        }
633    }
634
635    fn eval_row_condition_or_closure(
636        engine_state: &EngineState,
637        stack: &mut Stack,
638        block_id: BlockId,
639        span: Span,
640    ) -> Result<Value, ShellError> {
641        let captures = engine_state
642            .get_block(block_id)
643            .captures
644            .iter()
645            .map(|&id| {
646                stack
647                    .get_var(id, span)
648                    .or_else(|_| {
649                        engine_state
650                            .get_var(id)
651                            .const_val
652                            .clone()
653                            .ok_or(ShellError::VariableNotFoundAtRuntime { span })
654                    })
655                    .map(|var| (id, var))
656            })
657            .collect::<Result<_, _>>()?;
658
659        Ok(Value::closure(Closure { block_id, captures }, span))
660    }
661
662    fn eval_overlay(engine_state: &EngineState, span: Span) -> Result<Value, ShellError> {
663        let name = String::from_utf8_lossy(engine_state.get_span_contents(span)).to_string();
664
665        Ok(Value::string(name, span))
666    }
667
668    fn unreachable(engine_state: &EngineState, expr: &Expression) -> Result<Value, ShellError> {
669        Ok(Value::nothing(expr.span(&engine_state)))
670    }
671}
672
673/// Returns whether a string, when used as the name of an environment variable,
674/// is considered an automatic environment variable.
675///
676/// An automatic environment variable cannot be assigned to by user code.
677/// Current there are three of them: $env.PWD, $env.FILE_PWD, $env.CURRENT_FILE
678pub(crate) fn is_automatic_env_var(var: &str) -> bool {
679    let names = ["PWD", "FILE_PWD", "CURRENT_FILE"];
680    names.iter().any(|&name| {
681        if cfg!(windows) {
682            name.eq_ignore_case(var)
683        } else {
684            name.eq(var)
685        }
686    })
687}