Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions crates/deno_task_shell/src/grammar.pest
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,9 @@ pipeline = !{ Bang? ~ pipe_sequence }
pipe_sequence = !{ command ~ ((StdoutStderr | Stdout) ~ linebreak ~ pipe_sequence)? }

command = !{
function_definition |
compound_command ~ redirect_list? |
simple_command |
function_definition
simple_command
}

compound_command = {
Expand Down Expand Up @@ -378,10 +378,14 @@ binary_posix_conditional_op = !{
while_clause = !{ While ~ conditional_expression ~ do_group }
until_clause = !{ Until ~ conditional_expression ~ do_group }

function_definition = !{ fname ~ "(" ~ ")" ~ linebreak ~ function_body }
function_body = !{ compound_command ~ redirect_list? }
function_definition = {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@prsabahrami Does this grammar look fine?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO it looks good and adheres to the docs.
Thank you!

fname ~ "(" ~ ")" ~ linebreak ~ function_body |
"function" ~ fname ~ ("(" ~ ")")? ~ linebreak ~ function_body
}

function_body = !{ Lbrace ~ compound_list ~ Rbrace }

fname = @{ RESERVED_WORD | NAME | ASSIGNMENT_WORD | UNQUOTED_PENDING_WORD }
fname = @{ NAME }
name = @{ NAME }

brace_group = !{ Lbrace ~ compound_list ~ Rbrace }
Expand Down
74 changes: 71 additions & 3 deletions crates/deno_task_shell/src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ pub struct Command {
pub redirect: Option<Redirect>,
}

#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
#[cfg_attr(feature = "serialization", serde(rename_all = "camelCase"))]
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("Invalid function")]
pub struct Function {
pub name: String,
pub body: SequentialList,
}

#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
#[cfg_attr(
feature = "serialization",
Expand All @@ -170,6 +179,8 @@ pub enum CommandInner {
Case(CaseClause),
#[error("Invalid arithmetic expression")]
ArithmeticExpression(Arithmetic),
#[error("Invalid function definition")]
FunctionType(Function),
}

impl From<Command> for Sequence {
Expand Down Expand Up @@ -910,13 +921,70 @@ fn parse_command(pair: Pair<Rule>) -> Result<Command> {
match inner.as_rule() {
Rule::simple_command => parse_simple_command(inner),
Rule::compound_command => parse_compound_command(inner),
Rule::function_definition => {
Err(miette!("Function definitions are not supported yet"))
}
Rule::function_definition => parse_function_definition(inner),
_ => Err(miette!("Unexpected rule in command: {:?}", inner.as_rule())),
}
}

fn parse_function_definition(pair: Pair<Rule>) -> Result<Command> {
let mut inner = pair.into_inner();

// Handle both styles:
// 1. name() { body }
// 2. function name { body } or function name() { body }
let (name, body_pair) = if inner.peek().unwrap().as_rule() == Rule::fname {
// Style 1: name() { body }
let name = inner.next().unwrap().as_str().to_string();
// Skip the () part
if inner.peek().is_some() {
let next = inner.peek().unwrap();
if next.as_str() == "(" || next.as_str() == ")" {
inner.next(); // skip (
inner.next(); // skip )
}
}
(name, inner.next().unwrap())
} else {
// Style 2: function name [()] { body }
// Skip "function" keyword
inner.next();
let name = inner.next().unwrap().as_str().to_string();
// Skip optional ()
if inner.peek().is_some() {
let next = inner.peek().unwrap();
if next.as_str() == "(" || next.as_str() == ")" {
inner.next(); // skip (
inner.next(); // skip )
}
}
(name, inner.next().unwrap())
};

// Parse the function body
let mut body_inner = body_pair.into_inner();
// Skip Lbrace
if let Some(lbrace) = body_inner.next() {
if lbrace.as_str() != "{" {
return Err(miette!("Expected Lbrace to start function body"));
}
}
// Parse the actual compound_list
let compound_list = body_inner
.next()
.ok_or_else(|| miette!("Expected compound list in function body"))?;
let mut body_items = Vec::new();

parse_compound_list(compound_list, &mut body_items)?;

Ok(Command {
inner: CommandInner::FunctionType(Function {
name,
body: SequentialList { items: body_items },
}),
redirect: None,
})
}

fn parse_simple_command(pair: Pair<Rule>) -> Result<Command> {
let mut env_vars = Vec::new();
let mut args = Vec::new();
Expand Down
1 change: 1 addition & 0 deletions crates/deno_task_shell/src/shell/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ async fn parse_shebang_args(
CommandInner::While(_) => return err_unsupported(text),
CommandInner::ArithmeticExpression(_) => return err_unsupported(text),
CommandInner::Case(_) => return err_unsupported(text),
CommandInner::FunctionType(_) => return err_unsupported(text),
};
if !cmd.env_vars.is_empty() {
return err_unsupported(text);
Expand Down
48 changes: 48 additions & 0 deletions crates/deno_task_shell/src/shell/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,13 @@ async fn execute_command(
}
}
}
CommandInner::FunctionType(function) => {
changes.push(EnvChange::AddFunction(
function.name.clone(),
std::sync::Arc::new(function.clone()),
));
ExecuteResult::Continue(0, changes, Vec::new())
}
}
}

Expand Down Expand Up @@ -1521,6 +1528,47 @@ async fn execute_simple_command(
}
};

