mirror of
https://github.com/nushell/nushell.git
synced 2025-05-18 00:40:48 +02:00
# Description This PR adds an internal representation language to Nushell, offering an alternative evaluator based on simple instructions, stream-containing registers, and indexed control flow. The number of registers required is determined statically at compile-time, and the fixed size required is allocated upon entering the block. Each instruction is associated with a span, which makes going backwards from IR instructions to source code very easy. Motivations for IR: 1. **Performance.** By simplifying the evaluation path and making it more cache-friendly and branch predictor-friendly, code that does a lot of computation in Nushell itself can be sped up a decent bit. Because the IR is fairly easy to reason about, we can also implement optimization passes in the future to eliminate and simplify code. 2. **Correctness.** The instructions mostly have very simple and easily-specified behavior, so hopefully engine changes are a little bit easier to reason about, and they can be specified in a more formal way at some point. I have made an effort to document each of the instructions in the docs for the enum itself in a reasonably specific way. Some of the errors that would have happened during evaluation before are now moved to the compilation step instead, because they don't make sense to check during evaluation. 3. **As an intermediate target.** This is a good step for us to bring the [`new-nu-parser`](https://github.com/nushell/new-nu-parser) in at some point, as code generated from new AST can be directly compared to code generated from old AST. If the IR code is functionally equivalent, it will behave the exact same way. 4. **Debugging.** With a little bit more work, we can probably give control over advancing the virtual machine that `IrBlock`s run on to some sort of external driver, making things like breakpoints and single stepping possible. Tools like `view ir` and [`explore ir`](https://github.com/devyn/nu_plugin_explore_ir) make it easier than before to see what exactly is going on with your Nushell code. The goal is to eventually replace the AST evaluator entirely, once we're sure it's working just as well. You can help dogfood this by running Nushell with `$env.NU_USE_IR` set to some value. The environment variable is checked when Nushell starts, so config runs with IR, or it can also be set on a line at the REPL to change it dynamically. It is also checked when running `do` in case within a script you want to just run a specific piece of code with or without IR. # Example ```nushell view ir { |data| mut sum = 0 for n in $data { $sum += $n } $sum } ``` ```gas # 3 registers, 19 instructions, 0 bytes of data 0: load-literal %0, int(0) 1: store-variable var 904, %0 # let 2: drain %0 3: drop %0 4: load-variable %1, var 903 5: iterate %0, %1, end 15 # for, label(1), from(14:) 6: store-variable var 905, %0 7: load-variable %0, var 904 8: load-variable %2, var 905 9: binary-op %0, Math(Plus), %2 10: span %0 11: store-variable var 904, %0 12: load-literal %0, nothing 13: drain %0 14: jump 5 15: drop %0 # label(0), from(5:) 16: drain %0 17: load-variable %0, var 904 18: return %0 ``` # Benchmarks All benchmarks run on a base model Mac Mini M1. ## Iterative Fibonacci sequence This is about as best case as possible, making use of the much faster control flow. Most code will not experience a speed improvement nearly this large. ```nushell def fib [n: int] { mut a = 0 mut b = 1 for _ in 2..=$n { let c = $a + $b $a = $b $b = $c } $b } use std bench bench { 0..50 | each { |n| fib $n } } ``` IR disabled: ``` ╭───────┬─────────────────╮ │ mean │ 1ms 924µs 665ns │ │ min │ 1ms 700µs 83ns │ │ max │ 3ms 450µs 125ns │ │ std │ 395µs 759ns │ │ times │ [list 50 items] │ ╰───────┴─────────────────╯ ``` IR enabled: ``` ╭───────┬─────────────────╮ │ mean │ 452µs 820ns │ │ min │ 427µs 417ns │ │ max │ 540µs 167ns │ │ std │ 17µs 158ns │ │ times │ [list 50 items] │ ╰───────┴─────────────────╯ ```  ## [gradient_benchmark_no_check.nu](https://github.com/nushell/nu_scripts/blob/main/benchmarks/gradient_benchmark_no_check.nu) IR disabled: ``` ╭───┬──────────────────╮ │ 0 │ 27ms 929µs 958ns │ │ 1 │ 21ms 153µs 459ns │ │ 2 │ 18ms 639µs 666ns │ │ 3 │ 19ms 554µs 583ns │ │ 4 │ 13ms 383µs 375ns │ │ 5 │ 11ms 328µs 208ns │ │ 6 │ 5ms 659µs 542ns │ ╰───┴──────────────────╯ ``` IR enabled: ``` ╭───┬──────────────────╮ │ 0 │ 22ms 662µs │ │ 1 │ 17ms 221µs 792ns │ │ 2 │ 14ms 786µs 708ns │ │ 3 │ 13ms 876µs 834ns │ │ 4 │ 13ms 52µs 875ns │ │ 5 │ 11ms 269µs 666ns │ │ 6 │ 6ms 942µs 500ns │ ╰───┴──────────────────╯ ``` ## [random-bytes.nu](https://github.com/nushell/nu_scripts/blob/main/benchmarks/random-bytes.nu) I got pretty random results out of this benchmark so I decided not to include it. Not clear why. # User-Facing Changes - IR compilation errors may appear even if the user isn't evaluating with IR. - IR evaluation can be enabled by setting the `NU_USE_IR` environment variable to any value. - New command `view ir` pretty-prints the IR for a block, and `view ir --json` can be piped into an external tool like [`explore ir`](https://github.com/devyn/nu_plugin_explore_ir). # Tests + Formatting All tests are passing with `NU_USE_IR=1`, and I've added some more eval tests to compare the results for some very core operations. I will probably want to add some more so we don't have to always check `NU_USE_IR=1 toolkit test --workspace` on a regular basis. # After Submitting - [ ] release notes - [ ] further documentation of instructions? - [ ] post-release: publish `nu_plugin_explore_ir`
224 lines
7.6 KiB
Rust
224 lines
7.6 KiB
Rust
use crate::{
|
|
ast::{self, Expression},
|
|
ir, DeclId, FromValue, ShellError, Span, Value,
|
|
};
|
|
|
|
use super::{EngineState, Stack, StateWorkingSet};
|
|
|
|
/// This is a HACK to help [`Command`](super::Command) support both the old AST evaluator and the
|
|
/// new IR evaluator at the same time. It should be removed once we are satisfied with the new
|
|
/// evaluator.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Call<'a> {
|
|
pub head: Span,
|
|
pub decl_id: DeclId,
|
|
pub inner: CallImpl<'a>,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub enum CallImpl<'a> {
|
|
AstRef(&'a ast::Call),
|
|
AstBox(Box<ast::Call>),
|
|
IrRef(&'a ir::Call),
|
|
IrBox(Box<ir::Call>),
|
|
}
|
|
|
|
impl Call<'_> {
|
|
/// Returns a new AST call with the given span. This is often used by commands that need an
|
|
/// empty call to pass to a command. It's not easily possible to add anything to this.
|
|
pub fn new(span: Span) -> Self {
|
|
// this is using the boxed variant, which isn't so efficient... but this is only temporary
|
|
// anyway.
|
|
Call {
|
|
head: span,
|
|
decl_id: 0,
|
|
inner: CallImpl::AstBox(Box::new(ast::Call::new(span))),
|
|
}
|
|
}
|
|
|
|
/// Convert the `Call` from any lifetime into `'static`, by cloning the data within onto the
|
|
/// heap.
|
|
pub fn to_owned(&self) -> Call<'static> {
|
|
Call {
|
|
head: self.head,
|
|
decl_id: self.decl_id,
|
|
inner: self.inner.to_owned(),
|
|
}
|
|
}
|
|
|
|
/// Assert that the call is `ast::Call`, and fail with an error if it isn't.
|
|
///
|
|
/// Provided as a stop-gap for commands that can't work with `ir::Call`, or just haven't been
|
|
/// implemented yet. Eventually these issues should be resolved and then this can be removed.
|
|
pub fn assert_ast_call(&self) -> Result<&ast::Call, ShellError> {
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => Ok(call),
|
|
CallImpl::AstBox(call) => Ok(call),
|
|
_ => Err(ShellError::NushellFailedSpanned {
|
|
msg: "Can't be used in IR context".into(),
|
|
label: "this command is not yet supported by IR evaluation".into(),
|
|
span: self.head,
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// FIXME: implementation asserts `ast::Call` and proxies to that
|
|
pub fn has_flag_const(
|
|
&self,
|
|
working_set: &StateWorkingSet,
|
|
flag_name: &str,
|
|
) -> Result<bool, ShellError> {
|
|
self.assert_ast_call()?
|
|
.has_flag_const(working_set, flag_name)
|
|
}
|
|
|
|
/// FIXME: implementation asserts `ast::Call` and proxies to that
|
|
pub fn get_flag_const<T: FromValue>(
|
|
&self,
|
|
working_set: &StateWorkingSet,
|
|
name: &str,
|
|
) -> Result<Option<T>, ShellError> {
|
|
self.assert_ast_call()?.get_flag_const(working_set, name)
|
|
}
|
|
|
|
/// FIXME: implementation asserts `ast::Call` and proxies to that
|
|
pub fn req_const<T: FromValue>(
|
|
&self,
|
|
working_set: &StateWorkingSet,
|
|
pos: usize,
|
|
) -> Result<T, ShellError> {
|
|
self.assert_ast_call()?.req_const(working_set, pos)
|
|
}
|
|
|
|
/// FIXME: implementation asserts `ast::Call` and proxies to that
|
|
pub fn rest_const<T: FromValue>(
|
|
&self,
|
|
working_set: &StateWorkingSet,
|
|
starting_pos: usize,
|
|
) -> Result<Vec<T>, ShellError> {
|
|
self.assert_ast_call()?
|
|
.rest_const(working_set, starting_pos)
|
|
}
|
|
|
|
/// Returns a span covering the call's arguments.
|
|
pub fn arguments_span(&self) -> Span {
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => call.arguments_span(),
|
|
CallImpl::AstBox(call) => call.arguments_span(),
|
|
CallImpl::IrRef(call) => call.arguments_span(),
|
|
CallImpl::IrBox(call) => call.arguments_span(),
|
|
}
|
|
}
|
|
|
|
/// Returns a span covering the whole call.
|
|
pub fn span(&self) -> Span {
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => call.span(),
|
|
CallImpl::AstBox(call) => call.span(),
|
|
CallImpl::IrRef(call) => call.span(),
|
|
CallImpl::IrBox(call) => call.span(),
|
|
}
|
|
}
|
|
|
|
/// Get a parser info argument by name.
|
|
pub fn get_parser_info<'a>(&'a self, stack: &'a Stack, name: &str) -> Option<&'a Expression> {
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => call.get_parser_info(name),
|
|
CallImpl::AstBox(call) => call.get_parser_info(name),
|
|
CallImpl::IrRef(call) => call.get_parser_info(stack, name),
|
|
CallImpl::IrBox(call) => call.get_parser_info(stack, name),
|
|
}
|
|
}
|
|
|
|
/// Evaluator-agnostic implementation of `rest_iter_flattened()`. Evaluates or gets all of the
|
|
/// positional and spread arguments, flattens spreads, and then returns one list of values.
|
|
pub fn rest_iter_flattened(
|
|
&self,
|
|
engine_state: &EngineState,
|
|
stack: &mut Stack,
|
|
eval_expression: fn(
|
|
&EngineState,
|
|
&mut Stack,
|
|
&ast::Expression,
|
|
) -> Result<Value, ShellError>,
|
|
starting_pos: usize,
|
|
) -> Result<Vec<Value>, ShellError> {
|
|
fn by_ast(
|
|
call: &ast::Call,
|
|
engine_state: &EngineState,
|
|
stack: &mut Stack,
|
|
eval_expression: fn(
|
|
&EngineState,
|
|
&mut Stack,
|
|
&ast::Expression,
|
|
) -> Result<Value, ShellError>,
|
|
starting_pos: usize,
|
|
) -> Result<Vec<Value>, ShellError> {
|
|
call.rest_iter_flattened(starting_pos, |expr| {
|
|
eval_expression(engine_state, stack, expr)
|
|
})
|
|
}
|
|
|
|
fn by_ir(
|
|
call: &ir::Call,
|
|
stack: &Stack,
|
|
starting_pos: usize,
|
|
) -> Result<Vec<Value>, ShellError> {
|
|
call.rest_iter_flattened(stack, starting_pos)
|
|
}
|
|
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => {
|
|
by_ast(call, engine_state, stack, eval_expression, starting_pos)
|
|
}
|
|
CallImpl::AstBox(call) => {
|
|
by_ast(call, engine_state, stack, eval_expression, starting_pos)
|
|
}
|
|
CallImpl::IrRef(call) => by_ir(call, stack, starting_pos),
|
|
CallImpl::IrBox(call) => by_ir(call, stack, starting_pos),
|
|
}
|
|
}
|
|
|
|
/// Get the original AST expression for a positional argument. Does not usually work for IR
|
|
/// unless the decl specified `requires_ast_for_arguments()`
|
|
pub fn positional_nth<'a>(&'a self, stack: &'a Stack, index: usize) -> Option<&'a Expression> {
|
|
match &self.inner {
|
|
CallImpl::AstRef(call) => call.positional_nth(index),
|
|
CallImpl::AstBox(call) => call.positional_nth(index),
|
|
CallImpl::IrRef(call) => call.positional_ast(stack, index).map(|arc| arc.as_ref()),
|
|
CallImpl::IrBox(call) => call.positional_ast(stack, index).map(|arc| arc.as_ref()),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl CallImpl<'_> {
|
|
pub fn to_owned(&self) -> CallImpl<'static> {
|
|
match self {
|
|
CallImpl::AstRef(call) => CallImpl::AstBox(Box::new((*call).clone())),
|
|
CallImpl::AstBox(call) => CallImpl::AstBox(call.clone()),
|
|
CallImpl::IrRef(call) => CallImpl::IrBox(Box::new((*call).clone())),
|
|
CallImpl::IrBox(call) => CallImpl::IrBox(call.clone()),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> From<&'a ast::Call> for Call<'a> {
|
|
fn from(call: &'a ast::Call) -> Self {
|
|
Call {
|
|
head: call.head,
|
|
decl_id: call.decl_id,
|
|
inner: CallImpl::AstRef(call),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> From<&'a ir::Call> for Call<'a> {
|
|
fn from(call: &'a ir::Call) -> Self {
|
|
Call {
|
|
head: call.head,
|
|
decl_id: call.decl_id,
|
|
inner: CallImpl::IrRef(call),
|
|
}
|
|
}
|
|
}
|