Debugger experiments (#11441)

<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

This PR adds a new evaluator path with callbacks to a mutable trait
object implementing a Debugger trait. The trait object can do anything,
e.g., profiling, code coverage, step debugging. Currently,
entering/leaving a block and a pipeline element is marked with
callbacks, but more callbacks can be added as necessary. Not all
callbacks need to be used by all debuggers; unused ones are simply empty
calls. A simple profiler is implemented as a proof of concept.

The debugging support is implementing by making `eval_xxx()` functions
generic depending on whether we're debugging or not. This has zero
computational overhead, but makes the binary slightly larger (see
benchmarks below). `eval_xxx()` variants called from commands (like
`eval_block_with_early_return()` in `each`) are chosen with a dynamic
dispatch for two reasons: to not grow the binary size due to duplicating
the code of many commands, and for the fact that it isn't possible
because it would make Command trait objects object-unsafe.

In the future, I hope it will be possible to allow plugin callbacks such
that users would be able to implement their profiler plugins instead of
having to recompile Nushell.
[DAP](https://microsoft.github.io/debug-adapter-protocol/) would also be
interesting to explore.

Try `help debug profile`.

## Screenshots

Basic output:

![profiler_new](https://github.com/nushell/nushell/assets/25571562/418b9df0-b659-4dcb-b023-2d5fcef2c865)

To profile with more granularity, increase the profiler depth (you'll
see that repeated `is-windows` calls take a large chunk of total time,
making it a good candidate for optimizing):

![profiler_new_m3](https://github.com/nushell/nushell/assets/25571562/636d756d-5d56-460c-a372-14716f65f37f)

## Benchmarks

### Binary size

Binary size increase vs. main: **+40360 bytes**. _(Both built with
`--release --features=extra,dataframe`.)_

### Time

```nushell
# bench_debug.nu
use std bench

let test = {
    1..100
    | each {
        ls | each {|row| $row.name | str length }
    }
    | flatten
    | math avg
}

print 'debug:'
let res2 = bench { debug profile $test } --pretty
print $res2
```

```nushell
# bench_nodebug.nu
use std bench

let test = {
    1..100
    | each {
        ls | each {|row| $row.name | str length }
    }
    | flatten
    | math avg
}

print 'no debug:'
let res1 = bench { do $test } --pretty
print $res1
```

`cargo run --release -- bench_debug.nu` is consistently 1--2 ms slower
than `cargo run --release -- bench_nodebug.nu` due to the collection
overhead + gathering the report. This is expected. When gathering more
stuff, the overhead is obviously higher.

`cargo run --release -- bench_nodebug.nu` vs. `nu bench_nodebug.nu` I
didn't measure any difference. Both benchmarks report times between 97
and 103 ms randomly, without one being consistently higher than the
other. This suggests that at least in this particular case, when not
running any debugger, there is no runtime overhead.

## API changes

This PR adds a generic parameter to all `eval_xxx` functions that forces
you to specify whether you use the debugger. You can resolve it in two
ways:
* Use a provided helper that will figure it out for you. If you wanted
to use `eval_block(&engine_state, ...)`, call `let eval_block =
get_eval_block(&engine_state); eval_block(&engine_state, ...)`
* If you know you're in an evaluation path that doesn't need debugger
support, call `eval_block::<WithoutDebug>(&engine_state, ...)` (this is
the case of hooks, for example).

I tried to add more explanation in the docstring of `debugger_trait.rs`.

## TODO

- [x] Better profiler output to reduce spam of iterative commands like
`each`
- [x] Resolve `TODO: DEBUG` comments
- [x] Resolve unwraps
- [x] Add doc comments
- [x] Add usage and extra usage for `debug profile`, explaining all
columns

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

Hopefully none.

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->
This commit is contained in:
Jakub Žádník
2024-03-08 20:21:35 +02:00
committed by GitHub
parent a9ddc58f21
commit 14d1c67863
81 changed files with 1297 additions and 205 deletions

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, redirect_env, CallExt};
use nu_engine::{get_eval_block, redirect_env, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, SyntaxShape, Type,
@ -57,6 +58,8 @@ impl Command for Collect {
}
}
let eval_block = get_eval_block(engine_state);
let result = eval_block(
engine_state,
&mut stack_captures,

View File

@ -1,7 +1,8 @@
use std::thread;
use nu_engine::{eval_block_with_early_return, redirect_env, CallExt};
use nu_engine::{get_eval_block_with_early_return, redirect_env, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoSpanned, ListStream, PipelineData, RawStream, ShellError, Signature,
@ -116,6 +117,9 @@ impl Command for Do {
)
}
}
let eval_block_with_early_return = get_eval_block_with_early_return(engine_state);
let result = eval_block_with_early_return(
engine_state,
&mut callee_stack,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, eval_expression, CallExt};
use nu_engine::{get_eval_block, get_eval_expression, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
record, Category, Example, ListStream, PipelineData, ShellError, Signature, SyntaxShape, Type,
@ -70,6 +71,10 @@ impl Command for For {
.expect("checked through parser")
.as_keyword()
.expect("internal error: missing keyword");
let eval_expression = get_eval_expression(engine_state);
let eval_block = get_eval_block(engine_state);
let values = eval_expression(engine_state, stack, keyword_expr)?;
let block: Block = call.req(engine_state, stack, 2)?;
@ -104,7 +109,6 @@ impl Command for For {
},
);
//let block = engine_state.get_block(block_id);
match eval_block(
&engine_state,
stack,
@ -150,7 +154,6 @@ impl Command for For {
},
);
//let block = engine_state.get_block(block_id);
match eval_block(
&engine_state,
stack,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, eval_expression, eval_expression_with_input, CallExt};
use nu_engine::{get_eval_block, get_eval_expression, get_eval_expression_with_input, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack, StateWorkingSet};
use nu_protocol::eval_const::{eval_const_subexpression, eval_constant, eval_constant_with_input};
use nu_protocol::{
@ -105,6 +106,9 @@ impl Command for If {
let cond = call.positional_nth(0).expect("checked through parser");
let then_block: Block = call.req(engine_state, stack, 1)?;
let else_case = call.positional_nth(2);
let eval_expression = get_eval_expression(engine_state);
let eval_expression_with_input = get_eval_expression_with_input(engine_state);
let eval_block = get_eval_block(engine_state);
let result = eval_expression(engine_state, stack, cond)?;
match &result {

View File

@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex};
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::debugger::WithoutDebug;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoPipelineData, LazyRecord, PipelineData, ShellError, Signature, Span,
@ -146,7 +147,7 @@ impl<'a> LazyRecord<'a> for NuLazyRecord {
}
}
let pipeline_result = eval_block(
let pipeline_result = eval_block::<WithoutDebug>(
&self.engine_state,
&mut stack,
block,

View File

@ -1,4 +1,4 @@
use nu_engine::eval_block;
use nu_engine::get_eval_block;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
@ -63,7 +63,7 @@ impl Command for Let {
.expect("internal error: missing right hand side");
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let pipeline_data = eval_block(engine_state, stack, block, input, true, false)?;
let mut value = pipeline_data.into_value(call.head);

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_engine::{get_eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
@ -33,6 +34,7 @@ impl Command for Loop {
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let block: Block = call.req(engine_state, stack, 0)?;
let eval_block = get_eval_block(engine_state);
loop {
if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
@ -40,6 +42,7 @@ impl Command for Loop {
}
let block = engine_state.get_block(block.block_id);
match eval_block(
engine_state,
stack,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, eval_expression, eval_expression_with_input, CallExt};
use nu_engine::{get_eval_block, get_eval_expression, get_eval_expression_with_input, CallExt};
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Matcher, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
@ -38,6 +39,9 @@ impl Command for Match {
) -> Result<PipelineData, ShellError> {
let value: Value = call.req(engine_state, stack, 0)?;
let block = call.positional_nth(1);
let eval_expression = get_eval_expression(engine_state);
let eval_expression_with_input = get_eval_expression_with_input(engine_state);
let eval_block = get_eval_block(engine_state);
if let Some(Expression {
expr: Expr::MatchBlock(matches),

View File

@ -1,5 +1,6 @@
use nu_engine::eval_block;
use nu_engine::get_eval_block;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
@ -63,6 +64,8 @@ impl Command for Mut {
.expect("internal error: missing right hand side");
let block = engine_state.get_block(block_id);
let eval_block = get_eval_block(engine_state);
let pipeline_data = eval_block(
engine_state,
stack,

View File

@ -1,4 +1,4 @@
use nu_engine::{eval_block, find_in_dirs_env, get_dirs_var_from_call, redirect_env, CallExt};
use nu_engine::{find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env, CallExt};
use nu_parser::trim_quotes_str;
use nu_protocol::ast::{Call, Expr};
use nu_protocol::engine::{Command, EngineState, Stack};
@ -141,6 +141,8 @@ impl Command for OverlayUse {
callee_stack.add_env_var("CURRENT_FILE".to_string(), file_path);
}
let eval_block = get_eval_block(engine_state);
let _ = eval_block(
engine_state,
&mut callee_stack,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, CallExt};
use nu_engine::{get_eval_block, CallExt, EvalBlockFn};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Closure, Command, EngineState, Stack};
use nu_protocol::{
record, Category, Example, IntoPipelineData, PipelineData, ShellError, Signature, Span,
@ -47,6 +48,7 @@ impl Command for Try {
let catch_block: Option<Closure> = call.opt(engine_state, stack, 1)?;
let try_block = engine_state.get_block(try_block.block_id);
let eval_block = get_eval_block(engine_state);
let result = eval_block(engine_state, stack, try_block, input, false, false);
@ -54,12 +56,12 @@ impl Command for Try {
Err(error) => {
let error = intercept_block_control(error)?;
let err_record = err_to_record(error, call.head);
handle_catch(err_record, catch_block, engine_state, stack)
handle_catch(err_record, catch_block, engine_state, stack, eval_block)
}
Ok(PipelineData::Value(Value::Error { error, .. }, ..)) => {
let error = intercept_block_control(*error)?;
let err_record = err_to_record(error, call.head);
handle_catch(err_record, catch_block, engine_state, stack)
handle_catch(err_record, catch_block, engine_state, stack, eval_block)
}
// external command may fail to run
Ok(pipeline) => {
@ -69,7 +71,7 @@ impl Command for Try {
// (unless do -c is in effect)
// they can't be passed in as Nushell values.
let err_value = Value::nothing(call.head);
handle_catch(err_value, catch_block, engine_state, stack)
handle_catch(err_value, catch_block, engine_state, stack, eval_block)
} else {
Ok(pipeline)
}
@ -98,6 +100,7 @@ fn handle_catch(
catch_block: Option<Closure>,
engine_state: &EngineState,
stack: &mut Stack,
eval_block_fn: EvalBlockFn,
) -> Result<PipelineData, ShellError> {
if let Some(catch_block) = catch_block {
let catch_block = engine_state.get_block(catch_block.block_id);
@ -108,7 +111,7 @@ fn handle_catch(
}
}
eval_block(
eval_block_fn(
engine_state,
stack,
catch_block,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, find_in_dirs_env, get_dirs_var_from_call, redirect_env};
use nu_engine::{find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env};
use nu_protocol::ast::{Call, Expr, Expression};
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
@ -117,6 +118,8 @@ This command is a parser keyword. For details, check:
callee_stack.add_env_var("CURRENT_FILE".to_string(), file_path);
}
let eval_block = get_eval_block(engine_state);
// Run the block (discard the result)
let _ = eval_block(
engine_state,

View File

@ -1,5 +1,6 @@
use nu_engine::{eval_block, eval_expression, CallExt};
use nu_engine::{get_eval_block, get_eval_expression, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Block, Command, EngineState, Stack};
use nu_protocol::{
Category, Example, PipelineData, ShellError, Signature, SyntaxShape, Type, Value,
@ -44,16 +45,21 @@ impl Command for While {
let cond = call.positional_nth(0).expect("checked through parser");
let block: Block = call.req(engine_state, stack, 1)?;
let eval_expression = get_eval_expression(engine_state);
let eval_block = get_eval_block(engine_state);
loop {
if nu_utils::ctrl_c::was_pressed(&engine_state.ctrlc) {
break;
}
let result = eval_expression(engine_state, stack, cond)?;
match &result {
Value::Bool { val, .. } => {
if *val {
let block = engine_state.get_block(block.block_id);
match eval_block(
engine_state,
stack,

View File

@ -1,4 +1,5 @@
use itertools::Itertools;
use nu_protocol::debugger::WithoutDebug;
use nu_protocol::{
ast::{Block, RangeInclusion},
engine::{EngineState, Stack, StateDelta, StateWorkingSet},
@ -115,7 +116,8 @@ pub fn eval_block(
stack.add_env_var("PWD".to_string(), Value::test_string(cwd.to_string_lossy()));
match nu_engine::eval_block(engine_state, &mut stack, &block, input, true, true) {
match nu_engine::eval_block::<WithoutDebug>(engine_state, &mut stack, &block, input, true, true)
{
Err(err) => panic!("test eval error in `{}`: {:?}", "TODO", err),
Ok(result) => result.into_value(Span::test_data()),
}