ion-shell 1.0.1

The Ion Shell
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
// TODO: Handle Runtime Errors
extern crate permutate;
extern crate unicode_segmentation;
use self::unicode_segmentation::UnicodeSegmentation;

use types::Array;

mod braces;
mod ranges;
mod words;

use self::braces::BraceToken;
use self::ranges::parse_range;
pub use self::words::{WordIterator, WordToken};

pub use self::words::{Index, IndexEnd};

use std::io::{self, Write};
use types::*;

pub struct ExpanderFunctions<'f> {
    pub tilde:    &'f Fn(&str) -> Option<String>,
    pub array:    &'f Fn(&str, Index) -> Option<Array>,
    pub variable: &'f Fn(&str, bool) -> Option<Value>,
    pub command:  &'f Fn(&str, bool) -> Option<Value>
}

fn expand_process(current: &mut String, command: &str, quoted: bool,
    index: Index, expand_func: &ExpanderFunctions)
{
    let mut tokens = Vec::new();
    let mut contains_brace = false;

    for token in WordIterator::new(command, false) {
        if let WordToken::Brace(_) = token { contains_brace = true; }
        tokens.push(token);
    }

    let expanded = expand_tokens(&tokens, expand_func, false, contains_brace).join(" ");

    if let Some(result) = (expand_func.command)(&expanded, quoted) {
        slice_string(current, &result, index);
    }
}

fn expand_brace(current: &mut String, expanders: &mut Vec<Vec<String>>,
    tokens: &mut Vec<BraceToken>, nodes: &[&str], expand_func: &ExpanderFunctions,
    reverse_quoting: bool)
{
    let mut temp = Vec::new();
    for word in nodes.into_iter()
        .flat_map(|node| expand_string(node, expand_func, reverse_quoting))
    {
        match parse_range(&word) {
            Some(elements) => for word in elements { temp.push(word.into()) },
            None           => temp.push(word.into()),
        }
    }

    if !temp.is_empty() {
        if !current.is_empty() {
            tokens.push(BraceToken::Normal(current.clone()));
            current.clear();
        }
        tokens.push(BraceToken::Expander);
        expanders.push(temp);
    } else {
        current.push_str("{}");
    }
}

fn array_expand(elements: &[&str], expand_func: &ExpanderFunctions) -> Array {
    elements.iter()
        .flat_map(|element| expand_string(element, expand_func, false))
        .collect()
}

fn array_nth(elements: &[&str], expand_func: &ExpanderFunctions, id: usize) -> Value {
    elements.iter()
        .flat_map(|element| expand_string(element, expand_func, false))
        .nth(id).unwrap_or_default()
}

fn array_range(elements: &[&str], expand_func: &ExpanderFunctions, start: usize, end: IndexEnd) -> Array {
    match end {
        IndexEnd::CatchAll => elements.iter()
            .flat_map(|element| expand_string(element, expand_func, false))
            .skip(start).collect(),
        IndexEnd::ID(end) => elements.iter()
            .flat_map(|element| expand_string(element, expand_func, false))
            .skip(start).take(end-start).collect()
    }
}

fn slice_string(output: &mut String, expanded: &str, index: Index) {
    match index {
        Index::None => (),
        Index::All => output.push_str(expanded),
        Index::ID(id) => {
            if let Some(character) = UnicodeSegmentation::graphemes(expanded, true).nth(id) {
                output.push_str(character);
            }
        },
        Index::Range(start, IndexEnd::ID(end)) => {
            let substring = UnicodeSegmentation::graphemes(expanded, true)
                .skip(start).take(end-start)
                .collect::<Vec<&str>>().join("");

            output.push_str(&substring);
        },
        Index::Range(start, IndexEnd::CatchAll) => {
            let substring = UnicodeSegmentation::graphemes(expanded, true)
                .skip(start).collect::<Vec<&str>>().join("");

            output.push_str(&substring);
        }
    }
}

/// Performs shell expansions to an input string, efficiently returning the final expanded form.
/// Shells must provide their own batteries for expanding tilde and variable words.
pub fn expand_string(
    original: &str,
    expand_func: &ExpanderFunctions,
    reverse_quoting: bool
) -> Array {
    let mut token_buffer = Vec::new();
    let mut contains_brace = false;

    for word in WordIterator::new(original, true) {
        if let WordToken::Brace(_) = word { contains_brace = true; }
        token_buffer.push(word);
    }

    expand_tokens(
        &token_buffer,
        expand_func,
        reverse_quoting,
        contains_brace
    )
}

