Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
use nu_test_support::{nu, playground::Playground};
|
|
|
|
use regex::Regex;
|
2023-04-01 20:09:33 +02:00
|
|
|
|
|
|
|
#[test]
|
Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
fn record_with_redefined_key() {
|
2023-07-12 19:07:20 +02:00
|
|
|
let actual = nu!("{x: 1, x: 2}");
|
2023-04-01 20:09:33 +02:00
|
|
|
|
|
|
|
assert!(actual.err.contains("redefined"));
|
|
|
|
}
|
2023-09-05 14:36:37 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn run_file_parse_error() {
|
|
|
|
let actual = nu!(
|
|
|
|
cwd: "tests/fixtures/eval",
|
|
|
|
"nu script.nu"
|
|
|
|
);
|
|
|
|
|
|
|
|
assert!(actual.err.contains("unknown type"));
|
|
|
|
}
|
Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
|
|
|
|
enum ExpectedOut<'a> {
|
|
|
|
/// Equals a string exactly
|
|
|
|
Eq(&'a str),
|
|
|
|
/// Matches a regex
|
|
|
|
Matches(&'a str),
|
|
|
|
/// Produces an error (match regex)
|
|
|
|
Error(&'a str),
|
|
|
|
/// Drops a file that contains these contents
|
|
|
|
FileEq(&'a str, &'a str),
|
|
|
|
}
|
|
|
|
use self::ExpectedOut::*;
|
|
|
|
|
|
|
|
fn test_eval(source: &str, expected_out: ExpectedOut) {
|
2024-11-15 05:09:25 +01:00
|
|
|
Playground::setup("test_eval", |dirs, _playground| {
|
|
|
|
let actual = nu!(
|
|
|
|
cwd: dirs.test(),
|
|
|
|
source,
|
|
|
|
);
|
|
|
|
|
|
|
|
match expected_out {
|
|
|
|
Eq(eq) => {
|
|
|
|
assert_eq!(actual.out, eq);
|
|
|
|
assert!(actual.status.success());
|
Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
}
|
2024-11-15 05:09:25 +01:00
|
|
|
Matches(regex) => {
|
|
|
|
let compiled_regex = Regex::new(regex).expect("regex failed to compile");
|
|
|
|
assert!(
|
|
|
|
compiled_regex.is_match(&actual.out),
|
|
|
|
"eval out does not match: {}\n{}",
|
|
|
|
regex,
|
|
|
|
actual.out,
|
|
|
|
);
|
|
|
|
assert!(actual.status.success());
|
|
|
|
}
|
|
|
|
Error(regex) => {
|
|
|
|
let compiled_regex = Regex::new(regex).expect("regex failed to compile");
|
|
|
|
assert!(
|
|
|
|
compiled_regex.is_match(&actual.err),
|
|
|
|
"eval err does not match: {}",
|
|
|
|
regex
|
|
|
|
);
|
|
|
|
assert!(!actual.status.success());
|
|
|
|
}
|
|
|
|
FileEq(path, contents) => {
|
|
|
|
let read_contents =
|
|
|
|
std::fs::read_to_string(dirs.test().join(path)).expect("failed to read file");
|
|
|
|
assert_eq!(read_contents.trim(), contents);
|
|
|
|
assert!(actual.status.success());
|
|
|
|
}
|
|
|
|
}
|
Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_bool() {
|
|
|
|
test_eval("true", Eq("true"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_int() {
|
|
|
|
test_eval("1", Eq("1"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_float() {
|
|
|
|
test_eval("1.5", Eq("1.5"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_filesize() {
|
|
|
|
test_eval("30MiB", Eq("30.0 MiB"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_duration() {
|
|
|
|
test_eval("30ms", Eq("30ms"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_binary() {
|
|
|
|
test_eval("0x[1f 2f f0]", Matches("Length.*1f.*2f.*f0"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_closure() {
|
|
|
|
test_eval("{||}", Matches("<Closure"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_range() {
|
|
|
|
test_eval("0..2..10", Matches("10"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_list() {
|
|
|
|
test_eval("[foo bar baz]", Matches("foo.*bar.*baz"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_record() {
|
|
|
|
test_eval("{foo: bar, baz: quux}", Matches("foo.*bar.*baz.*quux"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_table() {
|
|
|
|
test_eval("[[a b]; [1 2] [3 4]]", Matches("a.*b.*1.*2.*3.*4"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_string() {
|
|
|
|
test_eval(r#""foobar""#, Eq("foobar"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_raw_string() {
|
|
|
|
test_eval(r#"r#'bazquux'#"#, Eq("bazquux"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_date() {
|
|
|
|
test_eval("2020-01-01T00:00:00Z", Matches("2020"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn literal_nothing() {
|
|
|
|
test_eval("null", Eq(""))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn list_spread() {
|
|
|
|
test_eval("[foo bar ...[baz quux]] | length", Eq("4"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn record_spread() {
|
|
|
|
test_eval("{foo: bar ...{baz: quux}} | columns | length", Eq("2"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn binary_op_example() {
|
|
|
|
test_eval(
|
|
|
|
"(([1 2] ++ [3 4]) == [1 2 3 4]) and (([1 2 3] ++ 4) == ([1] ++ [2 3 4]))",
|
|
|
|
Eq("true"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn range_from_expressions() {
|
|
|
|
test_eval("(1 + 1)..(2 + 2)", Matches("2.*3.*4"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn list_from_expressions() {
|
|
|
|
test_eval(
|
|
|
|
"[('foo' | str upcase) ('BAR' | str downcase)]",
|
|
|
|
Matches("FOO.*bar"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn record_from_expressions() {
|
|
|
|
test_eval("{('foo' | str upcase): 42}", Matches("FOO.*42"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn call_spread() {
|
|
|
|
test_eval(
|
|
|
|
"echo foo bar ...[baz quux nushell]",
|
|
|
|
Matches("foo.*bar.*baz.*quux.*nushell"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn call_flag() {
|
|
|
|
test_eval("print -e message", Eq("")) // should not be visible on stdout
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn call_named() {
|
|
|
|
test_eval("10.123 | into string --decimals 1", Eq("10.1"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn external_call() {
|
|
|
|
test_eval("nu --testbin cococo foo=bar baz", Eq("foo=bar baz"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn external_call_redirect_pipe() {
|
|
|
|
test_eval(
|
|
|
|
"nu --testbin cococo foo=bar baz | str upcase",
|
|
|
|
Eq("FOO=BAR BAZ"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn external_call_redirect_capture() {
|
|
|
|
test_eval(
|
|
|
|
"echo (nu --testbin cococo foo=bar baz) | str upcase",
|
|
|
|
Eq("FOO=BAR BAZ"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn external_call_redirect_file() {
|
|
|
|
test_eval(
|
|
|
|
"nu --testbin cococo hello out> hello.txt",
|
|
|
|
FileEq("hello.txt", "hello"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn let_variable() {
|
|
|
|
test_eval("let foo = 'test'; print $foo", Eq("test"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn let_variable_mutate_error() {
|
|
|
|
test_eval(
|
|
|
|
"let foo = 'test'; $foo = 'bar'; print $foo",
|
|
|
|
Error("immutable"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn constant() {
|
|
|
|
test_eval("const foo = 1 + 2; print $foo", Eq("3"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn constant_assign_error() {
|
|
|
|
test_eval(
|
|
|
|
"const foo = 1 + 2; $foo = 4; print $foo",
|
|
|
|
Error("immutable"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn mut_variable() {
|
|
|
|
test_eval("mut foo = 'test'; $foo = 'bar'; print $foo", Eq("bar"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn mut_variable_append_assign() {
|
|
|
|
test_eval(
|
|
|
|
"mut foo = 'test'; $foo ++= 'bar'; print $foo",
|
|
|
|
Eq("testbar"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn bind_in_variable_to_input() {
|
|
|
|
test_eval("3 | (4 + $in)", Eq("7"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn if_true() {
|
|
|
|
test_eval("if true { 'foo' }", Eq("foo"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn if_false() {
|
|
|
|
test_eval("if false { 'foo' } | describe", Eq("nothing"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn if_else_true() {
|
|
|
|
test_eval("if 5 > 3 { 'foo' } else { 'bar' }", Eq("foo"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn if_else_false() {
|
|
|
|
test_eval("if 5 < 3 { 'foo' } else { 'bar' }", Eq("bar"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_empty_fallthrough() {
|
|
|
|
test_eval("match 42 { }; 'pass'", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_value() {
|
|
|
|
test_eval("match 1 { 1 => 'pass', 2 => 'fail' }", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_value_default() {
|
|
|
|
test_eval(
|
|
|
|
"match 3 { 1 => 'fail1', 2 => 'fail2', _ => 'pass' }",
|
|
|
|
Eq("pass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_value_fallthrough() {
|
|
|
|
test_eval("match 3 { 1 => 'fail1', 2 => 'fail2' }", Eq(""))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_variable() {
|
|
|
|
test_eval(
|
|
|
|
"match 'pass' { $s => { print $s }, _ => { print 'fail' } }",
|
|
|
|
Eq("pass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_variable_in_list() {
|
|
|
|
test_eval("match [fail pass] { [$f, $p] => { print $p } }", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn match_passthrough_input() {
|
|
|
|
test_eval(
|
|
|
|
"'yes' | match [pass fail] { [$p, ..] => (collect { |y| $y ++ $p }) }",
|
|
|
|
Eq("yespass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn while_mutate_var() {
|
|
|
|
test_eval("mut x = 2; while $x > 0 { print $x; $x -= 1 }", Eq("21"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn for_list() {
|
|
|
|
test_eval("for v in [1 2 3] { print ($v * 2) }", Eq(r"246"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn for_seq() {
|
|
|
|
test_eval("for v in (seq 1 4) { print ($v * 2) }", Eq("2468"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn early_return() {
|
|
|
|
test_eval("do { return 'foo'; 'bar' }", Eq("foo"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn early_return_from_if() {
|
|
|
|
test_eval("do { if true { return 'pass' }; 'fail' }", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn early_return_from_loop() {
|
|
|
|
test_eval("do { loop { return 'pass' } }", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn early_return_from_while() {
|
|
|
|
test_eval(
|
|
|
|
"do { let x = true; while $x { return 'pass' } }",
|
|
|
|
Eq("pass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn early_return_from_for() {
|
|
|
|
test_eval("do { for x in [pass fail] { return $x } }", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn try_no_catch() {
|
|
|
|
test_eval("try { error make { msg: foo } }; 'pass'", Eq("pass"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn try_catch_no_var() {
|
|
|
|
test_eval(
|
|
|
|
"try { error make { msg: foo } } catch { 'pass' }",
|
|
|
|
Eq("pass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn try_catch_var() {
|
|
|
|
test_eval(
|
|
|
|
"try { error make { msg: foo } } catch { |err| $err.msg }",
|
|
|
|
Eq("foo"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn try_catch_with_non_literal_closure_no_var() {
|
|
|
|
test_eval(
|
|
|
|
r#"
|
|
|
|
let error_handler = { || "pass" }
|
|
|
|
try { error make { msg: foobar } } catch $error_handler
|
|
|
|
"#,
|
|
|
|
Eq("pass"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn try_catch_with_non_literal_closure() {
|
|
|
|
test_eval(
|
|
|
|
r#"
|
|
|
|
let error_handler = { |err| $err.msg }
|
|
|
|
try { error make { msg: foobar } } catch $error_handler
|
|
|
|
"#,
|
|
|
|
Eq("foobar"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-09-13 09:07:22 +02:00
|
|
|
#[test]
|
|
|
|
fn try_catch_external() {
|
|
|
|
test_eval(
|
|
|
|
r#"try { nu -c 'exit 1' } catch { $env.LAST_EXIT_CODE }"#,
|
|
|
|
Eq("1"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
Internal representation (IR) compiler and evaluator (#13330)
# 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] │
╰───────┴─────────────────╯
```
![explore ir
view](https://github.com/nushell/nushell/assets/10729/d7bccc03-5222-461c-9200-0dce71b83b83)
##
[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`
2024-07-11 02:33:59 +02:00
|
|
|
#[test]
|
|
|
|
fn row_condition() {
|
|
|
|
test_eval(
|
|
|
|
"[[a b]; [1 2] [3 4]] | where a < 3 | to nuon",
|
|
|
|
Eq("[[a, b]; [1, 2]]"),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn custom_command() {
|
|
|
|
test_eval(
|
|
|
|
r#"
|
|
|
|
def cmd [a: int, b: string = 'fail', ...c: string, --x: int] { $"($a)($b)($c)($x)" }
|
|
|
|
cmd 42 pass foo --x 30
|
|
|
|
"#,
|
|
|
|
Eq("42pass[foo]30"),
|
|
|
|
)
|
|
|
|
}
|