forked from DragonOS-Community/NovaShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.rs
More file actions
712 lines (634 loc) · 27.3 KB
/
parser.rs
File metadata and controls
712 lines (634 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
use std::{
collections::HashMap,
io::ErrorKind,
os::{
fd::{AsFd, AsRawFd, FromRawFd},
unix::process::CommandExt,
},
process::{Child, ChildStdout, Stdio},
sync::{Arc, Mutex},
};
use regex::Regex;
use crate::env::EnvManager;
#[derive(Debug)]
pub enum Token {
Word(String), // 普通的命令或选项
Symbol(String), // 特殊符号
}
#[derive(Debug, Clone)]
pub enum CommandType {
Simple, // 简单命令
Redirect {
target: RedirectTarget,
mode: RedirectMode,
}, // 重定向命令
Pipe, // 管道命令
}
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum ConnectType {
Simple, // 普通连接
And, // 与连接
Or, // 或连接
}
#[derive(Debug, Clone)]
pub struct Command {
name: String,
args: Vec<String>,
cmd_type: CommandType,
conn_type: ConnectType,
}
impl Command {
pub fn new(
name: &String,
args: &[String],
cmd_type: CommandType,
conn_type: ConnectType,
) -> Command {
Self {
name: name.clone(),
args: args.to_vec(),
cmd_type,
conn_type,
}
}
pub fn execute(&self) {}
}
#[derive(Debug, Clone)]
pub enum RedirectTarget {
File(String),
FileDiscriptor(i32),
}
impl RedirectTarget {
pub fn from_string(str: &String) -> Option<RedirectTarget> {
if str.starts_with("&") {
if let Ok(fd) = str.split_at(1).1.parse::<i32>() {
Some(RedirectTarget::FileDiscriptor(fd))
} else {
None
}
} else {
Some(RedirectTarget::File(str.clone()))
}
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum RedirectMode {
Overwrite,
Append,
}
impl RedirectMode {
pub fn from_string(str: &String) -> Option<RedirectMode> {
match str.as_str() {
">" => Some(RedirectMode::Overwrite),
">>" => Some(RedirectMode::Append),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub enum ParseError {
UnexpectedInput(String),
UnsupportedToken(String),
UnexpectedToken(String),
}
impl ParseError {
pub fn handle(&self) {
match self {
ParseError::UnexpectedInput(str) => eprintln!("Unexpected input: \"{str}\""),
ParseError::UnsupportedToken(str) => eprintln!("Unsupported token: \"{str}\""),
ParseError::UnexpectedToken(str) => eprintln!("Unexpected token: \"{str}\""),
}
}
}
pub struct Parser;
impl Parser {
fn parse_env(str: &str) -> String {
std::env::var(str).unwrap_or(String::new())
}
fn lexer(input: &str) -> Result<Vec<Token>, ParseError> {
let mut tokens = Vec::new();
// 匹配环境变量的正则表达式
let env_token = Regex::new(r#"\$\{(\w[\w\d_]*)\}"#).unwrap();
// 使用具体的符号组合来匹配
let regex_token =
Regex::new(r#"([^'";|&$\s]+)|(["'].*?["'])|(&&|\|\||<<|>>|[<>|&;])"#).unwrap();
// 预先替换"${}"包围的环境变量
let remaining_input = env_token
.replace_all(input, |captures: ®ex::Captures| {
Self::parse_env(&captures[1])
})
.into_owned();
let mut remaining_input = remaining_input.trim();
while !remaining_input.is_empty() {
if let Some(mat) = regex_token.find(remaining_input) {
let token_str = mat.as_str();
if token_str.starts_with('"') || token_str.starts_with('\'') {
tokens.push(Token::Word(token_str[1..token_str.len() - 1].to_string()));
} else if token_str.starts_with('$') {
tokens.push(Token::Word(Self::parse_env(&token_str[1..])));
} else if token_str == ">>"
|| token_str == ">"
|| token_str == "<<"
|| token_str == "<"
|| token_str == "|"
|| token_str == "&"
|| token_str == ";"
|| token_str == "&&"
|| token_str == "||"
{
if token_str == "<" || token_str == "<<" {
return Err(ParseError::UnsupportedToken(token_str.to_string()));
}
tokens.push(Token::Symbol(token_str.to_string()));
} else {
tokens.push(Token::Word(token_str.to_string()));
}
remaining_input = &remaining_input[mat.end()..].trim();
} else {
return Err(ParseError::UnexpectedInput(remaining_input.to_string()));
}
}
Ok(tokens)
}
fn parser(tokens: Vec<Token>) -> Result<Vec<Pipeline>, ParseError> {
let mut commands = Vec::new();
let mut current_command: Vec<String> = Vec::new();
let mut pipelines = Vec::new();
let mut redirect_object: (Option<RedirectMode>, Option<RedirectTarget>) = (None, None);
for token in tokens {
match token {
Token::Word(ref word) => {
if let (Some(_), None) = redirect_object {
redirect_object.1 = RedirectTarget::from_string(word);
} else {
current_command.push(word.to_string());
}
}
Token::Symbol(symbol) => {
match symbol.as_str() {
">" | ">>" => {
// 重定向符号不能重复出现
if redirect_object.0.is_some() {
return Err(ParseError::UnexpectedToken(symbol));
} else {
redirect_object.0 = RedirectMode::from_string(&symbol);
}
}
"|" | "&" | "||" | "&&" | ";" => {
if let Some((name, args)) = current_command.split_first() {
let mut cmd_type =
if let (Some(mode), Some(ref target)) = redirect_object {
CommandType::Redirect {
target: target.clone(),
mode,
}
} else {
CommandType::Simple
};
let conn_type = match symbol.as_str() {
"|" => {
// 重定向优先级高于管道
if let CommandType::Simple = cmd_type {
cmd_type = CommandType::Pipe;
}
ConnectType::Simple
}
"&" | ";" => ConnectType::Simple,
"||" => ConnectType::Or,
"&&" => ConnectType::And,
_ => todo!(),
};
commands.push(Command::new(name, args, cmd_type, conn_type));
current_command.clear();
if symbol == "&" {
pipelines.push(Pipeline::new(&commands, true));
commands.clear();
}
} else {
// 这些符号之前必须有word作为命令被分隔,否则这些符号是没有意义的
return Err(ParseError::UnexpectedToken(symbol));
}
}
_ => todo!(),
}
}
}
}
// 处理最后一个命令
if let Some((name, args)) = current_command.split_first() {
commands.push(Command::new(
name,
args,
if let (Some(mode), Some(ref target)) = redirect_object {
CommandType::Redirect {
target: target.clone(),
mode,
}
} else {
CommandType::Simple
},
ConnectType::Simple,
));
}
if !commands.is_empty() {
pipelines.push(Pipeline::new(&commands, false));
}
Ok(pipelines)
}
pub fn parse(input: &str) -> Result<Vec<Pipeline>, ParseError> {
// 解析输入并生成token列表
let tokens = Self::lexer(input)?;
// println!("tokens: {tokens:?}");
// 解析 tokens 生成命令流水线
Self::parser(tokens)
}
}
#[allow(dead_code)]
#[derive(Debug)]
pub struct ExecuteError {
name: String,
err_type: ExecuteErrorType,
}
impl ExecuteError {
pub fn handle(&self, prompt: Option<String>) {
if let Some(prompt) = prompt {
eprint!("{}: ", prompt);
}
eprint!("{}: ", self.name);
match &self.err_type {
ExecuteErrorType::CommandNotFound => eprintln!("Command not found"),
ExecuteErrorType::FileNotFound(file) => eprintln!("Not a file or directory: {}", file),
ExecuteErrorType::NotDir(ref path) => eprintln!("Not a Directory: {path}"),
ExecuteErrorType::NotFile(ref path) => eprintln!("Not a File: {path}"),
ExecuteErrorType::PermissionDenied(ref file) => eprintln!("File open denied: {file}"),
ExecuteErrorType::ExecuteFailed => eprintln!("Command execute failed"),
ExecuteErrorType::ExitWithCode(exit_code) => {
eprintln!("Command exit with code: {}", exit_code)
}
ExecuteErrorType::ProcessTerminated => eprintln!("Process terminated"),
ExecuteErrorType::FileOpenFailed(file) => {
eprintln!("File open failed: {}", file.clone())
}
ExecuteErrorType::TooManyArguments => eprintln!("Too many arguments"),
ExecuteErrorType::TooFewArguments => eprintln!("Too few arguments"),
ExecuteErrorType::InvalidArgument(arg) => eprintln!("Invalid argument: {}", arg),
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum ExecuteErrorType {
CommandNotFound,
FileNotFound(String),
NotDir(String),
NotFile(String),
PermissionDenied(String),
ExecuteFailed,
ProcessTerminated,
ExitWithCode(i32),
FileOpenFailed(String),
TooManyArguments,
TooFewArguments,
InvalidArgument(String),
}
pub enum RedirectStdout {
Stdout(Option<ChildStdout>),
RawPipe(i32),
}
impl RedirectStdout {
pub fn as_raw_fd(&mut self) -> i32 {
match self {
RedirectStdout::Stdout(child_stdout) => child_stdout.take().unwrap().as_raw_fd(),
RedirectStdout::RawPipe(fd) => *fd,
}
}
pub fn as_std(&mut self) -> Stdio {
match self {
RedirectStdout::Stdout(child_stdout) => Stdio::from(child_stdout.take().unwrap()),
RedirectStdout::RawPipe(fd) => unsafe { Stdio::from_raw_fd(*fd) },
}
}
}
impl From<i32> for RedirectStdout {
fn from(value: i32) -> Self {
RedirectStdout::RawPipe(value)
}
}
impl From<Option<ChildStdout>> for RedirectStdout {
fn from(mut value: Option<ChildStdout>) -> Self {
RedirectStdout::Stdout(value.take())
}
}
#[derive(Debug)]
pub struct Pipeline {
commands: Vec<Command>, // 存储一系列命令
backend: bool,
}
type CommandMap = HashMap<String, fn(&Vec<String>) -> Result<(), ExecuteErrorType>>;
impl Pipeline {
pub fn new(commands: &Vec<Command>, backend: bool) -> Pipeline {
Self {
commands: commands.to_vec(),
backend,
}
}
pub fn execute(&self, internal_commands: Option<Arc<Mutex<CommandMap>>>) -> Vec<Child> {
// 前一个命令是否为管道输出
let mut stdout: Option<RedirectStdout> = None;
// 提前推断下条命令的布尔值,为None代表下条命令需要运行
let mut result_next: Option<bool> = None;
let mut children: Vec<Child> = Vec::new();
let mut err: Option<ExecuteErrorType> = None;
for cmd in self.commands.iter() {
if let Some(result) = result_next {
// 如果前面已经推导出本条命令的布尔值,则本条命令不需要执行,并继续推断下条命令
if (result && cmd.conn_type == ConnectType::And)
|| (!result && cmd.conn_type == ConnectType::Or)
{
// 如果true遇到||或false遇到&&,则下条命令的布尔值相同
// 如果true遇到&&或false遇到||,继承中断,设为None以执行后续命令
result_next = None;
}
continue;
}
let mut internal = false;
if let Some(ref map) = internal_commands {
let map = map.lock().unwrap();
if let Some(f) = map.get(&cmd.name) {
// 找到内部命令,优先执行,设置标记
internal = true;
// 用于同步父子进程的tty setpgrp行为的管道
let (rfd, _wfd) = nix::unistd::pipe().expect("Failed to create pipe");
// child_pid
let child_pid = if self.backend {
unsafe { libc::fork() }
} else {
0
};
// 为子进程或前台运行
if child_pid == 0 {
let mut old_stdin: Option<i32> = None;
let mut old_stdout: Option<i32> = None;
// 如果上条命令为管道,将标准输入重定向
if let Some(mut redirect_stdout) = stdout {
unsafe {
old_stdin = Some(libc::dup(libc::STDIN_FILENO));
libc::dup2(redirect_stdout.as_raw_fd(), libc::STDIN_FILENO);
stdout = None;
}
}
// 根据命令类型重定向标准输出
match cmd.cmd_type {
CommandType::Simple => {}
CommandType::Pipe => unsafe {
let mut pipe: [i32; 2] = [0; 2];
libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC);
stdout = Some(RedirectStdout::from(pipe[0]));
old_stdout = Some(libc::dup(libc::STDOUT_FILENO));
libc::dup2(pipe[1], libc::STDOUT_FILENO);
},
CommandType::Redirect {
ref target,
ref mode,
} => unsafe {
let mut pipe: [i32; 2] = [0; 2];
libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC);
stdout = Some(RedirectStdout::from(pipe[0]));
old_stdout = Some(libc::dup(libc::STDOUT_FILENO));
let append = match mode {
RedirectMode::Overwrite => false,
RedirectMode::Append => true,
};
match target {
RedirectTarget::File(file) => {
match std::fs::OpenOptions::new()
.write(true)
.append(append)
.create(true)
.open(file)
{
Ok(file) => {
libc::dup2(file.as_raw_fd(), libc::STDIN_FILENO);
}
Err(_) => {
err = Some(ExecuteErrorType::FileOpenFailed(
file.clone(),
));
}
};
}
RedirectTarget::FileDiscriptor(fd) => {
libc::dup2(*fd, libc::STDIN_FILENO);
}
}
},
}
// 如果之前没有出错,执行命令
if err.is_none() {
if let Err(err_type) = f(&cmd.args) {
err = Some(err_type);
}
}
// 还原标准输出
unsafe {
if let Some(old_stdin) = old_stdin {
libc::dup2(old_stdin, libc::STDIN_FILENO);
}
if let Some(old_stdout) = old_stdout {
libc::dup2(old_stdout, libc::STDOUT_FILENO);
}
}
if self.backend {
// 当前为后台进程,退出当前进程
std::process::exit(if err.is_none() { 0 } else { 1 });
}
} else if child_pid > 0 {
// 当前进程为父进程
drop(rfd);
unsafe {
let mut status = 0;
err = match libc::waitpid(child_pid, &mut status, 0) {
-1 => Some(ExecuteErrorType::ExecuteFailed),
_ => None,
};
if status != 0 {
if libc::WIFEXITED(status) {
if libc::WEXITSTATUS(status) != 0 {
err = Some(ExecuteErrorType::ExitWithCode(status));
}
} else if libc::WIFSIGNALED(status) {
err = Some(ExecuteErrorType::ProcessTerminated);
}
}
}
} else {
err = Some(ExecuteErrorType::ExecuteFailed)
}
}
};
// 没找到执行内部命令的标记,尝试作为外部命令执行
if !internal {
let path = if cmd.name.contains('/') {
// 为路径,获取规范的绝对路径
if let Ok(path) = std::fs::canonicalize(&cmd.name) {
if path.is_file() {
Ok(path)
} else {
// 路径不为文件,返回错误
Err(ExecuteErrorType::NotFile(cmd.name.clone()))
}
} else {
Err(ExecuteErrorType::CommandNotFound)
}
} else {
// 不为路径,从环境变量中查找命令
which::which(&cmd.name).map_err(|_| ExecuteErrorType::CommandNotFound)
};
// println!("path: {:?}", path);
match path {
Err(e) => err = Some(e),
Ok(real_path) => {
let mut child_command = std::process::Command::new(real_path);
child_command.args(cmd.args.clone());
child_command.current_dir(EnvManager::current_dir());
if stdout.is_some() {
child_command.stdin(stdout.take().unwrap().as_std());
}
match &cmd.cmd_type {
CommandType::Simple => {}
CommandType::Redirect { target, mode } => {
let append = match mode {
RedirectMode::Overwrite => false,
RedirectMode::Append => true,
};
match target {
RedirectTarget::File(file) => {
match std::fs::OpenOptions::new()
.write(true)
.append(append)
.create(true)
.open(file)
{
Ok(file) => {
child_command.stdout(file);
}
Err(_) => {
err = Some(ExecuteErrorType::FileOpenFailed(
file.clone(),
));
}
};
}
RedirectTarget::FileDiscriptor(fd) => {
child_command.stdout(unsafe { Stdio::from_raw_fd(*fd) });
}
}
}
CommandType::Pipe => {
// 标准输出重定向到管道
child_command.stdout(Stdio::piped());
}
}
let (rfd, wfd) = nix::unistd::pipe().expect("Failed to create pipe");
unsafe {
child_command.pre_exec(move || {
let mut b = [0u8; 1];
loop {
let x = nix::unistd::read(rfd.as_raw_fd(), &mut b)?;
if x != 0 {
break;
} else {
std::thread::sleep(std::time::Duration::from_millis(30));
}
}
Ok(())
});
}
if err.is_none() {
match child_command.spawn() {
Ok(mut child) => {
// 如果为管道命令,记录下来
if let CommandType::Pipe = cmd.cmd_type {
stdout = Some(RedirectStdout::Stdout(child.stdout.take()));
}
// println!("exec command: {child_command:#?}");
if !self.backend {
// 设置前台进程
unsafe {
libc::tcsetpgrp(libc::STDIN_FILENO, child.id() as i32);
};
}
// 让子进程继续执行
nix::unistd::write(wfd.as_fd(), &[1u8])
.expect("Failed to write to pipe");
drop(wfd);
match child.wait() {
Ok(exit_status) => match exit_status.code() {
Some(exit_code) => {
if exit_code != 0 {
err = Some(ExecuteErrorType::ExitWithCode(
exit_code,
));
}
}
None => err = Some(ExecuteErrorType::ProcessTerminated),
},
Err(_) => err = Some(ExecuteErrorType::ExecuteFailed),
};
if !self.backend {
// 还原前台进程
unsafe {
libc::tcsetpgrp(
libc::STDIN_FILENO,
std::process::id() as i32,
);
}
}
children.push(child);
}
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => {
err = Some(ExecuteErrorType::PermissionDenied(
cmd.name.clone(),
))
}
_ => eprintln!("Error occurred: {}", e.kind()),
},
}
}
}
}
}
// 预计算下条命令的结果
result_next = match err {
Some(ref e) => {
ExecuteError {
name: cmd.name.clone(),
err_type: e.clone(),
}
.handle(if internal {
Some("internal command".to_string())
} else {
None
});
if cmd.conn_type == ConnectType::And {
Some(false)
} else {
None
}
}
None => {
if cmd.conn_type == ConnectType::Or {
Some(true)
} else {
None
}
}
}
}
children
}
pub fn backend(&self) -> bool {
self.backend
}
}