yash_syntax/parser/lex/
command_subst.rs

1// This file is part of yash, an extended POSIX shell.
2// Copyright (C) 2020 WATANABE Yuki
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17//! Part of the lexer that parses command substitutions
18
19use super::core::Lexer;
20use crate::parser::core::Result;
21use crate::parser::error::Error;
22use crate::parser::error::SyntaxError;
23use crate::syntax::TextUnit;
24
25impl Lexer<'_> {
26    /// Parses a command substitution of the form `$(...)`.
27    ///
28    /// The initial `$` must have been consumed before calling this function.
29    /// In this function, the next character is examined to see if it begins a
30    /// command substitution. If it is `(`, the following characters are parsed
31    /// as commands to find a matching `)`, which will be consumed before this
32    /// function returns. Otherwise, no characters are consumed and the return
33    /// value is `Ok(None)`.
34    ///
35    /// The `start_index` parameter should be the index for the initial `$`. It is
36    /// used to construct the result, but this function does not check if it
37    /// actually points to the `$`.
38    pub async fn command_substitution(&mut self, start_index: usize) -> Result<Option<TextUnit>> {
39        let opening_location = match self.consume_char_if(|c| c == '(').await? {
40            Some(ch) => ch.location.clone(),
41            None => return Ok(None),
42        };
43
44        let content = self.inner_program_boxed().await?.into();
45
46        if !self.skip_if(|c| c == ')').await? {
47            // TODO Return a better error depending on the token id of the next token
48            let cause = SyntaxError::UnclosedCommandSubstitution { opening_location }.into();
49            let location = self.location().await?.clone();
50            return Err(Error { cause, location });
51        }
52
53        let location = self.location_range(start_index..self.index());
54        Ok(Some(TextUnit::CommandSubst { content, location }))
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::parser::error::ErrorCause;
62    use crate::source::Source;
63    use assert_matches::assert_matches;
64    use futures_util::FutureExt;
65
66    #[test]
67    fn lexer_command_substitution_success() {
68        let mut lexer = Lexer::with_code("$( foo bar )baz");
69        lexer.peek_char().now_or_never().unwrap().unwrap();
70        lexer.consume_char();
71
72        let result = lexer.command_substitution(0).now_or_never().unwrap();
73        let text_unit = result.unwrap().unwrap();
74        assert_matches!(text_unit, TextUnit::CommandSubst { location, content } => {
75            assert_eq!(*location.code.value.borrow(), "$( foo bar )baz");
76            assert_eq!(location.code.start_line_number.get(), 1);
77            assert_eq!(*location.code.source, Source::Unknown);
78            assert_eq!(location.range, 0..12);
79            assert_eq!(&*content, " foo bar ");
80        });
81
82        let next = lexer.location().now_or_never().unwrap().unwrap();
83        assert_eq!(*next.code.value.borrow(), "$( foo bar )baz");
84        assert_eq!(next.code.start_line_number.get(), 1);
85        assert_eq!(*next.code.source, Source::Unknown);
86        assert_eq!(next.range, 12..13);
87    }
88
89    #[test]
90    fn lexer_command_substitution_none() {
91        let mut lexer = Lexer::with_code("$ foo bar )baz");
92        lexer.peek_char().now_or_never().unwrap().unwrap();
93        lexer.consume_char();
94
95        let result = lexer.command_substitution(0).now_or_never().unwrap();
96        let text_unit = result.unwrap();
97        assert_eq!(text_unit, None);
98
99        let next = lexer.location().now_or_never().unwrap().unwrap();
100        assert_eq!(*next.code.value.borrow(), "$ foo bar )baz");
101        assert_eq!(next.code.start_line_number.get(), 1);
102        assert_eq!(*next.code.source, Source::Unknown);
103        assert_eq!(next.range, 1..2);
104    }
105
106    #[test]
107    fn lexer_command_substitution_unclosed() {
108        let mut lexer = Lexer::with_code("$( foo bar baz");
109        lexer.peek_char().now_or_never().unwrap().unwrap();
110        lexer.consume_char();
111
112        let result = lexer.command_substitution(0).now_or_never().unwrap();
113        let e = result.unwrap_err();
114        assert_matches!(e.cause,
115            ErrorCause::Syntax(SyntaxError::UnclosedCommandSubstitution { opening_location }) => {
116            assert_eq!(*opening_location.code.value.borrow(), "$( foo bar baz");
117            assert_eq!(opening_location.code.start_line_number.get(), 1);
118            assert_eq!(*opening_location.code.source, Source::Unknown);
119            assert_eq!(opening_location.range, 1..2);
120        });
121        assert_eq!(*e.location.code.value.borrow(), "$( foo bar baz");
122        assert_eq!(e.location.code.start_line_number.get(), 1);
123        assert_eq!(*e.location.code.source, Source::Unknown);
124        assert_eq!(e.location.range, 14..14);
125    }
126}