#[allow(cyclomatic_complexity)]
pub fn expand_tokens<'a>(token_buffer: &[WordToken], expand_func: &'a ExpanderFunctions,
    reverse_quoting: bool, contains_brace: bool) -> Array
{
    let mut output = String::new();
    let mut expanded_words = Array::new();

    if !token_buffer.is_empty() {
        if contains_brace {
            let mut tokens: Vec<BraceToken> = Vec::new();
            let mut expanders: Vec<Vec<String>> = Vec::new();

            for word in token_buffer {
                match *word {
                    WordToken::Array(ref elements, index) => {
                        match index {
                            Index::None => (),
                            Index::All => {
                                let expanded = array_expand(elements, expand_func);
                                output.push_str(&expanded.join(" "));
                            },
                            Index::ID(id) => {
                                let expanded = array_nth(elements, expand_func, id);
                                output.push_str(&expanded);
                            },
                            Index::Range(start, end) => {
                                let expanded = array_range(elements, expand_func, start, end);
                                output.push_str(&expanded.join(" "));
                            }
                        };
                    },
                    WordToken::ArrayVariable(array, _, index) => {
                        if let Some(array) = (expand_func.array)(array, index) {
                            output.push_str(&array.join(" "));
                        }
                    },
                    WordToken::ArrayProcess(command, quoted, index) => {
                        let quoted = if reverse_quoting { !quoted } else { quoted };
                        match index {
                            Index::None => (),
                            Index::All => {
                                let mut temp = String::new();
                                expand_process(&mut temp, command, quoted, Index::All, expand_func);
                                let temp = temp.split_whitespace().collect::<Vec<&str>>();
                                output.push_str(&temp.join(" "));
                            },
                            Index::ID(id) => {
                                let mut temp = String::new();
                                expand_process(&mut temp, command, quoted, Index::All, expand_func);
                                output.push_str(temp.split_whitespace().nth(id).unwrap_or_default());
                            },
                            Index::Range(start, end) => {
                                let mut temp = String::new();
                                expand_process(&mut temp, command, quoted, Index::All, expand_func);
                                let temp = match end {
                                    IndexEnd::ID(end) => temp.split_whitespace()
                                        .skip(start).take(end-start)
                                        .collect::<Vec<&str>>(),
                                    IndexEnd::CatchAll => temp.split_whitespace()
                                        .skip(start).collect::<Vec<&str>>()
                                };
                                output.push_str(&temp.join(" "));
                            }
                        }
                    },
                    WordToken::ArrayMethod(ref array_method) => {
                        array_method.handle(&mut output, expand_func);
                    },
                    WordToken::StringMethod(method, variable, pattern, index) => {
                        let pattern = &expand_string(pattern, expand_func, false).join(" ");
                        match method {
                            "join" => if let Some(array) = (expand_func.array)(variable, Index::All) {
                                slice_string(&mut output, &array.join(pattern), index);
                            },
                            _ => {
                                let stderr = io::stderr();
                                let mut stderr = stderr.lock();
                                let _ = writeln!(stderr, "ion: invalid string method: {}", method);
                            }
                        }
                    },
                    WordToken::Brace(ref nodes) =>
                        expand_brace(&mut output, &mut expanders, &mut tokens, nodes, expand_func, reverse_quoting),
                    WordToken::Normal(text) => output.push_str(text),
                    WordToken::Whitespace(_) => unreachable!(),
                    WordToken::Tilde(text) => output.push_str(match (expand_func.tilde)(text) {
                        Some(ref expanded) => expanded,
                        None               => text,
                    }),
                    WordToken::Process(command, quoted, index) => {
                        let quoted = if reverse_quoting { !quoted } else { quoted };
                        expand_process(&mut output, command, quoted, index, expand_func);
                    },
                    WordToken::Variable(text, quoted, index) => {
                        let quoted = if reverse_quoting { !quoted } else { quoted };
                        let expanded = match (expand_func.variable)(text, quoted) {
                            Some(var) => var,
                            None      => continue
                        };

                        slice_string(&mut output, &expanded, index);
                    },
                }
            }

            if expanders.is_empty() {
                expanded_words.push(output.into());
            } else {
                if !output.is_empty() {
                    tokens.push(BraceToken::Normal(output));
                }
                for word in braces::expand_braces(&tokens, expanders) {
                    expanded_words.push(word.into());
                }
            }

            return expanded_words;
        } else if token_buffer.len() == 1 {
            match token_buffer[0] {
                WordToken::Array(ref elements, index) => {
                    return match index {
                        Index::None   => Array::new(),
                        Index::All    => array_expand(elements, expand_func),
                        Index::ID(id) =>
                            Some(array_nth(elements, expand_func, id))
                                .into_iter().collect(),
                        Index::Range(start, end) => array_range(elements, expand_func, start, end),
                    };
                },
                WordToken::ArrayVariable(array, quoted, index) => {
                    return match (expand_func.array)(array, index) {
                        Some(ref array) if quoted =>
                            Some(array.join(" ").into()).into_iter().collect(),
                        Some(array)               => array,
                        None                      => Array::new(),
                    };
                },
                WordToken::ArrayProcess(command, quoted, index) => {
                    let quoted = if reverse_quoting { !quoted } else { quoted };
                    match index {
                        Index::None => return Array::new(),
                        Index::All => {
                            expand_process(&mut output, command, quoted, Index::All, expand_func);
                            return output.split_whitespace()
                                .map(From::from)
                                .collect::<Array>();
                        },
                        Index::ID(id) => {
                            expand_process(&mut output, command, quoted, Index::All, expand_func);
                            return Some(
                                output.split_whitespace().nth(id)
                                    .unwrap_or_default()
                                    .into()
                            ).into_iter()
                                .collect();
                        }
                        Index::Range(start, end) => {
                            expand_process(&mut output, command, quoted, Index::All, expand_func);
                            return match end {
                                IndexEnd::ID(end) => output
                                    .split_whitespace()
                                    .skip(start)
                                    .take(end - start)
                                    .map(From::from)
                                    .collect::<Array>(),
                                IndexEnd::CatchAll => output
                                    .split_whitespace()
                                    .skip(start)
                                    .map(From::from)
                                    .collect::<Array>()
                            }
                        },
                    }
                },
                WordToken::ArrayMethod(ref array_method) => {
                    return array_method.handle_as_array(expand_func);
                },
                _ => ()
            }
        }

        for word in token_buffer {
            match *word {
                WordToken::Array(ref elements, index) => {
                    match index {
                        Index::None => (),
                        Index::All => {
                            let expanded = array_expand(elements, expand_func);
                            output.push_str(&expanded.join(" "));
                        },
                        Index::ID(id) => {
                            let expanded = array_nth(elements, expand_func, id);
                            output.push_str(&expanded);
                        },
                        Index::Range(start, end) => {
                            let expanded = array_range(elements, expand_func, start, end);
                            output.push_str(&expanded.join(" "));
                        },
                    };
                },
                WordToken::ArrayVariable(array, _, index) => {
                    if let Some(array) = (expand_func.array)(array, index) {
                        output.push_str(&array.join(" "));
                    }
                },
                WordToken::ArrayProcess(command, quoted, index) => {
                    let quoted = if reverse_quoting { !quoted } else { quoted };
                    match index {
                        Index::None => (),
                        Index::All => {
                            let mut temp = String::new();
                            expand_process(&mut temp, command, quoted, Index::All, expand_func);
                            let temp = temp.split_whitespace().collect::<Vec<&str>>();
                            output.push_str(&temp.join(" "));
                        },
                        Index::ID(id) => {
                            let mut temp = String::new();
                            expand_process(&mut temp, command, quoted, Index::All, expand_func);
                            output.push_str(temp.split_whitespace().nth(id).unwrap_or_default());
                        },
                        Index::Range(start, end) => {
                            let mut temp = String::new();
                            expand_process(&mut temp, command, quoted, Index::All, expand_func);
                            let temp = match end {
                                IndexEnd::ID(end) => temp.split_whitespace()
                                    .skip(start).take(end-start)
                                    .collect::<Vec<&str>>(),
                                IndexEnd::CatchAll => temp.split_whitespace()
                                    .skip(start).collect::<Vec<&str>>()
                            };
                            output.push_str(&temp.join(" "));
                        },
                    }
                },
                WordToken::ArrayMethod(ref array_method) => {
                    array_method.handle(&mut output, expand_func);
                },
                WordToken::StringMethod(method, variable, pattern, index) => {
                    let pattern = &expand_string(pattern, expand_func, false).join(" ");
                    match method {
                        "join" => if let Some(array) = (expand_func.array)(variable, Index::All) {
                            slice_string(&mut output, &array.join(pattern), index);
                        },
                        _ => {
                            let stderr = io::stderr();
                            let mut stderr = stderr.lock();
                            let _ = writeln!(stderr, "ion: invalid string method: {}", method);
                        }
                    }
                },
                WordToken::Brace(_) => unreachable!(),
                WordToken::Normal(text) | WordToken::Whitespace(text) => {
                    output.push_str(text);
                },
                WordToken::Process(command, quoted, index) => {
                    let quoted = if reverse_quoting { !quoted } else { quoted };
                    expand_process(&mut output, command, quoted, index, expand_func);
                }
                WordToken::Tilde(text) => output.push_str(match (expand_func.tilde)(text) {
                    Some(ref expanded) => expanded,
                    None               => text,
                }),
                WordToken::Variable(text, quoted, index) => {
                    let quoted = if reverse_quoting { !quoted } else { quoted };
                    let expanded = match (expand_func.variable)(text, quoted) {
                        Some(var) => var,
                        None          => continue
                    };

                    slice_string(&mut output, &expanded, index);
                },
            }
        }

        expanded_words.push(output.into());
    }

    expanded_words
}

