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
// 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 command substitutions.

use super::core::Lexer;
use crate::parser::core::Result;
use crate::parser::error::Error;
use crate::parser::error::SyntaxError;
use crate::source::Location;
use crate::syntax::TextUnit;

impl Lexer<'_> {
    /// Parses a command substitution of the form `$(...)`.
    ///
    /// The initial `$` must have been consumed before calling this function.
    /// In this function, the next character is examined to see if it begins a
    /// command substitution. If it is `(`, the following characters are parsed
    /// as commands to find a matching `)`, which will be consumed before this
    /// function returns. Otherwise, no characters are consumed and the return
    /// value is `Ok(None)`.
    ///
    /// `opening_location` should be the location of the initial `$`. It is used
    /// to construct the result, but this function does not check if it actually
    /// is a location of `$`.
    pub async fn command_substitution(
        &mut self,
        opening_location: Location,
    ) -> Result<Option<TextUnit>> {
        if !self.skip_if(|c| c == '(').await? {
            return Ok(None);
        }

        let content = self.inner_program_boxed().await?;

        if !self.skip_if(|c| c == ')').await? {
            // TODO Return a better error depending on the token id of the next token
            let cause = SyntaxError::UnclosedCommandSubstitution { opening_location }.into();
            let location = self.location().await?.clone();
            return Err(Error { cause, location });
        }

        let location = opening_location;
        Ok(Some(TextUnit::CommandSubst { content, location }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::error::ErrorCause;
    use crate::source::Source;
    use assert_matches::assert_matches;
    use futures_executor::block_on;

    #[test]
    fn lexer_command_substitution_success() {
        let mut lexer = Lexer::from_memory("( foo bar )baz", Source::Unknown);
        let location = Location::dummy("X");

        let result = block_on(lexer.command_substitution(location))
            .unwrap()
            .unwrap();
        assert_matches!(result, TextUnit::CommandSubst { location, content } => {
            assert_eq!(*location.code.value.borrow(), "X");
            assert_eq!(location.code.start_line_number.get(), 1);
            assert_eq!(location.code.source, Source::Unknown);
            assert_eq!(location.index, 0);
            assert_eq!(content, " foo bar ");
        });

        let next = block_on(lexer.location()).unwrap();
        assert_eq!(*next.code.value.borrow(), "( foo bar )baz");
        assert_eq!(next.code.start_line_number.get(), 1);
        assert_eq!(next.code.source, Source::Unknown);
        assert_eq!(next.index, 11);
    }

    #[test]
    fn lexer_command_substitution_none() {
        let mut lexer = Lexer::from_memory(" foo bar )baz", Source::Unknown);
        let location = Location::dummy("Y");

        let result = block_on(lexer.command_substitution(location)).unwrap();
        assert_eq!(result, None);

        let next = block_on(lexer.location()).unwrap();
        assert_eq!(*next.code.value.borrow(), " foo bar )baz");
        assert_eq!(next.code.start_line_number.get(), 1);
        assert_eq!(next.code.source, Source::Unknown);
        assert_eq!(next.index, 0);
    }

    #[test]
    fn lexer_command_substitution_unclosed() {
        let mut lexer = Lexer::from_memory("( foo bar baz", Source::Unknown);
        let location = Location::dummy("Z");

        let e = block_on(lexer.command_substitution(location)).unwrap_err();
        assert_matches!(e.cause,
            ErrorCause::Syntax(SyntaxError::UnclosedCommandSubstitution { opening_location }) => {
            assert_eq!(*opening_location.code.value.borrow(), "Z");
            assert_eq!(opening_location.code.start_line_number.get(), 1);
            assert_eq!(opening_location.code.source, Source::Unknown);
            assert_eq!(opening_location.index, 0);
        });
        assert_eq!(*e.location.code.value.borrow(), "( foo bar baz");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 13);
    }
}