/
mod.rs
271 lines (247 loc) · 9.83 KB
/
mod.rs
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
//! Contains the binary logic of Ion.
mod prompt;
mod readln;
use self::prompt::{prompt, prompt_fn};
use self::readln::readln;
use super::{FlowLogic, JobControl, Shell, ShellHistory};
use super::flags::*;
use super::flow_control::Statement;
use super::library::IonLibrary;
use super::status::*;
use liner::{Buffer, Context};
use parser::QuoteTerminator;
use smallvec::SmallVec;
use std::env;
use std::fs::File;
use std::io::{self, ErrorKind, Write};
use std::iter::{self, FromIterator};
use std::path::Path;
use std::process;
pub(crate) trait Binary {
/// Launches the shell, parses arguments, and then diverges into one of the `execution`
/// paths.
fn main(self);
/// Parses and executes the arguments that were supplied to the shell.
fn execute_arguments<A: Iterator<Item = String>>(&mut self, args: A);
/// Creates an interactive session that reads from a prompt provided by Liner.
fn execute_interactive(self);
/// Ensures that read statements from a script are terminated.
fn terminate_script_quotes<I: Iterator<Item = String>>(&mut self, lines: I) -> i32;
/// Ensures that read statements from the interactive prompt is terminated.
fn terminate_quotes(&mut self, command: String) -> Result<String, ()>;
/// Ion's interface to Liner's `read_line` method, which handles everything related to
/// rendering, controlling, and getting input from the prompt.
fn readln(&mut self) -> Option<String>;
/// Generates the prompt that will be used by Liner.
fn prompt(&mut self) -> String;
/// Display version information and exit
fn display_version(&self);
// Executes the PROMPT function, if it exists, and returns the output.
fn prompt_fn(&mut self) -> Option<String>;
}
impl Binary for Shell {
fn prompt(&mut self) -> String { prompt(self) }
fn prompt_fn(&mut self) -> Option<String> { prompt_fn(self) }
fn readln(&mut self) -> Option<String> { readln(self) }
fn terminate_script_quotes<I: Iterator<Item = String>>(&mut self, mut lines: I) -> i32 {
while let Some(command) = lines.next() {
let mut buffer = QuoteTerminator::new(command);
while !buffer.check_termination() {
loop {
if let Some(command) = lines.next() {
buffer.append(command);
break;
} else {
let stderr = io::stderr();
let _ = writeln!(stderr.lock(), "ion: unterminated quote in script");
return FAILURE;
}
}
}
self.on_command(&buffer.consume());
}
// The flow control level being non zero means that we have a statement that has
// only been partially parsed.
if self.flow_control.level != 0 {
eprintln!(
"ion: unexpected end of script: expected end block for `{}`",
self.flow_control.current_statement.short()
);
return FAILURE;
}
SUCCESS
}
fn terminate_quotes(&mut self, command: String) -> Result<String, ()> {
let mut buffer = QuoteTerminator::new(command);
self.flow_control.level += 1;
while !buffer.check_termination() {
if let Some(command) = self.readln() {
buffer.append(command);
} else {
return Err(());
}
}
self.flow_control.level -= 1;
let terminated = buffer.consume();
Ok(terminated)
}
fn execute_arguments<A: Iterator<Item = String>>(&mut self, mut args: A) {
if let Some(mut arg) = args.next() {
for argument in args {
arg.push(' ');
if argument == "" {
arg.push_str("''");
} else {
arg.push_str(&argument);
}
}
self.on_command(&arg);
} else {
let stderr = io::stderr();
let mut stderr = stderr.lock();
let _ = writeln!(stderr, "ion: -c requires an argument");
self.exit(FAILURE);
}
if self.flow_control.level != 0 {
eprintln!(
"ion: unexpected end of arguments: expected end block for `{}`",
self.flow_control.current_statement.short()
);
self.exit(FAILURE);
}
}
fn execute_interactive(mut self) {
self.context = Some({
let mut context = Context::new();
context.word_divider_fn = Box::new(word_divide);
if "1" == self.variables.get_var_or_empty("HISTFILE_ENABLED") {
let path = self.variables.get_var("HISTFILE").expect("shell didn't set HISTFILE");
context.history.set_file_name(Some(path.clone()));
if !Path::new(path.as_str()).exists() {
eprintln!("ion: creating history file at \"{}\"", path);
if let Err(why) = File::create(path) {
eprintln!("ion: could not create history file: {}", why);
}
}
match context.history.load_history() {
Ok(()) => {
// pass
}
Err(ref err) if err.kind() == ErrorKind::NotFound => {
let history_filename = self.variables.get_var_or_empty("HISTFILE");
eprintln!("ion: failed to find history file {}: {}", history_filename, err);
}
Err(err) => {
eprintln!("ion: failed to load history: {}", err);
}
}
}
context
});
self.evaluate_init_file();
self.variables.set_array("args", iter::once(env::args().next().unwrap()).collect());
loop {
if let Some(command) = self.readln() {
if !command.is_empty() {
if let Ok(command) = self.terminate_quotes(command.replace("\\\n", "")) {
let cmd = command.trim();
self.on_command(cmd);
if cmd.starts_with('~') {
if !cmd.ends_with('/')
&& self.variables
.tilde_expansion(cmd, &self.directory_stack)
.map_or(false, |ref path| Path::new(path).is_dir())
{
self.save_command_in_history(&[cmd, "/"].concat());
} else {
self.save_command_in_history(cmd);
}
self.update_variables();
continue;
}
if Path::new(cmd).is_dir() & !cmd.ends_with('/') {
self.save_command_in_history(&[cmd, "/"].concat());
} else {
self.save_command_in_history(cmd);
}
} else {
self.flow_control.level = 0;
self.flow_control.current_if_mode = 0;
self.flow_control.current_statement = Statement::Default;
}
}
self.update_variables();
} else {
self.flow_control.level = 0;
self.flow_control.current_if_mode = 0;
self.flow_control.current_statement = Statement::Default;
}
}
}
fn main(mut self) {
let mut args = env::args().skip(1);
while let Some(path) = args.next() {
match path.as_str() {
"-n" => {
self.flags |= NO_EXEC;
continue;
}
"-c" => self.execute_arguments(args),
"--version" => self.display_version(),
_ => {
let mut array = SmallVec::from_iter(Some(path.clone().into()));
for arg in args {
array.push(arg.into());
}
self.variables.set_array("args", array);
if let Err(err) = self.execute_script(&path) {
eprintln!("ion: {}", err);
}
}
}
self.wait_for_background();
let previous_status = self.previous_status;
self.exit(previous_status);
}
self.execute_interactive();
}
fn display_version(&self) {
println!("{}", include!(concat!(env!("OUT_DIR"), "/version_string")));
process::exit(0);
}
}
fn word_divide(buf: &Buffer) -> Vec<(usize, usize)> {
let mut res = Vec::new();
let mut word_start = None;
macro_rules! check_boundary {
($c:expr, $index:expr, $escaped:expr) => {{
if let Some(start) = word_start {
if $c == ' ' && !$escaped {
res.push((start, $index));
word_start = None;
}
} else {
if $c != ' ' {
word_start = Some($index);
}
}
}}
}
let mut iter = buf.chars().enumerate();
while let Some((i, &c)) = iter.next() {
match c {
'\\' => {
if let Some((_, &cnext)) = iter.next() {
// We use `i` in order to include the backslash as part of the word
check_boundary!(cnext, i, true);
}
}
c => check_boundary!(c, i, false),
}
}
if let Some(start) = word_start {
// When start has been set, that means we have encountered a full word.
res.push((start, buf.num_chars()));
}
res
}