Skip to main content

nu_protocol/
eval_const.rs

1//! Implementation of const-evaluation
2//!
3//! This enables you to assign `const`-constants and execute parse-time code dependent on this.
4//! e.g. `source $my_const`
5use crate::{
6    BlockId, Config, HistoryPath, IntoValue, PipelineData, Record, ShellError, Span, Value, VarId,
7    ast::{self, Assignment, Block, Call, Expr, Expression, ExternalArgument},
8    debugger::{DebugContext, WithoutDebug},
9    engine::{
10        Argument, Closure, CommandType, EngineState, Stack, StateWorkingSet,
11        named_flags::normalize_engine_arguments,
12    },
13    eval_base::Eval,
14    ir, record,
15    shell_error::generic::GenericError,
16};
17use nu_system::os_info::{get_kernel_version, get_os_arch, get_os_family, get_os_name};
18use std::{
19    path::{Path, PathBuf},
20    sync::Arc,
21};
22
23/// Create a Value for `$nu`.
24// Note: When adding new constants to $nu, please update the doc at https://nushell.sh/book/special_variables.html
25// or at least add a TODO/reminder issue in nushell.github.io so we don't lose track of it.
26pub(crate) fn create_nu_constant(engine_state: &EngineState, span: Span) -> Value {
27    fn canonicalize_path(engine_state: &EngineState, path: &Path) -> PathBuf {
28        let cwd = engine_state.cwd_as_string(None).unwrap_or_default();
29
30        if path.exists() {
31            match nu_path::canonicalize_with(path, cwd) {
32                Ok(canon_path) => canon_path,
33                Err(_) => path.to_owned(),
34            }
35        } else {
36            path.to_owned()
37        }
38    }
39
40    let mut record = Record::new();
41
42    let config_home = &engine_state.config_dirs.config_home;
43    let canon_config_home = canonicalize_path(engine_state, config_home);
44
45    record.push(
46        "default-config-dir",
47        Value::string(canon_config_home.to_string_lossy(), span),
48    );
49
50    record.push(
51        "config-path",
52        Value::string(
53            canonicalize_path(engine_state, engine_state.config_dirs.config_file.as_path())
54                .to_string_lossy(),
55            span,
56        ),
57    );
58
59    record.push(
60        "env-path",
61        Value::string(
62            canonicalize_path(engine_state, engine_state.config_dirs.env_file.as_path())
63                .to_string_lossy(),
64            span,
65        ),
66    );
67
68    record.push(
69        "history-path",
70        match &engine_state.config.history.path {
71            HistoryPath::Disabled => Value::string("", span),
72            HistoryPath::Custom(custom_path) => {
73                let effective_path = if custom_path.is_dir() {
74                    custom_path.join(engine_state.config.history.file_format.default_file_name())
75                } else {
76                    custom_path.clone()
77                };
78                let canon_hist_path = canonicalize_path(engine_state, &effective_path);
79                Value::string(canon_hist_path.to_string_lossy(), span)
80            }
81            HistoryPath::Default => {
82                // Use the same resolution path as history backends so `$nu.history-path`
83                // always matches the file reedline opens.
84                let hist_path = engine_state
85                    .config
86                    .history
87                    .file_path(config_home)
88                    .unwrap_or_else(|| {
89                        config_home
90                            .join(engine_state.config.history.file_format.default_file_name())
91                    });
92                let canon_hist_path = canonicalize_path(engine_state, &hist_path);
93                Value::string(canon_hist_path.to_string_lossy(), span)
94            }
95        },
96    );
97
98    record.push(
99        "loginshell-path",
100        Value::string(
101            canonicalize_path(engine_state, &config_home.join("login.nu")).to_string_lossy(),
102            span,
103        ),
104    );
105
106    #[cfg(feature = "plugin")]
107    {
108        // Prefer the live plugin_path (set once at startup from config_dirs).
109        let plugin_path = engine_state
110            .plugin_path
111            .as_deref()
112            .unwrap_or_else(|| engine_state.config_dirs.plugin_file.as_path());
113        record.push(
114            "plugin-path",
115            Value::string(
116                canonicalize_path(engine_state, plugin_path).to_string_lossy(),
117                span,
118            ),
119        );
120    }
121
122    let home_dir = &engine_state.config_dirs.home_dir;
123    record.push(
124        "home-dir",
125        if home_dir.as_os_str().is_empty() {
126            Value::error(
127                ShellError::Generic(GenericError::new(
128                    "setting $nu.home-dir failed",
129                    "Could not get home directory",
130                    span,
131                )),
132                span,
133            )
134        } else {
135            Value::string(
136                canonicalize_path(engine_state, home_dir).to_string_lossy(),
137                span,
138            )
139        },
140    );
141
142    record.push(
143        "data-dir",
144        Value::string(
145            canonicalize_path(engine_state, &engine_state.config_dirs.data_home).to_string_lossy(),
146            span,
147        ),
148    );
149
150    record.push(
151        "cache-dir",
152        Value::string(
153            canonicalize_path(engine_state, &engine_state.config_dirs.cache_home).to_string_lossy(),
154            span,
155        ),
156    );
157
158    record.push(
159        "vendor-autoload-dirs",
160        Value::list(
161            engine_state
162                .config_dirs
163                .vendor_autoload_dirs
164                .iter()
165                .map(|path| Value::string(path.to_string_lossy(), span))
166                .collect(),
167            span,
168        ),
169    );
170
171    record.push(
172        "user-autoload-dirs",
173        Value::list(
174            engine_state
175                .config_dirs
176                .user_autoload_dirs
177                .iter()
178                .map(|path| Value::string(path.to_string_lossy(), span))
179                .collect(),
180            span,
181        ),
182    );
183
184    record.push("temp-dir", {
185        let canon_temp_path = canonicalize_path(engine_state, &std::env::temp_dir());
186        Value::string(canon_temp_path.to_string_lossy(), span)
187    });
188
189    record.push("pid", Value::int(std::process::id().into(), span));
190
191    record.push("os-info", {
192        let ver = get_kernel_version();
193        Value::record(
194            record! {
195                "name" => Value::string(get_os_name(), span),
196                "arch" => Value::string(get_os_arch(), span),
197                "family" => Value::string(get_os_family(), span),
198                "kernel_version" => Value::string(ver, span),
199            },
200            span,
201        )
202    });
203
204    record.push("startup-time", engine_state.startup_time().into_value(span));
205
206    record.push(
207        "is-interactive",
208        Value::bool(engine_state.is_interactive, span),
209    );
210
211    record.push("is-login", Value::bool(engine_state.is_login, span));
212
213    record.push(
214        "history-enabled",
215        Value::bool(engine_state.history_enabled, span),
216    );
217
218    record.push(
219        "current-exe",
220        if let Ok(current_exe) = std::env::current_exe() {
221            Value::string(current_exe.to_string_lossy(), span)
222        } else {
223            Value::error(
224                ShellError::Generic(GenericError::new(
225                    "setting $nu.current-exe failed",
226                    "Could not get current executable path",
227                    span,
228                )),
229                span,
230            )
231        },
232    );
233
234    record.push("is-lsp", Value::bool(engine_state.is_lsp, span));
235    record.push("is-mcp", Value::bool(engine_state.is_mcp, span));
236    record.push("is-dap", Value::bool(engine_state.is_dap, span));
237
238    Value::record(record, span)
239}
240
241fn eval_const_call(
242    working_set: &StateWorkingSet,
243    call: &Call,
244    mut input: PipelineData,
245) -> Result<PipelineData, ShellError> {
246    let decl = working_set.get_decl(call.decl_id);
247
248    if !decl.is_const() {
249        return Err(ShellError::NotAConstCommand { span: call.head });
250    }
251
252    if !decl.is_known_external() && call.named_iter().any(|(flag, _, _)| flag.item == "help") {
253        // It would require re-implementing get_full_help() for const evaluation. Assuming that
254        // getting help messages at parse-time is rare enough, we can simply disallow it.
255        return Err(ShellError::NotAConstHelp { span: call.head });
256    }
257
258    // Keyword `if` needs AST branch structure; IR-shaped flat Values are not enough.
259    if decl.command_type() == CommandType::Keyword && decl.name() == "if" {
260        return eval_const_if(working_set, call, input);
261    }
262
263    // Keyword const: parse_const already set const_val; AST args include VarDecl (not a Value).
264    if decl.command_type() == CommandType::Keyword && decl.name() == "const" {
265        return Ok(PipelineData::empty());
266    }
267
268    // Make sure that iterating the value itself can be interrupted, as the IR
269    // evaluator does: `1..10000000000 | math sum`.
270    if let PipelineData::Value(value, ..) = &mut input {
271        value.inject_signals(working_set.permanent());
272    }
273    let mut stack = Stack::new();
274    let ir_call = build_const_ir_call(working_set, call, &decl.signature(), &mut stack)?;
275    let result = decl.run_const(working_set, &mut stack, &(&ir_call).into(), input);
276    ir_call.leave(&mut stack);
277    // A command stopped by an interrupt returns what it had so far, or an
278    // error about the input it didn't get.
279    working_set.permanent().signals().check(&call.head)?;
280    result
281}
282
283/// `data`, the output of a const command or block, as one value. A stream
284/// stops at an interrupt, and the check after collecting it keeps the part
285/// collected so far from being taken for the value: `const xs = 1..1000000000
286/// | math abs` interrupted is an error, not a short list.
287fn collect_const(
288    working_set: &StateWorkingSet,
289    data: PipelineData,
290    span: Span,
291) -> Result<Value, ShellError> {
292    let value = data.into_value(span)?;
293    working_set.permanent().signals().check(&span)?;
294    Ok(value)
295}
296
297/// Evaluate a single const-call argument expression to a [`Value`].
298///
299/// A positional declared as [`SyntaxShape::Block`](crate::SyntaxShape::Block) parses to
300/// [`Expr::Block`] and is materialized as a capture-free [`Closure`] so const commands can
301/// read its source text (e.g. `attr example`). Captures are not known during const
302/// evaluation (`block.captures` is filled at the end of parsing), so the closure must not be
303/// executed. Closures and row conditions are deliberately left to [`eval_constant`], which
304/// rejects them with `NotAConstant`; materializing them here would let e.g.
305/// `const c = (echo {|| $v })` parse and then fail at runtime with a missing capture.
306fn eval_const_call_arg(
307    working_set: &StateWorkingSet,
308    expr: &Expression,
309) -> Result<Value, ShellError> {
310    match &expr.expr {
311        Expr::Block(block_id) => Ok(Value::closure(
312            Closure {
313                block_id: *block_id,
314                captures: vec![],
315            },
316            expr.span,
317        )),
318        _ => eval_constant(working_set, expr),
319    }
320}
321
322fn build_const_ir_call(
323    working_set: &StateWorkingSet,
324    call: &Call,
325    signature: &crate::Signature,
326    stack: &mut Stack,
327) -> Result<ir::Call, ShellError> {
328    let mut builder = ir::Call::build(call.decl_id, call.head);
329
330    for arg in &call.arguments {
331        match arg {
332            ast::Argument::Positional(expr) | ast::Argument::Unknown(expr) => {
333                let val = eval_const_call_arg(working_set, expr)?;
334                builder.add_positional(stack, expr.span, val);
335            }
336            ast::Argument::Spread(expr) => {
337                let val = eval_const_call_arg(working_set, expr)?;
338                builder.add_spread(stack, expr.span, val);
339            }
340            ast::Argument::Named((long, short, maybe_expr)) => {
341                let short_name = short.as_ref().map(|s| s.item.as_str()).unwrap_or("");
342                if let Some(expr) = maybe_expr {
343                    let val = eval_const_call_arg(working_set, expr)?;
344                    builder.add_named(stack, &long.item, short_name, arg.span(), val);
345                } else {
346                    builder.add_flag(stack, &long.item, short_name, arg.span());
347                }
348            }
349        }
350    }
351
352    for (name, expr) in &call.parser_info {
353        let data: std::sync::Arc<[u8]> = name.as_bytes().into();
354        let name_slice = ir::DataSlice {
355            start: 0,
356            len: name.len().try_into().expect("parser info name too big"),
357        };
358        builder.add_argument(
359            stack,
360            Argument::ParserInfo {
361                data,
362                name: name_slice,
363                info: Box::new(expr.clone()),
364            },
365        );
366    }
367
368    let mut ir_call = builder.finish();
369    // Match runtime IR: expand record flag spreads and omit null named args that
370    // do not accept `nothing`.
371    let raw: Vec<Argument> = stack
372        .arguments
373        .drain_args(ir_call.args_base, ir_call.args_len)
374        .collect();
375    let expanded = normalize_engine_arguments(signature, raw)?;
376    ir_call.args_len = expanded.len();
377    for arg in expanded {
378        stack.arguments.push(arg);
379    }
380
381    Ok(ir_call)
382}
383
384/// Const evaluation of `if` using AST structure (not IR-shaped call args).
385fn eval_const_if(
386    working_set: &StateWorkingSet,
387    call: &Call,
388    input: PipelineData,
389) -> Result<PipelineData, ShellError> {
390    let mut iter = call.positional_iter();
391    let cond = iter.next().expect("checked through parser");
392    let then_expr = iter.next().expect("checked through parser");
393    let else_case = iter.next();
394
395    let then_block = then_expr
396        .as_block()
397        .ok_or_else(|| ShellError::TypeMismatch {
398            err_message: "expected block".into(),
399            span: then_expr.span,
400        })?;
401
402    // A non-bool condition is the same type mismatch as when `if` runs.
403    let condition = match eval_constant(working_set, cond)? {
404        Value::Bool { val, .. } => val,
405        other => {
406            return Err(ShellError::TypeMismatch {
407                err_message: "expected bool".into(),
408                span: other.span(),
409            });
410        }
411    };
412    if condition {
413        let block = working_set.get_block(then_block);
414        eval_const_subexpression(working_set, block, input, block.span.unwrap_or(call.head))
415    } else if let Some(else_case) = else_case {
416        if let Some(else_expr) = else_case.as_keyword() {
417            if let Some(block_id) = else_expr.as_block() {
418                let block = working_set.get_block(block_id);
419                eval_const_subexpression(working_set, block, input, block.span.unwrap_or(call.head))
420            } else {
421                eval_constant_with_input(working_set, else_expr, input)
422            }
423        } else {
424            eval_constant_with_input(working_set, else_case, input)
425        }
426    } else {
427        Ok(PipelineData::empty())
428    }
429}
430
431/// The output of `block`'s last pipeline, with `input` going to the first.
432///
433/// Between pipelines this does what a `;` does when the block runs: a
434/// stream is drained, raising an error it holds, a value is dropped, and the
435/// next pipeline starts with no input.
436pub fn eval_const_subexpression(
437    working_set: &StateWorkingSet,
438    block: &Block,
439    mut input: PipelineData,
440    span: Span,
441) -> Result<PipelineData, ShellError> {
442    for (index, pipeline) in block.pipelines.iter().enumerate() {
443        if index > 0 {
444            let previous = std::mem::replace(&mut input, PipelineData::empty());
445            if !matches!(previous, PipelineData::Value(..)) {
446                previous.drain()?;
447            }
448        }
449        for element in pipeline.elements.iter() {
450            if element.redirection.is_some() {
451                return Err(ShellError::NotAConstant { span });
452            }
453
454            input = eval_constant_with_input(working_set, &element.expr, input)?
455        }
456    }
457
458    Ok(input)
459}
460
461pub fn eval_constant_with_input(
462    working_set: &StateWorkingSet,
463    expr: &Expression,
464    input: PipelineData,
465) -> Result<PipelineData, ShellError> {
466    match &expr.expr {
467        Expr::Call(call) => eval_const_call(working_set, call, input),
468        Expr::Subexpression(block_id) => {
469            let block = working_set.get_block(*block_id);
470            eval_const_subexpression(working_set, block, input, expr.span(&working_set))
471        }
472        _ => eval_constant(working_set, expr).map(|v| PipelineData::value(v, None)),
473    }
474}
475
476/// Evaluate a constant value at parse time
477pub fn eval_constant(
478    working_set: &StateWorkingSet,
479    expr: &Expression,
480) -> Result<Value, ShellError> {
481    // TODO: Allow debugging const eval
482    <EvalConst as Eval>::eval::<WithoutDebug>(working_set, &mut (), expr)
483}
484
485struct EvalConst;
486
487impl Eval for EvalConst {
488    type State<'a> = &'a StateWorkingSet<'a>;
489
490    type MutState = ();
491
492    fn get_config(state: Self::State<'_>, _: &mut ()) -> Arc<Config> {
493        state.get_config().clone()
494    }
495
496    fn eval_var(
497        working_set: &StateWorkingSet,
498        _: &mut (),
499        var_id: VarId,
500        span: Span,
501    ) -> Result<Value, ShellError> {
502        match working_set.get_variable(var_id).const_val.as_ref() {
503            Some(val) => Ok(val.clone()),
504            None => Err(ShellError::NotAConstant { span }),
505        }
506    }
507
508    fn eval_call<D: DebugContext>(
509        working_set: &StateWorkingSet,
510        _: &mut (),
511        call: &Call,
512        span: Span,
513    ) -> Result<Value, ShellError> {
514        // TODO: Allow debugging const eval
515        // TODO: eval.rs uses call.head for the span rather than expr.span
516        let data = eval_const_call(working_set, call, PipelineData::empty())?;
517        collect_const(working_set, data, span)
518    }
519
520    fn eval_external_call(
521        _: &StateWorkingSet,
522        _: &mut (),
523        _: &Expression,
524        _: &[ExternalArgument],
525        span: Span,
526    ) -> Result<Value, ShellError> {
527        // TODO: It may be more helpful to give not_a_const_command error
528        Err(ShellError::NotAConstant { span })
529    }
530
531    fn eval_collect<D: DebugContext>(
532        _: &StateWorkingSet,
533        _: &mut (),
534        _var_id: VarId,
535        expr: &Expression,
536    ) -> Result<Value, ShellError> {
537        Err(ShellError::NotAConstant { span: expr.span })
538    }
539
540    fn eval_subexpression<D: DebugContext>(
541        working_set: &StateWorkingSet,
542        _: &mut (),
543        block_id: BlockId,
544        span: Span,
545    ) -> Result<Value, ShellError> {
546        // If parsing errors exist in the subexpression, don't bother to evaluate it.
547        if working_set
548            .parse_errors
549            .iter()
550            .any(|error| span.contains_span(error.span()))
551        {
552            return Err(ShellError::ParseErrorInConstant { span });
553        }
554        // TODO: Allow debugging const eval
555        let block = working_set.get_block(block_id);
556        let data = eval_const_subexpression(working_set, block, PipelineData::empty(), span)?;
557        collect_const(working_set, data, span)
558    }
559
560    fn regex_match(
561        _: &StateWorkingSet,
562        _op_span: Span,
563        _: &Value,
564        _: &Value,
565        _: bool,
566        expr_span: Span,
567    ) -> Result<Value, ShellError> {
568        Err(ShellError::NotAConstant { span: expr_span })
569    }
570
571    fn check_point_in_time(
572        _: &StateWorkingSet,
573        rhs: &Value,
574        expr_span: Span,
575    ) -> Result<(), ShellError> {
576        match rhs {
577            Value::Duration { .. } => Err(ShellError::NotAConstant { span: expr_span }),
578            _ => Ok(()),
579        }
580    }
581
582    fn eval_assignment<D: DebugContext>(
583        _: &StateWorkingSet,
584        _: &mut (),
585        _: &Expression,
586        _: &Expression,
587        _: Assignment,
588        _op_span: Span,
589        expr_span: Span,
590    ) -> Result<Value, ShellError> {
591        // TODO: Allow debugging const eval
592        Err(ShellError::NotAConstant { span: expr_span })
593    }
594
595    fn eval_row_condition_or_closure(
596        _: &StateWorkingSet,
597        _: &mut (),
598        _: BlockId,
599        span: Span,
600    ) -> Result<Value, ShellError> {
601        Err(ShellError::NotAConstant { span })
602    }
603
604    fn eval_overlay(_: &StateWorkingSet, span: Span) -> Result<Value, ShellError> {
605        Err(ShellError::NotAConstant { span })
606    }
607
608    fn unreachable(working_set: &StateWorkingSet, expr: &Expression) -> Result<Value, ShellError> {
609        Err(ShellError::NotAConstant {
610            span: expr.span(&working_set),
611        })
612    }
613}