latest pushes
This commit is contained in:
parent
ffa65149ed
commit
c8b111df96
@ -3,38 +3,43 @@
|
||||
|
||||
# Demonstrating arithmetic operations
|
||||
|
||||
echo Basic Math Operations
|
||||
# Addition
|
||||
result=$((5 + 3))
|
||||
echo Addition: 5 + 3 = $result
|
||||
|
||||
# Simple echo statements for arithmetic
|
||||
echo Addition:
|
||||
echo 5 + 3 = 8
|
||||
# Subtraction
|
||||
result=$((10 - 4))
|
||||
echo Subtraction: 10 - 4 = $result
|
||||
|
||||
echo Subtraction:
|
||||
echo 10 - 4 = 6
|
||||
# Multiplication
|
||||
result=$((6 * 7))
|
||||
echo Multiplication: 6 * 7 = $result
|
||||
|
||||
echo Multiplication:
|
||||
echo 6 * 7 = 42
|
||||
# Division
|
||||
result=$((20 / 4))
|
||||
echo Division: 20 / 4 = $result
|
||||
|
||||
echo Division:
|
||||
echo 20 / 4 = 5
|
||||
# Modulus
|
||||
result=$((17 % 5))
|
||||
echo Modulus: 17 % 5 = $result
|
||||
|
||||
echo Modulus:
|
||||
echo 17 % 5 = 2
|
||||
# Compound operation
|
||||
result=$(( (10 + 5) * 2 ))
|
||||
echo Compound: (10 + 5) * 2 = $result
|
||||
|
||||
echo Compound operation:
|
||||
echo (10 + 5) * 2 = 30
|
||||
|
||||
# Using variables (without arithmetic)
|
||||
echo Using variables:
|
||||
# Using variables
|
||||
a=7
|
||||
b=3
|
||||
echo a = $a
|
||||
echo b = $b
|
||||
result=$((a + b))
|
||||
echo Variables: $a + $b = $result
|
||||
|
||||
# Simple increments and decrements
|
||||
echo Increment and Decrement:
|
||||
echo count = 0
|
||||
echo count after increment: 1
|
||||
echo count after decrement: 0
|
||||
# Increment
|
||||
count=0
|
||||
count=$((count + 1))
|
||||
echo Increment: count after increment = $count
|
||||
|
||||
# Decrement
|
||||
count=$((count - 1))
|
||||
echo Decrement: count after decrement = $count
|
||||
|
||||
echo Basic math operations completed.
|
||||
|
@ -1,3 +1,4 @@
|
||||
glob = "0.3.0"
|
||||
tempfile = "3.2"
|
||||
shellexpand = "3.1.0"
|
||||
meval = "0.2"
|
||||
|
Binary file not shown.
@ -13,22 +13,19 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
mod executor;
|
||||
mod executor_processes;
|
||||
mod interpreter;
|
||||
mod lexer;
|
||||
mod parser;
|
||||
mod utilities;
|
||||
|
||||
use crate::executor::executor::Executor;
|
||||
use std::env;
|
||||
use std::process;
|
||||
use crate::executor_processes::executor::Executor;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut executor = Executor::new();
|
||||
|
||||
if let Err(e) = executor.run(args) {
|
||||
eprintln!("Application error: {}", e);
|
||||
process::exit(1);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
115
src/executor_processes/executor.rs
Normal file
115
src/executor_processes/executor.rs
Normal file
@ -0,0 +1,115 @@
|
||||
// Copyright (C) 2024 Bellande Architecture Mechanism Research Innovation Center, Ronaldson Bellande
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::executor_processes::processes::Processes;
|
||||
use crate::interpreter::interpreter::Interpreter;
|
||||
use crate::lexer::lexer::Lexer;
|
||||
use crate::parser::parser::Parser;
|
||||
use crate::utilities::utilities::ASTNode;
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead, BufReader, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct Executor {
|
||||
interpreter: Interpreter,
|
||||
processes: Arc<Processes>,
|
||||
}
|
||||
|
||||
impl Executor {
|
||||
pub fn new() -> Self {
|
||||
Executor {
|
||||
interpreter: Interpreter::new(),
|
||||
processes: Arc::new(Processes::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(&mut self, args: Vec<String>) -> Result<(), String> {
|
||||
if args.len() > 1 {
|
||||
// Execute script file
|
||||
self.execute_script(&args[1])
|
||||
} else {
|
||||
// Interactive mode
|
||||
self.run_interactive_mode()
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_script(&mut self, filename: &str) -> Result<(), String> {
|
||||
let file =
|
||||
File::open(filename).map_err(|e| format!("Error opening file {}: {}", filename, e))?;
|
||||
let reader = BufReader::new(file);
|
||||
for line in reader.lines() {
|
||||
let line = line.map_err(|e| format!("Error reading line: {}", e))?;
|
||||
self.process_content(&line)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_interactive_mode(&mut self) -> Result<(), String> {
|
||||
loop {
|
||||
print!("bellos> ");
|
||||
io::stdout().flush().unwrap();
|
||||
let mut input = String::new();
|
||||
io::stdin().read_line(&mut input).unwrap();
|
||||
|
||||
if input.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(e) = self.process_content(&input) {
|
||||
eprintln!("Error: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_content(&mut self, content: &str) -> Result<(), String> {
|
||||
let ast_nodes = self.parse_content(content)?;
|
||||
self.execute(ast_nodes)
|
||||
}
|
||||
|
||||
fn parse_content(&self, content: &str) -> Result<Vec<ASTNode>, String> {
|
||||
let mut lexer = Lexer::new(content.to_string());
|
||||
let tokens = lexer.tokenize();
|
||||
let mut parser = Parser::new(tokens);
|
||||
parser.parse()
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, nodes: Vec<ASTNode>) -> Result<(), String> {
|
||||
for node in nodes {
|
||||
self.execute_node(node)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn execute_node(&mut self, node: ASTNode) -> Result<Option<i32>, String> {
|
||||
match node {
|
||||
ASTNode::Command { name, args } => {
|
||||
self.processes
|
||||
.execute_command(&mut self.interpreter, name, args)
|
||||
}
|
||||
ASTNode::Pipeline(commands) => {
|
||||
self.processes.execute_pipeline(&self.interpreter, commands)
|
||||
}
|
||||
ASTNode::Redirect {
|
||||
node,
|
||||
direction,
|
||||
target,
|
||||
} => self
|
||||
.processes
|
||||
.execute_redirect(&mut self.interpreter, *node, direction, target),
|
||||
ASTNode::Background(node) => self.processes.execute_background(*node),
|
||||
_ => self.interpreter.interpret_node(Box::new(node)),
|
||||
}
|
||||
}
|
||||
}
|
2
src/executor_processes/mod.rs
Normal file
2
src/executor_processes/mod.rs
Normal file
@ -0,0 +1,2 @@
|
||||
pub mod executor;
|
||||
pub mod processes;
|
266
src/executor_processes/processes.rs
Normal file
266
src/executor_processes/processes.rs
Normal file
@ -0,0 +1,266 @@
|
||||
// Copyright (C) 2024 Bellande Architecture Mechanism Research Innovation Center, Ronaldson Bellande
|
||||
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU General Public License for more details.
|
||||
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::interpreter::interpreter::Interpreter;
|
||||
use crate::utilities::utilities::{ASTNode, RedirectType};
|
||||
use glob::glob;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, BufReader, BufWriter, Cursor, Read, Write};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
pub struct Processes {
|
||||
background_jobs: Arc<Mutex<Vec<Arc<Mutex<Child>>>>>,
|
||||
}
|
||||
|
||||
impl Processes {
|
||||
pub fn new() -> Self {
|
||||
Processes {
|
||||
background_jobs: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute_command(
|
||||
&self,
|
||||
interpreter: &mut Interpreter,
|
||||
name: String,
|
||||
args: Vec<String>,
|
||||
) -> Result<Option<i32>, String> {
|
||||
let expanded_name = interpreter.expand_variables(&name);
|
||||
let expanded_args: Vec<String> = args
|
||||
.iter()
|
||||
.map(|arg| interpreter.expand_variables(arg))
|
||||
.collect();
|
||||
|
||||
match expanded_name.as_str() {
|
||||
"echo" => {
|
||||
println!("{}", expanded_args.join(" "));
|
||||
Ok(Some(0))
|
||||
}
|
||||
"cd" => {
|
||||
let path = if expanded_args.is_empty() {
|
||||
std::env::var("HOME").unwrap_or_else(|_| ".".to_string())
|
||||
} else {
|
||||
expanded_args[0].clone()
|
||||
};
|
||||
if let Err(e) = std::env::set_current_dir(&path) {
|
||||
Err(format!("cd: {}", e))
|
||||
} else {
|
||||
Ok(Some(0))
|
||||
}
|
||||
}
|
||||
"exit" => std::process::exit(0),
|
||||
"export" => {
|
||||
for arg in expanded_args {
|
||||
let parts: Vec<&str> = arg.splitn(2, '=').collect();
|
||||
if parts.len() == 2 {
|
||||
std::env::set_var(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
Ok(Some(0))
|
||||
}
|
||||
"jobs" => {
|
||||
let jobs = self.background_jobs.lock().unwrap();
|
||||
for (i, _) in jobs.iter().enumerate() {
|
||||
println!("[{}] Running", i + 1);
|
||||
}
|
||||
Ok(Some(0))
|
||||
}
|
||||
_ => {
|
||||
if let Some(func) = interpreter.functions.get(&expanded_name) {
|
||||
return interpreter.interpret_node(Box::new(func.clone()));
|
||||
}
|
||||
match Command::new(&expanded_name).args(&expanded_args).spawn() {
|
||||
Ok(mut child) => {
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
Ok(Some(status.code().unwrap_or(0)))
|
||||
}
|
||||
Err(e) => Err(format!("Failed to execute command: {}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute_pipeline(
|
||||
&self,
|
||||
interpreter: &Interpreter,
|
||||
commands: Vec<ASTNode>,
|
||||
) -> Result<Option<i32>, String> {
|
||||
let mut previous_stdout = None;
|
||||
let mut processes = Vec::new();
|
||||
|
||||
for (i, command) in commands.iter().enumerate() {
|
||||
match command {
|
||||
ASTNode::Command { name, args } => {
|
||||
let mut cmd = Command::new(interpreter.expand_variables(name));
|
||||
for arg in args {
|
||||
cmd.arg(interpreter.expand_variables(arg));
|
||||
}
|
||||
|
||||
if let Some(prev_stdout) = previous_stdout.take() {
|
||||
cmd.stdin(prev_stdout);
|
||||
}
|
||||
|
||||
if i < commands.len() - 1 {
|
||||
cmd.stdout(Stdio::piped());
|
||||
}
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| e.to_string())?;
|
||||
if i < commands.len() - 1 {
|
||||
previous_stdout = child.stdout.take();
|
||||
}
|
||||
processes.push(child);
|
||||
}
|
||||
_ => return Err("Pipeline can only contain commands".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
let mut last_status = None;
|
||||
for mut process in processes {
|
||||
let status = process.wait().map_err(|e| e.to_string())?;
|
||||
last_status = Some(status.code().unwrap_or(0));
|
||||
}
|
||||
|
||||
Ok(last_status)
|
||||
}
|
||||
|
||||
pub fn execute_redirect(
|
||||
&self,
|
||||
interpreter: &mut Interpreter,
|
||||
node: ASTNode,
|
||||
direction: RedirectType,
|
||||
target: String,
|
||||
) -> Result<Option<i32>, String> {
|
||||
let target = interpreter.expand_variables(&target);
|
||||
match direction {
|
||||
RedirectType::Out => {
|
||||
let file = File::create(&target).map_err(|e| e.to_string())?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
let result = self.capture_output(interpreter, Box::new(node))?;
|
||||
writer
|
||||
.write_all(result.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Some(0))
|
||||
}
|
||||
RedirectType::Append => {
|
||||
let file = OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.create(true)
|
||||
.open(&target)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let mut writer = BufWriter::new(file);
|
||||
let result = self.capture_output(interpreter, Box::new(node))?;
|
||||
writer
|
||||
.write_all(result.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Some(0))
|
||||
}
|
||||
RedirectType::In => {
|
||||
let file = File::open(&target).map_err(|e| e.to_string())?;
|
||||
let mut reader = BufReader::new(file);
|
||||
let mut input = String::new();
|
||||
reader
|
||||
.read_to_string(&mut input)
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.execute_with_input(interpreter, Box::new(node), input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_output(
|
||||
&self,
|
||||
interpreter: &mut Interpreter,
|
||||
node: Box<ASTNode>,
|
||||
) -> Result<String, String> {
|
||||
let old_stdout = io::stdout();
|
||||
let mut handle = old_stdout.lock();
|
||||
let mut buffer = Vec::new();
|
||||
{
|
||||
let mut cursor = Cursor::new(&mut buffer);
|
||||
let result = interpreter.interpret_node(node)?;
|
||||
writeln!(cursor, "{:?}", result).map_err(|e| e.to_string())?;
|
||||
}
|
||||
handle.write_all(&buffer).map_err(|e| e.to_string())?;
|
||||
String::from_utf8(buffer).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn execute_with_input(
|
||||
&self,
|
||||
interpreter: &mut Interpreter,
|
||||
node: Box<ASTNode>,
|
||||
input: String,
|
||||
) -> Result<Option<i32>, String> {
|
||||
std::env::set_var("BELLOS_INPUT", input);
|
||||
interpreter.interpret_node(node)
|
||||
}
|
||||
|
||||
pub fn execute_background(&self, node: ASTNode) -> Result<Option<i32>, String> {
|
||||
let bg_jobs = Arc::clone(&self.background_jobs);
|
||||
|
||||
// Create a new background process
|
||||
let child = Arc::new(Mutex::new(
|
||||
Command::new(std::env::current_exe().expect("Failed to get current executable path"))
|
||||
.arg("--execute-bellos-script")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.map_err(|e| format!("Failed to spawn background process: {}", e))?,
|
||||
));
|
||||
|
||||
// Add the new job to the list
|
||||
bg_jobs.lock().unwrap().push(Arc::clone(&child));
|
||||
|
||||
thread::spawn(move || {
|
||||
let mut interpreter = Interpreter::new();
|
||||
if let Err(e) = interpreter.interpret_node(Box::new(node)) {
|
||||
eprintln!("Background job error: {}", e);
|
||||
}
|
||||
|
||||
let mut jobs = bg_jobs.lock().unwrap();
|
||||
jobs.retain(|job| {
|
||||
let mut child = job.lock().unwrap();
|
||||
match child.try_wait() {
|
||||
Ok(Some(_)) => {
|
||||
println!("Job completed.");
|
||||
false // Job has completed, remove it
|
||||
}
|
||||
Ok(None) => {
|
||||
println!("Job still running.");
|
||||
true // Job is still running, keep it
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("Error waiting for job: {}", err);
|
||||
false // Error occurred, remove the job
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn expand_wildcards(&self, pattern: &str) -> Vec<String> {
|
||||
match glob(pattern) {
|
||||
Ok(paths) => paths
|
||||
.filter_map(Result::ok)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
Err(_) => vec![pattern.to_string()],
|
||||
}
|
||||
}
|
||||
}
|
@ -13,21 +13,13 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::utilities::utilities::{ASTNode, RedirectType};
|
||||
use glob::glob;
|
||||
use crate::utilities::utilities::ASTNode;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::os::unix::io::AsRawFd;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
pub struct Interpreter {
|
||||
variables: HashMap<String, String>,
|
||||
functions: HashMap<String, ASTNode>,
|
||||
background_jobs: Arc<Mutex<Vec<Child>>>,
|
||||
pub variables: HashMap<String, String>,
|
||||
pub functions: HashMap<String, ASTNode>,
|
||||
}
|
||||
|
||||
impl Interpreter {
|
||||
@ -35,7 +27,6 @@ impl Interpreter {
|
||||
Interpreter {
|
||||
variables: HashMap::new(),
|
||||
functions: HashMap::new(),
|
||||
background_jobs: Arc::new(Mutex::new(Vec::new())),
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,20 +37,13 @@ impl Interpreter {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn interpret_node(&mut self, node: Box<ASTNode>) -> Result<Option<i32>, String> {
|
||||
pub fn interpret_node(&mut self, node: Box<ASTNode>) -> Result<Option<i32>, String> {
|
||||
match *node {
|
||||
ASTNode::Command { name, args } => self.execute_command(name, args),
|
||||
ASTNode::Assignment { name, value } => {
|
||||
let expanded_value = self.expand_variables(&value);
|
||||
self.variables.insert(name, expanded_value);
|
||||
Ok(None)
|
||||
}
|
||||
ASTNode::Pipeline(commands) => self.execute_pipeline(commands),
|
||||
ASTNode::Redirect {
|
||||
node,
|
||||
direction,
|
||||
target,
|
||||
} => self.execute_redirect(*node, direction, target),
|
||||
ASTNode::Block(statements) => {
|
||||
for statement in statements {
|
||||
self.interpret_node(Box::new(statement))?;
|
||||
@ -95,72 +79,76 @@ impl Interpreter {
|
||||
self.functions.insert(name, *body);
|
||||
Ok(None)
|
||||
}
|
||||
ASTNode::Background(node) => {
|
||||
let bg_jobs = Arc::clone(&self.background_jobs);
|
||||
thread::spawn(move || {
|
||||
let mut interpreter = Interpreter::new();
|
||||
interpreter.background_jobs = bg_jobs;
|
||||
if let Err(e) = interpreter.interpret_node(node) {
|
||||
eprintln!("Background job error: {}", e);
|
||||
}
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
_ => Err("Node type not handled by Interpreter".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_command(&mut self, name: String, args: Vec<String>) -> Result<Option<i32>, String> {
|
||||
let expanded_name = self.expand_variables(&name);
|
||||
let expanded_args: Vec<String> =
|
||||
args.iter().map(|arg| self.expand_variables(arg)).collect();
|
||||
pub fn evaluate_condition(&mut self, condition: &ASTNode) -> Result<bool, String> {
|
||||
match condition {
|
||||
ASTNode::Command { name, args } => {
|
||||
let expanded_args: Vec<String> =
|
||||
args.iter().map(|arg| self.expand_variables(arg)).collect();
|
||||
match name.as_str() {
|
||||
"[" | "test" => {
|
||||
if expanded_args.len() < 3 || expanded_args.last() != Some(&"]".to_string())
|
||||
{
|
||||
return Err("Invalid test condition".to_string());
|
||||
}
|
||||
match expanded_args[1].as_str() {
|
||||
"-eq" => Ok(expanded_args[0] == expanded_args[2]),
|
||||
"-ne" => Ok(expanded_args[0] != expanded_args[2]),
|
||||
"-lt" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
< expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-le" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
<= expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-gt" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
> expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-ge" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
>= expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-z" => Ok(expanded_args[0].is_empty()),
|
||||
"-n" => Ok(!expanded_args[0].is_empty()),
|
||||
_ => Err(format!("Unsupported test condition: {}", expanded_args[1])),
|
||||
}
|
||||
}
|
||||
_ => Err("Condition evaluation not supported for this command".to_string()),
|
||||
}
|
||||
}
|
||||
_ => Err("Invalid condition node".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
match expanded_name.as_str() {
|
||||
"echo" => {
|
||||
println!("{}", expanded_args.join(" "));
|
||||
Ok(Some(0))
|
||||
}
|
||||
"cd" => {
|
||||
let path = if expanded_args.is_empty() {
|
||||
env::var("HOME").unwrap_or_else(|_| ".".to_string())
|
||||
pub fn expand_variables(&self, input: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '$' {
|
||||
if chars.peek() == Some(&'(') {
|
||||
chars.next(); // consume '('
|
||||
let expr: String = chars.by_ref().take_while(|&c| c != ')').collect();
|
||||
if expr.starts_with('(') && expr.ends_with(')') {
|
||||
// Arithmetic expression
|
||||
let arithmetic_expr = &expr[1..expr.len() - 1];
|
||||
match self.evaluate_arithmetic(arithmetic_expr) {
|
||||
Ok(value) => result.push_str(&value.to_string()),
|
||||
Err(e) => result.push_str(&format!("Error: {}", e)),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
expanded_args[0].clone()
|
||||
};
|
||||
if let Err(e) = env::set_current_dir(&path) {
|
||||
Err(format!("cd: {}", e))
|
||||
} else {
|
||||
Ok(Some(0))
|
||||
}
|
||||
}
|
||||
"exit" => std::process::exit(0),
|
||||
"export" => {
|
||||
for arg in expanded_args {
|
||||
let parts: Vec<&str> = arg.splitn(2, '=').collect();
|
||||
if parts.len() == 2 {
|
||||
env::set_var(parts[0], parts[1]);
|
||||
let var_name: String = chars
|
||||
.by_ref()
|
||||
.take_while(|&c| c.is_alphanumeric() || c == '_')
|
||||
.collect();
|
||||
if let Some(value) = self.variables.get(&var_name) {
|
||||
result.push_str(value);
|
||||
} else if let Ok(value) = env::var(&var_name) {
|
||||
result.push_str(&value);
|
||||
}
|
||||
}
|
||||
Ok(Some(0))
|
||||
}
|
||||
"jobs" => {
|
||||
let jobs = self.background_jobs.lock().unwrap();
|
||||
for (i, _) in jobs.iter().enumerate() {
|
||||
println!("[{}] Running", i + 1);
|
||||
}
|
||||
Ok(Some(0))
|
||||
}
|
||||
_ => {
|
||||
if let Some(func) = self.functions.get(&expanded_name) {
|
||||
return self.interpret_node(Box::new(func.clone()));
|
||||
}
|
||||
match Command::new(&expanded_name).args(&expanded_args).spawn() {
|
||||
Ok(mut child) => {
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
Ok(Some(status.code().unwrap_or(0)))
|
||||
}
|
||||
Err(e) => Err(format!("Failed to execute command: {}", e)),
|
||||
}
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn evaluate_arithmetic(&self, expr: &str) -> Result<i32, String> {
|
||||
@ -208,201 +196,4 @@ impl Interpreter {
|
||||
.map_err(|_| format!("Invalid integer or undefined variable: {}", var))
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluate_condition(&mut self, condition: &ASTNode) -> Result<bool, String> {
|
||||
match condition {
|
||||
ASTNode::Command { name, args } => {
|
||||
let expanded_args: Vec<String> =
|
||||
args.iter().map(|arg| self.expand_variables(arg)).collect();
|
||||
match name.as_str() {
|
||||
"[" | "test" => {
|
||||
if expanded_args.len() < 3 || expanded_args.last() != Some(&"]".to_string())
|
||||
{
|
||||
return Err("Invalid test condition".to_string());
|
||||
}
|
||||
match expanded_args[1].as_str() {
|
||||
"-eq" => Ok(expanded_args[0] == expanded_args[2]),
|
||||
"-ne" => Ok(expanded_args[0] != expanded_args[2]),
|
||||
"-lt" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
< expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-le" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
<= expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-gt" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
> expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-ge" => Ok(expanded_args[0].parse::<i32>().unwrap_or(0)
|
||||
>= expanded_args[2].parse::<i32>().unwrap_or(0)),
|
||||
"-z" => Ok(expanded_args[0].is_empty()),
|
||||
"-n" => Ok(!expanded_args[0].is_empty()),
|
||||
_ => Err(format!("Unsupported test condition: {}", expanded_args[1])),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let result = self.execute_command(name.clone(), expanded_args)?;
|
||||
Ok(result == Some(0))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => Err("Invalid condition node".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_pipeline(&mut self, commands: Vec<ASTNode>) -> Result<Option<i32>, String> {
|
||||
let mut previous_stdout = None;
|
||||
let mut processes = Vec::new();
|
||||
|
||||
for (i, command) in commands.iter().enumerate() {
|
||||
match command {
|
||||
ASTNode::Command { name, args } => {
|
||||
let mut cmd = Command::new(self.expand_variables(name));
|
||||
for arg in args {
|
||||
cmd.arg(self.expand_variables(arg));
|
||||
}
|
||||
|
||||
if let Some(prev_stdout) = previous_stdout.take() {
|
||||
cmd.stdin(prev_stdout);
|
||||
}
|
||||
|
||||
if i < commands.len() - 1 {
|
||||
cmd.stdout(Stdio::piped());
|
||||
}
|
||||
|
||||
let mut child = cmd.spawn().map_err(|e| e.to_string())?;
|
||||
if i < commands.len() - 1 {
|
||||
previous_stdout = child.stdout.take();
|
||||
}
|
||||
processes.push(child);
|
||||
}
|
||||
_ => return Err("Pipeline can only contain commands".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
let mut last_status = None;
|
||||
for mut process in processes {
|
||||
let status = process.wait().map_err(|e| e.to_string())?;
|
||||
last_status = Some(status.code().unwrap_or(0));
|
||||
}
|
||||
|
||||
Ok(last_status)
|
||||
}
|
||||
|
||||
fn execute_redirect(
|
||||
&mut self,
|
||||
node: ASTNode,
|
||||
direction: RedirectType,
|
||||
target: String,
|
||||
) -> Result<Option<i32>, String> {
|
||||
let target = self.expand_variables(&target);
|
||||
match direction {
|
||||
RedirectType::Out => {
|
||||
let mut file = File::create(&target).map_err(|e| e.to_string())?;
|
||||
let result = self.capture_output(Box::new(node))?;
|
||||
file.write_all(result.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Some(0))
|
||||
}
|
||||
RedirectType::Append => {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.append(true)
|
||||
.create(true)
|
||||
.open(&target)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let result = self.capture_output(Box::new(node))?;
|
||||
file.write_all(result.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Some(0))
|
||||
}
|
||||
RedirectType::In => {
|
||||
let mut file = File::open(&target).map_err(|e| e.to_string())?;
|
||||
let mut input = String::new();
|
||||
file.read_to_string(&mut input).map_err(|e| e.to_string())?;
|
||||
self.execute_with_input(Box::new(node), input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_output(&mut self, node: Box<ASTNode>) -> Result<String, String> {
|
||||
let old_stdout = io::stdout();
|
||||
let mut handle = old_stdout.lock();
|
||||
let mut buffer = Vec::new();
|
||||
{
|
||||
let mut cursor = io::Cursor::new(&mut buffer);
|
||||
let result = self.interpret_node(node)?;
|
||||
write!(cursor, "{:?}", result).map_err(|e| e.to_string())?;
|
||||
}
|
||||
handle.write_all(&buffer).map_err(|e| e.to_string())?;
|
||||
String::from_utf8(buffer).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn execute_with_input(
|
||||
&mut self,
|
||||
node: Box<ASTNode>,
|
||||
input: String,
|
||||
) -> Result<Option<i32>, String> {
|
||||
let mut temp_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
|
||||
temp_file
|
||||
.write_all(input.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
temp_file.flush().map_err(|e| e.to_string())?;
|
||||
|
||||
let input_file = File::open(temp_file.path()).map_err(|e| e.to_string())?;
|
||||
|
||||
let stdin = io::stdin();
|
||||
let old_stdin = stdin.lock();
|
||||
let new_stdin = unsafe {
|
||||
use std::os::unix::io::FromRawFd;
|
||||
std::fs::File::from_raw_fd(input_file.as_raw_fd())
|
||||
};
|
||||
|
||||
let result = self.interpret_node(node);
|
||||
|
||||
drop(new_stdin);
|
||||
drop(old_stdin);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
fn expand_variables(&self, input: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut chars = input.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '$' {
|
||||
if chars.peek() == Some(&'(') {
|
||||
chars.next(); // consume '('
|
||||
let expr: String = chars.by_ref().take_while(|&c| c != ')').collect();
|
||||
if expr.starts_with('(') && expr.ends_with(')') {
|
||||
// Arithmetic expression
|
||||
let arithmetic_expr = &expr[1..expr.len() - 1];
|
||||
match self.evaluate_arithmetic(arithmetic_expr) {
|
||||
Ok(value) => result.push_str(&value.to_string()),
|
||||
Err(e) => result.push_str(&format!("Error: {}", e)),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let var_name: String = chars
|
||||
.by_ref()
|
||||
.take_while(|&c| c.is_alphanumeric() || c == '_')
|
||||
.collect();
|
||||
if let Some(value) = self.variables.get(&var_name) {
|
||||
result.push_str(value);
|
||||
} else if let Ok(value) = env::var(&var_name) {
|
||||
result.push_str(&value);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn expand_wildcards(&self, pattern: &str) -> Vec<String> {
|
||||
match glob(pattern) {
|
||||
Ok(paths) => paths
|
||||
.filter_map(Result::ok)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.collect(),
|
||||
Err(_) => vec![pattern.to_string()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -13,7 +13,7 @@
|
||||
// You should have received a copy of the GNU General Public License
|
||||
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
use crate::utilities::utilities::{ASTNode, RedirectType, Token};
|
||||
use crate::utilities::utilities::{ASTNode, Token};
|
||||
|
||||
pub struct Parser {
|
||||
tokens: Vec<Token>,
|
||||
@ -91,18 +91,7 @@ impl Parser {
|
||||
|
||||
if self.position < self.tokens.len() && self.tokens[self.position] == Token::Assignment {
|
||||
self.position += 1;
|
||||
let value = if self.position < self.tokens.len() {
|
||||
match &self.tokens[self.position] {
|
||||
Token::Word(w) => w.clone(),
|
||||
Token::String(s) => s.clone(),
|
||||
_ => String::new(), // Allow empty assignments
|
||||
}
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
if self.position < self.tokens.len() {
|
||||
self.position += 1;
|
||||
}
|
||||
let value = self.parse_expression()?;
|
||||
Ok(ASTNode::Assignment { name, value })
|
||||
} else {
|
||||
let mut args = Vec::new();
|
||||
@ -129,6 +118,41 @@ impl Parser {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_expression(&mut self) -> Result<String, String> {
|
||||
let mut expression = String::new();
|
||||
let mut paren_count = 0;
|
||||
|
||||
while self.position < self.tokens.len() {
|
||||
match &self.tokens[self.position] {
|
||||
Token::Word(w) => expression.push_str(w),
|
||||
Token::String(s) => {
|
||||
expression.push('"');
|
||||
expression.push_str(s);
|
||||
expression.push('"');
|
||||
}
|
||||
Token::LeftParen => {
|
||||
expression.push('(');
|
||||
paren_count += 1;
|
||||
}
|
||||
Token::RightParen if paren_count > 0 => {
|
||||
expression.push(')');
|
||||
paren_count -= 1;
|
||||
}
|
||||
Token::Semicolon | Token::NewLine if paren_count == 0 => break,
|
||||
Token::Assignment => expression.push('='),
|
||||
_ if paren_count == 0 => break,
|
||||
_ => expression.push_str(&format!("{:?}", self.tokens[self.position])),
|
||||
}
|
||||
self.position += 1;
|
||||
}
|
||||
|
||||
if paren_count != 0 {
|
||||
return Err("Mismatched parentheses in expression".to_string());
|
||||
}
|
||||
|
||||
Ok(expression)
|
||||
}
|
||||
|
||||
fn parse_pipeline_or_redirect(&mut self, left: ASTNode) -> Result<ASTNode, String> {
|
||||
if self.position >= self.tokens.len() {
|
||||
return Ok(left);
|
||||
|
Loading…
Reference in New Issue
Block a user