// TODO: Write Nested Brace Tests

#[cfg(test)]
mod test {
    use super::*;

    macro_rules! functions {
        () => {
            ExpanderFunctions {
                tilde:    &|_| None,
                array:    &|_, _| None,
                variable: &|variable: &str, _| match variable {
                    "A" => Some("1".to_owned()),
                    "B" => Some("test".to_owned()),
                    "C" => Some("ing".to_owned()),
                    "D" => Some("1 2 3".to_owned()),
                    "FOO" => Some("FOO".to_owned()),
                    "BAR" => Some("BAR".to_owned()),
                    _   => None
                },
                command:  &|_, _| None
            }
        }
    }

    #[test]
    fn expand_variable_normal_variable() {
        let input = "$FOO:NOT:$BAR";
        let expected = "FOO:NOT:BAR";
        let expanded = expand_string(input, &functions!(), false);
        assert_eq!(Array::from_vec(vec![expected.to_owned()]), expanded);
    }

    #[test]
    fn expand_braces() {
        let line = "pro{digal,grammer,cessed,totype,cedures,ficiently,ving,spective,jections}";
        let expected = "prodigal programmer processed prototype procedures proficiently proving prospective projections";
        let expanded = expand_string(line, &functions!(), false);
        assert_eq!(
            expected.split_whitespace()
                .map(|x| x.to_owned())
                .collect::<Array>(),
            expanded
        );
    }

    #[test]
    fn expand_variables_with_colons() {
        let expanded = expand_string("$FOO:$BAR", &functions!(), false);
        assert_eq!(Array::from_vec(vec!["FOO:BAR".to_owned()]), expanded);
    }

    #[test]
    fn expand_multiple_variables() {
        let expanded = expand_string("${B}${C}...${D}", &functions!(), false);
        assert_eq!(Array::from_vec(vec!["testing...1 2 3".to_owned()]), expanded);
    }

    #[test]
    fn expand_variable_alongside_braces() {
        let line = "$A{1,2}";
        let expected = Array::from_vec(vec!["11".to_owned(), "12".to_owned()]);
        let expanded = expand_string(line, &functions!(), false);
        assert_eq!(expected, expanded);
    }

    #[test]
    fn expand_variable_within_braces() {
        let line = "1{$A,2}";
        let expected = Array::from_vec(vec!["11".to_owned(), "12".to_owned()]);
        let expanded = expand_string(line, &functions!(), false);
        assert_eq!(&expected, &expanded);
    }
}