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

@ -0,0 +1,149 @@
//! Traits related to debugging
//!
//! The purpose of DebugContext is achieving static dispatch on `eval_xxx()` calls.
//! The main Debugger trait is intended to be used as a trait object.
//!
//! The debugging information is stored in `EngineState` as the `debugger` field storing a `Debugger`
//! trait object behind `Arc` and `Mutex`. To evaluate something (e.g., a block), first create a
//! `Debugger` trait object (such as the `Profiler`). Then, add it to engine state via
//! `engine_state.activate_debugger()`. This sets the internal state of EngineState to the debugging
//! mode and calls `Debugger::activate()`. Now, you can call `eval_xxx::<WithDebug>()`. When you're
//! done, call `engine_state.deactivate_debugger()` which calls `Debugger::deactivate()`, sets the
//! EngineState into non-debugging mode, and returns the original mutated `Debugger` trait object.
//! (`NoopDebugger` is placed in its place inside `EngineState`.) After deactivating, you can call
//! `Debugger::report()` to get some output from the debugger, if necessary.
use crate::ast::{Block, PipelineElement};
use crate::engine::EngineState;
use crate::{PipelineData, ShellError, Span, Value};
use std::fmt::Debug;
use std::ops::DerefMut;
/// Trait used for static dispatch of `eval_xxx()` evaluator calls
///
/// DebugContext implements the same interface as Debugger (except activate() and deactivate(). It
/// is intended to be implemented only by two structs
/// * WithDebug which calls down to the Debugger methods
/// * WithoutDebug with default implementation, i.e., empty calls to be optimized away
pub trait DebugContext: Clone + Copy + Debug {
/// Called when the evaluator enters a block
#[allow(unused_variables)]
fn enter_block(engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator leaves a block
#[allow(unused_variables)]
fn leave_block(engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator enters a pipeline element
#[allow(unused_variables)]
fn enter_element(engine_state: &EngineState, element: &PipelineElement) {}
/// Called when the evaluator leaves a pipeline element
#[allow(unused_variables)]
fn leave_element(
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<(PipelineData, bool), ShellError>,
) {
}
}
/// Marker struct signalizing that evaluation should use a Debugger
///
/// Trait methods call to Debugger trait object inside the supplied EngineState.
#[derive(Clone, Copy, Debug)]
pub struct WithDebug;
impl DebugContext for WithDebug {
fn enter_block(engine_state: &EngineState, block: &Block) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().enter_block(engine_state, block);
}
}
fn leave_block(engine_state: &EngineState, block: &Block) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().leave_block(engine_state, block);
}
}
fn enter_element(engine_state: &EngineState, element: &PipelineElement) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger.deref_mut().enter_element(engine_state, element);
}
}
fn leave_element(
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<(PipelineData, bool), ShellError>,
) {
if let Ok(mut debugger) = engine_state.debugger.lock() {
debugger
.deref_mut()
.leave_element(engine_state, element, result);
}
}
}
/// Marker struct signalizing that evaluation should NOT use a Debugger
///
/// Trait methods are empty calls to be optimized away.
#[derive(Clone, Copy, Debug)]
pub struct WithoutDebug;
impl DebugContext for WithoutDebug {}
/// Debugger trait that every debugger needs to implement.
///
/// By default, its methods are empty. Not every Debugger needs to implement all of them.
pub trait Debugger: Send + Debug {
/// Called by EngineState::activate_debugger().
///
/// Intended for initializing the debugger.
fn activate(&mut self) {}
/// Called by EngineState::deactivate_debugger().
///
/// Intended for wrapping up the debugger after a debugging session before returning back to
/// normal evaluation without debugging.
fn deactivate(&mut self) {}
/// Called when the evaluator enters a block
#[allow(unused_variables)]
fn enter_block(&mut self, engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator leaves a block
#[allow(unused_variables)]
fn leave_block(&mut self, engine_state: &EngineState, block: &Block) {}
/// Called when the evaluator enters a pipeline element
#[allow(unused_variables)]
fn enter_element(&mut self, engine_state: &EngineState, pipeline_element: &PipelineElement) {}
/// Called when the evaluator leaves a pipeline element
#[allow(unused_variables)]
fn leave_element(
&mut self,
engine_state: &EngineState,
element: &PipelineElement,
result: &Result<(PipelineData, bool), ShellError>,
) {
}
/// Create a final report as a Value
///
/// Intended to be called after deactivate()
#[allow(unused_variables)]
fn report(&self, engine_state: &EngineState, debugger_span: Span) -> Result<Value, ShellError> {
Ok(Value::nothing(debugger_span))
}
}
/// A debugger that does nothing
///
/// Used as a placeholder debugger when not debugging.
#[derive(Debug)]
pub struct NoopDebugger;
impl Debugger for NoopDebugger {}

View File

@ -0,0 +1,5 @@
pub mod debugger_trait;
pub mod profiler;
pub use debugger_trait::*;
pub use profiler::*;

View File

@ -0,0 +1,360 @@
//! Nushell Profiler
//!
//! Profiler implements the Debugger trait and can be used via the `debug profile` command for
//! profiling Nushell code.
use crate::ast::{Block, Expr, PipelineElement};
use crate::debugger::Debugger;
use crate::engine::EngineState;
use crate::record;
use crate::{PipelineData, ShellError, Span, Value};
use std::time::Instant;
#[derive(Debug, Clone, Copy)]
struct ElementId(usize);
/// Stores profiling information about one pipeline element
#[derive(Debug, Clone)]
struct ElementInfo {
start: Instant,
duration_sec: f64,
depth: i64,
element_span: Span,
element_output: Option<Value>,
expr: Option<String>,
children: Vec<ElementId>,
}
impl ElementInfo {
pub fn new(depth: i64, element_span: Span) -> Self {
ElementInfo {
start: Instant::now(),
duration_sec: 0.0,
depth,
element_span,
element_output: None,
expr: None,
children: vec![],
}
}
}
/// Basic profiler, used in `debug profile`
#[derive(Debug, Clone)]
pub struct Profiler {
depth: i64,
max_depth: i64,
collect_spans: bool,
collect_source: bool,
collect_expanded_source: bool,
collect_values: bool,
collect_exprs: bool,
elements: Vec<ElementInfo>,
element_stack: Vec<ElementId>,
}
impl Profiler {
pub fn new(
max_depth: i64,
collect_spans: bool,
collect_source: bool,
collect_expanded_source: bool,
collect_values: bool,
collect_exprs: bool,
span: Span,
) -> Self {
let first = ElementInfo {
start: Instant::now(),
duration_sec: 0.0,
depth: 0,
element_span: span,
element_output: if collect_values {
Some(Value::nothing(span))
} else {
None
},
expr: if collect_exprs {
Some("call".to_string())
} else {
None
},
children: vec![],
};
Profiler {
depth: 0,
max_depth,
collect_spans,
collect_source,
collect_expanded_source,
collect_values,
collect_exprs,
elements: vec![first],
element_stack: vec![ElementId(0)],
}
}
fn last_element_id(&self) -> Option<ElementId> {
self.element_stack.last().copied()
}
fn last_element_mut(&mut self) -> Option<&mut ElementInfo> {
self.last_element_id()
.and_then(|id| self.elements.get_mut(id.0))
}
}
impl Debugger for Profiler {
fn activate(&mut self) {
let Some(root_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing root element.");
return;
};
root_element.start = Instant::now();
}
fn deactivate(&mut self) {
let Some(root_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing root element.");
return;
};
root_element.duration_sec = root_element.start.elapsed().as_secs_f64();
}
fn enter_block(&mut self, _engine_state: &EngineState, _block: &Block) {
self.depth += 1;
}
fn leave_block(&mut self, _engine_state: &EngineState, _block: &Block) {
self.depth -= 1;
}
fn enter_element(&mut self, engine_state: &EngineState, element: &PipelineElement) {
if self.depth > self.max_depth {
return;
}
let Some(parent_id) = self.last_element_id() else {
eprintln!("Profiler Error: Missing parent element ID.");
return;
};
let expr_opt = if self.collect_exprs {
Some(match element {
PipelineElement::Expression(_, expression) => {
expr_to_string(engine_state, &expression.expr)
}
_ => "other".to_string(),
})
} else {
None
};
let new_id = ElementId(self.elements.len());
let mut new_element = ElementInfo::new(self.depth, element.span());
new_element.expr = expr_opt;
self.elements.push(new_element);
let Some(parent) = self.elements.get_mut(parent_id.0) else {
eprintln!("Profiler Error: Missing parent element.");
return;
};
parent.children.push(new_id);
self.element_stack.push(new_id);
}
fn leave_element(
&mut self,
_engine_state: &EngineState,
element: &PipelineElement,
result: &Result<(PipelineData, bool), ShellError>,
) {
if self.depth > self.max_depth {
return;
}
let element_span = element.span();
let out_opt = if self.collect_values {
Some(match result {
Ok((pipeline_data, _not_sure_what_this_is)) => match pipeline_data {
PipelineData::Value(val, ..) => val.clone(),
PipelineData::ListStream(..) => Value::string("list stream", element_span),
PipelineData::ExternalStream { .. } => {
Value::string("external stream", element_span)
}
_ => Value::nothing(element_span),
},
Err(e) => Value::error(e.clone(), element_span),
})
} else {
None
};
let Some(last_element) = self.last_element_mut() else {
eprintln!("Profiler Error: Missing last element.");
return;
};
last_element.duration_sec = last_element.start.elapsed().as_secs_f64();
last_element.element_output = out_opt;
self.element_stack.pop();
}
fn report(&self, engine_state: &EngineState, profiler_span: Span) -> Result<Value, ShellError> {
Ok(Value::list(
collect_data(
engine_state,
self,
ElementId(0),
ElementId(0),
profiler_span,
)?,
profiler_span,
))
}
}
fn profiler_error(msg: impl Into<String>, span: Span) -> ShellError {
ShellError::GenericError {
error: "Profiler Error".to_string(),
msg: msg.into(),
span: Some(span),
help: None,
inner: vec![],
}
}
fn expr_to_string(engine_state: &EngineState, expr: &Expr) -> String {
match expr {
Expr::Binary(_) => "binary".to_string(),
Expr::BinaryOp(_, _, _) => "binary operation".to_string(),
Expr::Block(_) => "block".to_string(),
Expr::Bool(_) => "bool".to_string(),
Expr::Call(call) => {
let decl = engine_state.get_decl(call.decl_id);
if decl.name() == "collect" && call.head == Span::new(0, 0) {
"call (implicit collect)"
} else {
"call"
}
.to_string()
}
Expr::CellPath(_) => "cell path".to_string(),
Expr::Closure(_) => "closure".to_string(),
Expr::DateTime(_) => "datetime".to_string(),
Expr::Directory(_, _) => "directory".to_string(),
Expr::ExternalCall(_, _, _) => "external call".to_string(),
Expr::Filepath(_, _) => "filepath".to_string(),
Expr::Float(_) => "float".to_string(),
Expr::FullCellPath(full_cell_path) => {
let head = expr_to_string(engine_state, &full_cell_path.head.expr);
format!("full cell path ({head})")
}
Expr::Garbage => "garbage".to_string(),
Expr::GlobPattern(_, _) => "glob pattern".to_string(),
Expr::ImportPattern(_) => "import pattern".to_string(),
Expr::Int(_) => "int".to_string(),
Expr::Keyword(_, _, _) => "keyword".to_string(),
Expr::List(_) => "list".to_string(),
Expr::MatchBlock(_) => "match block".to_string(),
Expr::Nothing => "nothing".to_string(),
Expr::Operator(_) => "operator".to_string(),
Expr::Overlay(_) => "overlay".to_string(),
Expr::Range(_, _, _, _) => "range".to_string(),
Expr::Record(_) => "record".to_string(),
Expr::RowCondition(_) => "row condition".to_string(),
Expr::Signature(_) => "signature".to_string(),
Expr::Spread(_) => "spread".to_string(),
Expr::String(_) => "string".to_string(),
Expr::StringInterpolation(_) => "string interpolation".to_string(),
Expr::Subexpression(_) => "subexpression".to_string(),
Expr::Table(_, _) => "table".to_string(),
Expr::UnaryNot(_) => "unary not".to_string(),
Expr::ValueWithUnit(_, _) => "value with unit".to_string(),
Expr::Var(_) => "var".to_string(),
Expr::VarDecl(_) => "var decl".to_string(),
}
}
fn collect_data(
engine_state: &EngineState,
profiler: &Profiler,
element_id: ElementId,
parent_id: ElementId,
profiler_span: Span,
) -> Result<Vec<Value>, ShellError> {
let element = &profiler.elements[element_id.0];
let mut row = record! {
"depth" => Value::int(element.depth, profiler_span),
"id" => Value::int(element_id.0 as i64, profiler_span),
"parent_id" => Value::int(parent_id.0 as i64, profiler_span),
};
if profiler.collect_spans {
let span_start = i64::try_from(element.element_span.start)
.map_err(|_| profiler_error("error converting span start to i64", profiler_span))?;
let span_end = i64::try_from(element.element_span.end)
.map_err(|_| profiler_error("error converting span end to i64", profiler_span))?;
row.push(
"span",
Value::record(
record! {
"start" => Value::int(span_start, profiler_span),
"end" => Value::int(span_end, profiler_span),
},
profiler_span,
),
);
}
if profiler.collect_source {
let val = String::from_utf8_lossy(engine_state.get_span_contents(element.element_span));
let val = val.trim();
let nlines = val.lines().count();
let fragment = if profiler.collect_expanded_source {
val.to_string()
} else {
let mut first_line = val.lines().next().unwrap_or("").to_string();
if nlines > 1 {
first_line.push_str(" ...");
}
first_line
};
row.push("source", Value::string(fragment, profiler_span));
}
if let Some(expr_string) = &element.expr {
row.push("expr", Value::string(expr_string.clone(), profiler_span));
}
if let Some(val) = &element.element_output {
row.push("output", val.clone());
}
row.push(
"duration_ms",
Value::float(element.duration_sec * 1e3, profiler_span),
);
let mut rows = vec![Value::record(row, profiler_span)];
for child in &element.children {
let child_rows = collect_data(engine_state, profiler, *child, element_id, profiler_span)?;
rows.extend(child_rows);
}
Ok(rows)
}

View File

@ -4,6 +4,7 @@ use lru::LruCache;
use super::{usage::build_usage, usage::Usage, StateDelta};
use super::{Command, EnvVars, OverlayFrame, ScopeFrame, Stack, Visibility, DEFAULT_OVERLAY_NAME};
use crate::ast::Block;
use crate::debugger::{Debugger, NoopDebugger};
use crate::{
BlockId, Config, DeclId, Example, FileId, HistoryConfig, Module, ModuleId, OverlayId,
ShellError, Signature, Span, Type, VarId, Variable, VirtualPathId,
@ -14,11 +15,14 @@ use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::path::Path;
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::sync::{
atomic::{AtomicBool, AtomicU32},
Arc, Mutex,
Arc, Mutex, MutexGuard, PoisonError,
};
type PoisonDebuggerError<'a> = PoisonError<MutexGuard<'a, Box<dyn Debugger>>>;
pub static PWD_ENV: &str = "PWD";
#[derive(Clone, Debug)]
@ -33,6 +37,20 @@ pub struct ReplState {
pub cursor_pos: usize,
}
pub struct IsDebugging(AtomicBool);
impl IsDebugging {
pub fn new(val: bool) -> Self {
IsDebugging(AtomicBool::new(val))
}
}
impl Clone for IsDebugging {
fn clone(&self) -> Self {
IsDebugging(AtomicBool::new(self.0.load(Ordering::Relaxed)))
}
}
/// The core global engine state. This includes all global definitions as well as any global state that
/// will persist for the whole session.
///
@ -104,6 +122,8 @@ pub struct EngineState {
pub is_interactive: bool,
pub is_login: bool,
startup_time: i64,
is_debugging: IsDebugging,
pub debugger: Arc<Mutex<Box<dyn Debugger>>>,
}
// The max number of compiled regexes to keep around in a LRU cache, arbitrarily chosen
@ -161,6 +181,8 @@ impl EngineState {
is_interactive: false,
is_login: false,
startup_time: -1,
is_debugging: IsDebugging::new(false),
debugger: Arc::new(Mutex::new(Box::new(NoopDebugger))),
}
}
@ -916,6 +938,29 @@ impl EngineState {
self.startup_time = startup_time;
}
pub fn activate_debugger(
&self,
debugger: Box<dyn Debugger>,
) -> Result<(), PoisonDebuggerError> {
let mut locked_debugger = self.debugger.lock()?;
*locked_debugger = debugger;
locked_debugger.activate();
self.is_debugging.0.store(true, Ordering::Relaxed);
Ok(())
}
pub fn deactivate_debugger(&self) -> Result<Box<dyn Debugger>, PoisonDebuggerError> {
let mut locked_debugger = self.debugger.lock()?;
locked_debugger.deactivate();
let ret = std::mem::replace(&mut *locked_debugger, Box::new(NoopDebugger));
self.is_debugging.0.store(false, Ordering::Relaxed);
Ok(ret)
}
pub fn is_debugging(&self) -> bool {
self.is_debugging.0.load(Ordering::Relaxed)
}
pub fn recover_from_panic(&mut self) {
if Mutex::is_poisoned(&self.repl_state) {
self.repl_state = Arc::new(Mutex::new(ReplState {

View File

@ -1,3 +1,4 @@
use crate::debugger::DebugContext;
use crate::{
ast::{
eval_operator, Assignment, Bits, Boolean, Call, Comparison, Expr, Expression,
@ -5,6 +6,7 @@ use crate::{
},
Config, IntoInterruptiblePipelineData, Range, Record, ShellError, Span, Value, VarId,
};
use std::{borrow::Cow, collections::HashMap};
/// To share implementations for regular eval and const eval
@ -17,7 +19,7 @@ pub trait Eval {
/// This is the stack for regular eval, and unused by const eval
type MutState;
fn eval(
fn eval<D: DebugContext>(
state: Self::State<'_>,
mut_state: &mut Self::MutState,
expr: &Expression,
@ -34,7 +36,7 @@ pub trait Eval {
Expr::Var(var_id) => Self::eval_var(state, mut_state, *var_id, expr.span),
Expr::CellPath(cell_path) => Ok(Value::cell_path(cell_path.clone(), expr.span)),
Expr::FullCellPath(cell_path) => {
let value = Self::eval(state, mut_state, &cell_path.head)?;
let value = Self::eval::<D>(state, mut_state, &cell_path.head)?;
value.follow_cell_path(&cell_path.tail, false)
}
@ -43,11 +45,11 @@ pub trait Eval {
let mut output = vec![];
for expr in x {
match &expr.expr {
Expr::Spread(expr) => match Self::eval(state, mut_state, expr)? {
Expr::Spread(expr) => match Self::eval::<D>(state, mut_state, expr)? {
Value::List { mut vals, .. } => output.append(&mut vals),
_ => return Err(ShellError::CannotSpreadAsList { span: expr.span }),
},
_ => output.push(Self::eval(state, mut_state, expr)?),
_ => output.push(Self::eval::<D>(state, mut_state, expr)?),
}
}
Ok(Value::list(output, expr.span))
@ -59,7 +61,7 @@ pub trait Eval {
match item {
RecordItem::Pair(col, val) => {
// avoid duplicate cols
let col_name = Self::eval(state, mut_state, col)?.coerce_into_string()?;
let col_name = Self::eval::<D>(state, mut_state, col)?.coerce_into_string()?;
if let Some(orig_span) = col_names.get(&col_name) {
return Err(ShellError::ColumnDefinedTwice {
col_name,
@ -68,11 +70,11 @@ pub trait Eval {
});
} else {
col_names.insert(col_name.clone(), col.span);
record.push(col_name, Self::eval(state, mut_state, val)?);
record.push(col_name, Self::eval::<D>(state, mut_state, val)?);
}
}
RecordItem::Spread(_, inner) => {
match Self::eval(state, mut_state, inner)? {
match Self::eval::<D>(state, mut_state, inner)? {
Value::Record { val: inner_val, .. } => {
for (col_name, val) in inner_val {
if let Some(orig_span) = col_names.get(&col_name) {
@ -102,7 +104,7 @@ pub trait Eval {
Expr::Table(headers, vals) => {
let mut output_headers = vec![];
for expr in headers {
let header = Self::eval(state, mut_state, expr)?.coerce_into_string()?;
let header = Self::eval::<D>(state, mut_state, expr)?.coerce_into_string()?;
if let Some(idx) = output_headers
.iter()
.position(|existing| existing == &header)
@ -120,7 +122,7 @@ pub trait Eval {
let mut output_rows = vec![];
for val in vals {
let record = output_headers.iter().zip(val).map(|(col, expr)| {
Self::eval(state, mut_state, expr).map(|val| (col.clone(), val))
Self::eval::<D>(state, mut_state, expr).map(|val| (col.clone(), val))
}).collect::<Result<_,_>>()?;
output_rows.push(Value::record(
@ -130,10 +132,10 @@ pub trait Eval {
}
Ok(Value::list(output_rows, expr.span))
}
Expr::Keyword(_, _, expr) => Self::eval(state, mut_state, expr),
Expr::Keyword(_, _, expr) => Self::eval::<D>(state, mut_state, expr),
Expr::String(s) => Ok(Value::string(s.clone(), expr.span)),
Expr::Nothing => Ok(Value::nothing(expr.span)),
Expr::ValueWithUnit(e, unit) => match Self::eval(state, mut_state, e)? {
Expr::ValueWithUnit(e, unit) => match Self::eval::<D>(state, mut_state, e)? {
Value::Int { val, .. } => unit.item.to_value(val, unit.span),
x => Err(ShellError::CantConvert {
to_type: "unit value".into(),
@ -142,28 +144,28 @@ pub trait Eval {
help: None,
}),
},
Expr::Call(call) => Self::eval_call(state, mut_state, call, expr.span),
Expr::Call(call) => Self::eval_call::<D>(state, mut_state, call, expr.span),
Expr::ExternalCall(head, args, is_subexpression) => {
Self::eval_external_call(state, mut_state, head, args, *is_subexpression, expr.span)
}
Expr::Subexpression(block_id) => {
Self::eval_subexpression(state, mut_state, *block_id, expr.span)
Self::eval_subexpression::<D>(state, mut_state, *block_id, expr.span)
}
Expr::Range(from, next, to, operator) => {
let from = if let Some(f) = from {
Self::eval(state, mut_state, f)?
Self::eval::<D>(state, mut_state, f)?
} else {
Value::nothing(expr.span)
};
let next = if let Some(s) = next {
Self::eval(state, mut_state, s)?
Self::eval::<D>(state, mut_state, s)?
} else {
Value::nothing(expr.span)
};
let to = if let Some(t) = to {
Self::eval(state, mut_state, t)?
Self::eval::<D>(state, mut_state, t)?
} else {
Value::nothing(expr.span)
};
@ -173,7 +175,7 @@ pub trait Eval {
))
}
Expr::UnaryNot(expr) => {
let lhs = Self::eval(state, mut_state, expr)?;
let lhs = Self::eval::<D>(state, mut_state, expr)?;
match lhs {
Value::Bool { val, .. } => Ok(Value::bool(!val, expr.span)),
other => Err(ShellError::TypeMismatch {
@ -188,13 +190,13 @@ pub trait Eval {
match op {
Operator::Boolean(boolean) => {
let lhs = Self::eval(state, mut_state, lhs)?;
let lhs = Self::eval::<D>(state, mut_state, lhs)?;
match boolean {
Boolean::And => {
if lhs.is_false() {
Ok(Value::bool(false, expr.span))
} else {
let rhs = Self::eval(state, mut_state, rhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
lhs.and(op_span, &rhs, expr.span)
}
}
@ -202,19 +204,19 @@ pub trait Eval {
if lhs.is_true() {
Ok(Value::bool(true, expr.span))
} else {
let rhs = Self::eval(state, mut_state, rhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
lhs.or(op_span, &rhs, expr.span)
}
}
Boolean::Xor => {
let rhs = Self::eval(state, mut_state, rhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
lhs.xor(op_span, &rhs, expr.span)
}
}
}
Operator::Math(math) => {
let lhs = Self::eval(state, mut_state, lhs)?;
let rhs = Self::eval(state, mut_state, rhs)?;
let lhs = Self::eval::<D>(state, mut_state, lhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
match math {
Math::Plus => lhs.add(op_span, &rhs, expr.span),
@ -228,8 +230,8 @@ pub trait Eval {
}
}
Operator::Comparison(comparison) => {
let lhs = Self::eval(state, mut_state, lhs)?;
let rhs = Self::eval(state, mut_state, rhs)?;
let lhs = Self::eval::<D>(state, mut_state, lhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
match comparison {
Comparison::LessThan => lhs.lt(op_span, &rhs, expr.span),
Comparison::LessThanOrEqual => lhs.lte(op_span, &rhs, expr.span),
@ -250,8 +252,8 @@ pub trait Eval {
}
}
Operator::Bits(bits) => {
let lhs = Self::eval(state, mut_state, lhs)?;
let rhs = Self::eval(state, mut_state, rhs)?;
let lhs = Self::eval::<D>(state, mut_state, lhs)?;
let rhs = Self::eval::<D>(state, mut_state, rhs)?;
match bits {
Bits::BitAnd => lhs.bit_and(op_span, &rhs, expr.span),
Bits::BitOr => lhs.bit_or(op_span, &rhs, expr.span),
@ -260,8 +262,8 @@ pub trait Eval {
Bits::ShiftRight => lhs.bit_shr(op_span, &rhs, expr.span),
}
}
Operator::Assignment(assignment) => Self::eval_assignment(
state, mut_state, lhs, rhs, assignment, op_span, expr.span,
Operator::Assignment(assignment) => Self::eval_assignment::<D>(
state, mut_state, lhs, rhs, assignment, op_span, expr.span
),
}
}
@ -272,7 +274,7 @@ pub trait Eval {
Expr::StringInterpolation(exprs) => {
let mut parts = vec![];
for expr in exprs {
parts.push(Self::eval(state, mut_state, expr)?);
parts.push(Self::eval::<D>(state, mut_state, expr)?);
}
let config = Self::get_config(state, mut_state);
@ -324,7 +326,7 @@ pub trait Eval {
span: Span,
) -> Result<Value, ShellError>;
fn eval_call(
fn eval_call<D: DebugContext>(
state: Self::State<'_>,
mut_state: &mut Self::MutState,
call: &Call,
@ -340,7 +342,7 @@ pub trait Eval {
span: Span,
) -> Result<Value, ShellError>;
fn eval_subexpression(
fn eval_subexpression<D: DebugContext>(
state: Self::State<'_>,
mut_state: &mut Self::MutState,
block_id: usize,
@ -356,7 +358,8 @@ pub trait Eval {
expr_span: Span,
) -> Result<Value, ShellError>;
fn eval_assignment(
#[allow(clippy::too_many_arguments)]
fn eval_assignment<D: DebugContext>(
state: Self::State<'_>,
mut_state: &mut Self::MutState,
lhs: &Expression,

View File

@ -1,3 +1,4 @@
use crate::debugger::{DebugContext, WithoutDebug};
use crate::{
ast::{Assignment, Block, Call, Expr, Expression, ExternalArgument, PipelineElement},
engine::{EngineState, StateWorkingSet},
@ -5,10 +6,8 @@ use crate::{
record, Config, HistoryFileFormat, PipelineData, Record, ShellError, Span, Value, VarId,
};
use nu_system::os_info::{get_kernel_version, get_os_arch, get_os_family, get_os_name};
use std::{
borrow::Cow,
path::{Path, PathBuf},
};
use std::borrow::Cow;
use std::path::{Path, PathBuf};
pub fn create_nu_constant(engine_state: &EngineState, span: Span) -> Result<Value, ShellError> {
fn canonicalize_path(engine_state: &EngineState, path: &Path) -> PathBuf {
@ -257,7 +256,8 @@ pub fn eval_constant(
working_set: &StateWorkingSet,
expr: &Expression,
) -> Result<Value, ShellError> {
<EvalConst as Eval>::eval(working_set, &mut (), expr)
// TODO: Allow debugging const eval
<EvalConst as Eval>::eval::<WithoutDebug>(working_set, &mut (), expr)
}
struct EvalConst;
@ -303,12 +303,13 @@ impl Eval for EvalConst {
}
}
fn eval_call(
fn eval_call<D: DebugContext>(
working_set: &StateWorkingSet,
_: &mut (),
call: &Call,
span: Span,
) -> Result<Value, ShellError> {
// TODO: Allow debugging const eval
// TODO: eval.rs uses call.head for the span rather than expr.span
Ok(eval_const_call(working_set, call, PipelineData::empty())?.into_value(span))
}
@ -325,12 +326,13 @@ impl Eval for EvalConst {
Err(ShellError::NotAConstant { span })
}
fn eval_subexpression(
fn eval_subexpression<D: DebugContext>(
working_set: &StateWorkingSet,
_: &mut (),
block_id: usize,
span: Span,
) -> Result<Value, ShellError> {
// TODO: Allow debugging const eval
let block = working_set.get_block(block_id);
Ok(
eval_const_subexpression(working_set, block, PipelineData::empty(), span)?
@ -349,7 +351,7 @@ impl Eval for EvalConst {
Err(ShellError::NotAConstant { span: expr_span })
}
fn eval_assignment(
fn eval_assignment<D: DebugContext>(
_: &StateWorkingSet,
_: &mut (),
_: &Expression,
@ -358,6 +360,7 @@ impl Eval for EvalConst {
_op_span: Span,
expr_span: Span,
) -> Result<Value, ShellError> {
// TODO: Allow debugging const eval
Err(ShellError::NotAConstant { span: expr_span })
}

View File

@ -2,6 +2,7 @@ mod alias;
pub mod ast;
pub mod cli_error;
pub mod config;
pub mod debugger;
mod did_you_mean;
pub mod engine;
pub mod eval_base;