if !args.is_empty() {
let command_name = &args[0];
if let Some(body) = state.get_function(command_name).cloned() {
// Set $0 to function name and $1, $2, etc. to arguments
let mut function_changes = vec![EnvChange::SetShellVar(
"0".to_string(),
command_name.clone().to_string(),
)];
for (i, arg) in args.iter().skip(1).enumerate() {
function_changes.push(EnvChange::SetShellVar(
(i + 1).to_string(),
arg.clone().to_string(),
));
}

state.apply_changes(&function_changes);
changes.extend(function_changes);

let result = execute_sequential_list(
body.body.clone(),
state.clone(),
stdin,
stdout,
stderr,
AsyncCommandBehavior::Yield,
)
.await;

match result {
ExecuteResult::Exit(code, env_changes, handles) => {
changes.extend(env_changes);
return ExecuteResult::Exit(code, changes, handles);
}
ExecuteResult::Continue(code, env_changes, handles) => {
changes.extend(env_changes);
return ExecuteResult::Continue(code, changes, handles);
}
}
}
}

let mut state = state.clone();
for env_var in command.env_vars {
let word_result = evaluate_word(
Expand Down
88 changes: 87 additions & 1 deletion crates/deno_task_shell/src/shell/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use std::path::Path;
use std::path::PathBuf;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;

use futures::future::LocalBoxFuture;
use miette::Error;
Expand All @@ -25,6 +26,7 @@ use crate::shell::fs_util;

use super::commands::builtin_commands;
use super::commands::ShellCommand;
use crate::parser::Function;

#[derive(Clone)]
pub struct ShellState {
Expand Down Expand Up @@ -52,6 +54,7 @@ pub struct ShellState {
last_command_exit_code: i32, // Exit code of the last command
// The shell options to be modified using `set` command
shell_options: HashMap<ShellOptions, bool>,
pub functions: HashMap<String, Function>,
}

#[allow(clippy::print_stdout)]
Expand Down Expand Up @@ -92,6 +95,7 @@ impl ShellState {
map.insert(ShellOptions::ExitOnError, true);
map
},
functions: HashMap::new(),
};
// ensure the data is normalized
for (name, value) in env_vars {
Expand Down Expand Up @@ -293,6 +297,9 @@ impl ShellState {
EnvChange::SetShellOptions(option, value) => {
self.set_shell_option(*option, *value);
}
EnvChange::AddFunction(name, func) => {
self.add_function(name.clone(), (**func).clone());
}
}
}

Expand Down Expand Up @@ -353,9 +360,17 @@ impl ShellState {
pub fn reset_cancellation_token(&mut self) {
self.token = CancellationToken::default();
}

pub fn add_function(&mut self, name: String, func: Function) {
self.functions.insert(name, func);
}

pub fn get_function(&self, name: &str) -> Option<&Function> {
return self.functions.get(name);
}
}

#[derive(Debug, PartialEq, Eq, Clone, PartialOrd)]
#[derive(Debug, Clone)]
pub enum EnvChange {
/// `export ENV_VAR=VALUE`
SetEnvVar(String, String),
Expand All @@ -371,6 +386,77 @@ pub enum EnvChange {
Cd(PathBuf),
/// `set -ex`
SetShellOptions(ShellOptions, bool),
/// Add a user-defined function
AddFunction(String, Arc<Function>),
}

// Manual implementations for PartialEq and PartialOrd to handle Arc<Function>
impl PartialEq for EnvChange {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(EnvChange::SetEnvVar(a1, b1), EnvChange::SetEnvVar(a2, b2)) => {
a1 == a2 && b1 == b2
}
(
EnvChange::SetShellVar(a1, b1),
EnvChange::SetShellVar(a2, b2),
) => a1 == a2 && b1 == b2,
(
EnvChange::AliasCommand(a1, b1),
EnvChange::AliasCommand(a2, b2),
) => a1 == a2 && b1 == b2,
(EnvChange::UnAliasCommand(a1), EnvChange::UnAliasCommand(a2)) => {
a1 == a2
}
(EnvChange::UnsetVar(a1), EnvChange::UnsetVar(a2)) => a1 == a2,
(EnvChange::Cd(a1), EnvChange::Cd(a2)) => a1 == a2,
(
EnvChange::SetShellOptions(a1, b1),
EnvChange::SetShellOptions(a2, b2),
) => a1 == a2 && b1 == b2,
(
EnvChange::AddFunction(a1, b1),
EnvChange::AddFunction(a2, b2),
) => a1 == a2 && **b1 == **b2,
_ => false,
}
}
}

impl Eq for EnvChange {}

impl PartialOrd for EnvChange {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}

impl Ord for EnvChange {
fn cmp(&self, other: &Self) -> Ordering {
// Simple ordering based on variant - using discriminant comparison
use EnvChange::*;
let self_idx = match self {
SetEnvVar(..) => 0,
SetShellVar(..) => 1,
AliasCommand(..) => 2,
UnAliasCommand(..) => 3,
UnsetVar(..) => 4,
Cd(..) => 5,
SetShellOptions(..) => 6,
AddFunction(..) => 7,
};
let other_idx = match other {
SetEnvVar(..) => 0,
SetShellVar(..) => 1,
AliasCommand(..) => 2,
UnAliasCommand(..) => 3,
UnsetVar(..) => 4,
Cd(..) => 5,
SetShellOptions(..) => 6,
AddFunction(..) => 7,
};
self_idx.cmp(&other_idx)
}
}

#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug, PartialOrd)]
Expand Down
5 changes: 5 additions & 0 deletions crates/shell/src/commands/which.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ fn execute_which(context: &mut ShellCommandContext) -> Result<(), i32> {
return Ok(());
}

if context.state.get_function(arg).is_some() {
context.stdout.write_line("<user function>").ok();
return Ok(());
}

if context.state.resolve_custom_command(arg).is_some() {
context.stdout.write_line("<builtin function>").ok();
return Ok(());
Expand Down
Loading
Loading