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
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2020 WATANABE Yuki
//
// 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/>.

//! Part of the lexer that parses operators.

use super::core::Lexer;
use super::core::Token;
use super::core::TokenId;
use crate::parser::core::Result;
use crate::syntax::Literal;
use crate::syntax::Unquoted;
use crate::syntax::Word;
use std::fmt;
use std::fmt::Write;
use std::future::Future;
use std::pin::Pin;

/// Operator token identifier.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operator {
    /// Newline
    Newline,
    /// `&`
    And,
    /// `&&`
    AndAnd,
    /// `(`
    OpenParen,
    /// `)`
    CloseParen,
    /// `;`
    Semicolon,
    /// `;;`
    SemicolonSemicolon,
    /// `<`
    Less,
    /// `<&`
    LessAnd,
    /// `<(`
    LessOpenParen,
    /// `<<`
    LessLess,
    /// `<<-`
    LessLessDash,
    /// `<<<`
    LessLessLess,
    /// `<>`
    LessGreater,
    /// `>`
    Greater,
    /// `>&`
    GreaterAnd,
    /// `>(`
    GreaterOpenParen,
    /// `>>`
    GreaterGreater,
    /// `>>|`
    GreaterGreaterBar,
    /// `>|`
    GreaterBar,
    /// `|`
    Bar,
    /// `||`
    BarBar,
}

impl Operator {
    /// Determines if this token can be a delimiter of a clause.
    ///
    /// This function returns `true` for `CloseParen` and `SemicolonSemicolon`,
    /// and `false` for others.
    pub fn is_clause_delimiter(self) -> bool {
        use Operator::*;
        match self {
            CloseParen | SemicolonSemicolon => true,
            Newline | And | AndAnd | OpenParen | Semicolon | Less | LessAnd | LessOpenParen
            | LessLess | LessLessDash | LessLessLess | LessGreater | Greater | GreaterAnd
            | GreaterOpenParen | GreaterGreater | GreaterGreaterBar | GreaterBar | Bar | BarBar => {
                false
            }
        }
    }
}

impl fmt::Display for Operator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Operator::*;
        match self {
            Newline => f.write_char('\n'),
            And => f.write_char('&'),
            AndAnd => f.write_str("&&"),
            OpenParen => f.write_char('('),
            CloseParen => f.write_char(')'),
            Semicolon => f.write_char(';'),
            SemicolonSemicolon => f.write_str(";;"),
            Less => f.write_char('<'),
            LessAnd => f.write_str("<&"),
            LessOpenParen => f.write_str("<("),
            LessLess => f.write_str("<<"),
            LessLessDash => f.write_str("<<-"),
            LessLessLess => f.write_str("<<<"),
            LessGreater => f.write_str("<>"),
            Greater => f.write_char('>'),
            GreaterAnd => f.write_str(">&"),
            GreaterOpenParen => f.write_str(">("),
            GreaterGreater => f.write_str(">>"),
            GreaterGreaterBar => f.write_str(">>|"),
            GreaterBar => f.write_str(">|"),
            Bar => f.write_char('|'),
            BarBar => f.write_str("||"),
        }
    }
}

