add the ast command to peek at the internals of nushell (#6423)

* add the ast command to peak at the internals of nushell

* fixed a bug in an example
This commit is contained in:
Darren Schroeder 2022-08-26 14:48:48 -05:00 committed by GitHub
parent fbae137442
commit 3f1824111d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,77 @@
use nu_engine::CallExt;
use nu_parser::parse;
use nu_protocol::{
ast::Call,
engine::{Command, EngineState, Stack, StateWorkingSet},
Category, Example, PipelineData, ShellError, Signature, Spanned, SyntaxShape,
};
#[derive(Clone)]
pub struct Ast;
impl Command for Ast {
fn name(&self) -> &str {
"ast"
}
fn usage(&self) -> &str {
"Print the abstract syntax tree (ast) for a pipeline."
}
fn signature(&self) -> Signature {
Signature::build("ast")
.required(
"pipeline",
SyntaxShape::String,
"the pipeline to print the ast for",
)
.category(Category::Core)
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
_input: PipelineData,
) -> Result<PipelineData, ShellError> {
let head = call.head;
let pipeline: Spanned<String> = call.req(engine_state, stack, 0)?;
let mut working_set = StateWorkingSet::new(engine_state);
let (output, err) = parse(&mut working_set, None, pipeline.item.as_bytes(), false, &[]);
eprintln!("output: {:#?}\nerror: {:#?}", output, err);
Ok(PipelineData::new(head))
}
fn examples(&self) -> Vec<Example> {
vec![
Example {
description: "Print the ast of a string",
example: "ast 'hello'",
result: None,
},
Example {
description: "Print the ast of a pipeline",
example: "ast 'ls | where name =~ README'",
result: None,
},
Example {
description: "Print the ast of a pipeline with an error",
example: "ast 'for x in 1..10 { echo $x '",
result: None,
},
]
}
}
#[cfg(test)]
mod test {
#[test]
fn test_examples() {
use super::Ast;
use crate::test_examples;
test_examples(Ast {})
}
}

View File

@ -1,4 +1,5 @@
mod alias;
mod ast;
mod debug;
mod def;
mod def_env;
@ -29,6 +30,7 @@ mod use_;
mod version;
pub use alias::Alias;
pub use ast::Ast;
pub use debug::Debug;
pub use def::Def;
pub use def_env::DefEnv;

View File

@ -29,6 +29,7 @@ pub fn create_default_context() -> EngineState {
// Core
bind_command! {
Alias,
Ast,
Debug,
Def,
DefEnv,