/// Trie data structure that defines a set of operator tokens.
///
/// This struct represents a node of the trie. A node is a sorted array of [`Edge`]s.
#[derive(Copy, Clone, Debug)]
pub struct Trie(&'static [Edge]);

/// Edge of a [`Trie`].
#[derive(Copy, Clone, Debug)]
pub struct Edge {
    /// Character value of this edge.
    pub key: char,
    /// Final operator token that is delimited after taking this edge if there are no longer
    /// matches.
    pub value: Option<Operator>,
    /// Sub-trie containing values for keys that have the common prefix.
    pub next: Trie,
}

impl Trie {
    /// Tests if this trie is empty.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Finds an edge for the given key.
    pub fn edge(&self, key: char) -> Option<&Edge> {
        self.0
            .binary_search_by_key(&key, |edge| edge.key)
            .ok()
            .map(|i| &self.0[i])
    }
}

/// Trie containing all the operators.
pub const OPERATORS: Trie = Trie(&[
    Edge {
        key: '\n',
        value: Some(Operator::Newline),
        next: NONE,
    },
    Edge {
        key: '&',
        value: Some(Operator::And),
        next: AND,
    },
    Edge {
        key: '(',
        value: Some(Operator::OpenParen),
        next: NONE,
    },
    Edge {
        key: ')',
        value: Some(Operator::CloseParen),
        next: NONE,
    },
    Edge {
        key: ';',
        value: Some(Operator::Semicolon),
        next: SEMICOLON,
    },
    Edge {
        key: '<',
        value: Some(Operator::Less),
        next: LESS,
    },
    Edge {
        key: '>',
        value: Some(Operator::Greater),
        next: GREATER,
    },
    Edge {
        key: '|',
        value: Some(Operator::Bar),
        next: BAR,
    },
]);

/// Trie of the operators that start with `&`.
const AND: Trie = Trie(&[Edge {
    key: '&',
    value: Some(Operator::AndAnd),
    next: NONE,
}]);

/// Trie of the operators that start with `;`.
const SEMICOLON: Trie = Trie(&[Edge {
    key: ';',
    value: Some(Operator::SemicolonSemicolon),
    next: NONE,
}]);

/// Trie of the operators that start with `<`.
const LESS: Trie = Trie(&[
    Edge {
        key: '&',
        value: Some(Operator::LessAnd),
        next: NONE,
    },
    Edge {
        key: '(',
        value: Some(Operator::LessOpenParen),
        next: NONE,
    },
    Edge {
        key: '<',
        value: Some(Operator::LessLess),
        next: LESS_LESS,
    },
    Edge {
        key: '>',
        value: Some(Operator::LessGreater),
        next: NONE,
    },
]);

/// Trie of the operators that start with `<<`.
const LESS_LESS: Trie = Trie(&[
    Edge {
        key: '-',
        value: Some(Operator::LessLessDash),
        next: NONE,
    },
    Edge {
        key: '<',
        value: Some(Operator::LessLessLess),
        next: NONE,
    },
]);

/// Trie of the operators that start with `>`.
const GREATER: Trie = Trie(&[
    Edge {
        key: '&',
        value: Some(Operator::GreaterAnd),
        next: NONE,
    },
    Edge {
        key: '(',
        value: Some(Operator::GreaterOpenParen),
        next: NONE,
    },
    Edge {
        key: '>',
        value: Some(Operator::GreaterGreater),
        next: GREATER_GREATER,
    },
    Edge {
        key: '|',
        value: Some(Operator::GreaterBar),
        next: NONE,
    },
]);

/// Trie of the operators that start with `>>`.
const GREATER_GREATER: Trie = Trie(&[Edge {
    key: '|',
    value: Some(Operator::GreaterGreaterBar),
    next: NONE,
}]);

/// Trie of the operators that start with `|`.
const BAR: Trie = Trie(&[Edge {
    key: '|',
    value: Some(Operator::BarBar),
    next: NONE,
}]);

/// Trie containing nothing.
const NONE: Trie = Trie(&[]);

/// Tests whether the given character is the first character of an operator.
pub fn is_operator_char(c: char) -> bool {
    OPERATORS.edge(c).is_some()
}

/// Return type for [`Lexer::operator_tail`]
struct OperatorTail {
    pub operator: Operator,
    pub reversed_key: Vec<char>,
}

impl Lexer<'_> {
    /// Parses an operator that matches a key in the given trie, if any.
    fn operator_tail(
        &mut self,
        trie: Trie,
    ) -> Pin<Box<dyn Future<Output = Result<Option<OperatorTail>>> + '_>> {
        Box::pin(async move {
            if trie.is_empty() {
                return Ok(None);
            }

            let c = match self.peek_char().await? {
                None => return Ok(None),
                Some(c) => c,
            };
            let edge = match trie.edge(c) {
                None => return Ok(None),
                Some(edge) => edge,
            };

            let old_index = self.index();
            self.consume_char();

            if let Some(mut operator_tail) = self.operator_tail(edge.next).await? {
                operator_tail.reversed_key.push(c);
                return Ok(Some(operator_tail));
            }

            match edge.value {
                None => {
                    self.rewind(old_index);
                    Ok(None)
                }
                Some(operator) => Ok(Some(OperatorTail {
                    operator,
                    reversed_key: vec![c],
                })),
            }
        })
    }

    /// Parses an operator token.
    pub async fn operator(&mut self) -> Result<Option<Token>> {
        let index = self.index();
        self.operator_tail(OPERATORS).await.map(|o| {
            o.map(|ot| {
                let OperatorTail {
                    operator,
                    reversed_key,
                } = ot;
                let units = reversed_key
                    .into_iter()
                    .rev()
                    .map(|c| Unquoted(Literal(c)))
                    .collect::<Vec<_>>();
                let location = self.location_range(index..self.index());
                let word = Word { units, location };
                let id = TokenId::Operator(operator);
                Token { word, id, index }
            })
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::Context;
    use crate::input::Input;
    use crate::source::Source;
    use crate::syntax::TextUnit;
    use crate::syntax::WordUnit;
    use futures_executor::block_on;
    use std::num::NonZeroU64;

    fn ensure_sorted(trie: &Trie) {
        assert!(
            trie.0.windows(2).all(|pair| pair[0].key < pair[1].key),
            "The trie should be sorted: {:?}",
            trie
        );

        for edge in trie.0 {
            ensure_sorted(&edge.next);
        }
    }

    #[test]
    fn tries_are_sorted() {
        ensure_sorted(&OPERATORS);
    }

    #[test]
    fn lexer_operator_longest_match() {
        let mut lexer = Lexer::from_memory("<<-", Source::Unknown);

        let t = block_on(lexer.operator()).unwrap().unwrap();
        assert_eq!(t.word.units.len(), 3);
        assert_eq!(t.word.units[0], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(t.word.units[1], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(t.word.units[2], WordUnit::Unquoted(TextUnit::Literal('-')));
        assert_eq!(*t.word.location.code.value.borrow(), "<<-");
        assert_eq!(t.word.location.code.start_line_number.get(), 1);
        assert_eq!(t.word.location.code.source, Source::Unknown);
        assert_eq!(t.word.location.range, 0..3);
        assert_eq!(t.id, TokenId::Operator(Operator::LessLessDash));

        assert_eq!(block_on(lexer.peek_char()), Ok(None));
    }

    #[test]
    fn lexer_operator_delimited_by_another_operator() {
        let mut lexer = Lexer::from_memory("<<>", Source::Unknown);

        let t = block_on(lexer.operator()).unwrap().unwrap();
        assert_eq!(t.word.units.len(), 2);
        assert_eq!(t.word.units[0], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(t.word.units[1], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(*t.word.location.code.value.borrow(), "<<>");
        assert_eq!(t.word.location.code.start_line_number.get(), 1);
        assert_eq!(t.word.location.code.source, Source::Unknown);
        assert_eq!(t.word.location.range, 0..2);
        assert_eq!(t.id, TokenId::Operator(Operator::LessLess));

        assert_eq!(block_on(lexer.location()).unwrap().range, 2..3);
    }

    #[test]
    fn lexer_operator_delimited_by_eof() {
        let mut lexer = Lexer::from_memory("<<", Source::Unknown);

        let t = block_on(lexer.operator()).unwrap().unwrap();
        assert_eq!(t.word.units.len(), 2);
        assert_eq!(t.word.units[0], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(t.word.units[1], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(*t.word.location.code.value.borrow(), "<<");
        assert_eq!(t.word.location.code.start_line_number.get(), 1);
        assert_eq!(t.word.location.code.source, Source::Unknown);
        assert_eq!(t.word.location.range, 0..2);
        assert_eq!(t.id, TokenId::Operator(Operator::LessLess));

        assert_eq!(block_on(lexer.peek_char()), Ok(None));
    }

    #[test]
    fn lexer_operator_containing_line_continuations() {
        let mut lexer = Lexer::from_memory("\\\n\\\n<\\\n<\\\n>", Source::Unknown);

        let t = block_on(lexer.operator()).unwrap().unwrap();
        assert_eq!(t.word.units.len(), 2);
        assert_eq!(t.word.units[0], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(t.word.units[1], WordUnit::Unquoted(TextUnit::Literal('<')));
        assert_eq!(*t.word.location.code.value.borrow(), "\\\n\\\n<\\\n<\\\n>");
        assert_eq!(t.word.location.code.start_line_number.get(), 1);
        assert_eq!(t.word.location.code.source, Source::Unknown);
        assert_eq!(t.word.location.range, 0..10);
        assert_eq!(t.id, TokenId::Operator(Operator::LessLess));

        assert_eq!(block_on(lexer.peek_char()), Ok(Some('>')));
    }

    #[test]
    fn lexer_operator_none() {
        let mut lexer = Lexer::from_memory("\\\n ", Source::Unknown);

        let r = block_on(lexer.operator()).unwrap();
        assert!(r.is_none(), "Unexpected success: {:?}", r);
    }

    #[test]
    fn lexer_operator_should_not_peek_beyond_newline() {
        struct OneLineInput(Option<String>);
        #[async_trait::async_trait(?Send)]
        impl Input for OneLineInput {
            async fn next_line(&mut self, _: &Context) -> crate::input::Result {
                if let Some(line) = self.0.take() {
                    Ok(line)
                } else {
                    panic!("The second line should not be read")
                }
            }
        }

        let line_number = NonZeroU64::new(1).unwrap();
        let mut lexer = Lexer::new(
            Box::new(OneLineInput(Some("\n".to_owned()))),
            line_number,
            Source::Unknown,
        );

        let t = block_on(lexer.operator()).unwrap().unwrap();
        assert_eq!(t.word.units, [WordUnit::Unquoted(TextUnit::Literal('\n'))]);
        assert_eq!(*t.word.location.code.value.borrow(), "\n");
        assert_eq!(t.word.location.code.start_line_number.get(), 1);
        assert_eq!(t.word.location.code.source, Source::Unknown);
        assert_eq!(t.word.location.range, 0..1);
        assert_eq!(t.id, TokenId::Operator(Operator::Newline));
    }
}