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
// 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 dollar units.
//!
//! Note that the detail lexer for each type of dollar units in another
//! dedicated module.

use super::core::WordLexer;
use crate::parser::core::Result;
use crate::syntax::TextUnit;

impl WordLexer<'_, '_> {
    /// Parses a text unit that starts with `$`.
    ///
    /// If the next character is `$`, a parameter expansion, command
    /// substitution, or arithmetic expansion is parsed. Otherwise, no
    /// characters are consumed and the return value is `Ok(None)`.
    pub async fn dollar_unit(&mut self) -> Result<Option<TextUnit>> {
        let start_index = self.index();
        if !self.skip_if(|c| c == '$').await? {
            return Ok(None);
        }

        if let Some(result) = self.raw_param(start_index).await? {
            return Ok(Some(result));
        }
        if let Some(result) = self.braced_param(start_index).await? {
            return Ok(Some(TextUnit::BracedParam(result)));
        }
        if let Some(result) = self.arithmetic_expansion(start_index).await? {
            return Ok(Some(result));
        }
        if let Some(result) = self.command_substitution(start_index).await? {
            return Ok(Some(result));
        }

        // TODO maybe reject unrecognized dollar unit?
        self.rewind(start_index);
        Ok(None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parser::lex::Lexer;
    use crate::parser::lex::WordContext;
    use crate::source::Source;
    use crate::syntax::Literal;
    use crate::syntax::Param;
    use crate::syntax::SpecialParam;
    use crate::syntax::Text;
    use assert_matches::assert_matches;
    use futures_util::FutureExt;

    #[test]
    fn lexer_dollar_unit_no_dollar() {
        let mut lexer = Lexer::from_memory("foo", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap().unwrap();
        assert_eq!(result, None);

        let mut lexer = Lexer::from_memory("()", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap().unwrap();
        assert_eq!(result, None);
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(Some('(')));

        let mut lexer = Lexer::from_memory("", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap().unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn lexer_dollar_unit_dollar_followed_by_non_special() {
        let mut lexer = Lexer::from_memory("$;", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap().unwrap();
        assert_eq!(result, None);
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(Some('$')));

        let mut lexer = Lexer::from_memory("$&", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap().unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn lexer_dollar_unit_raw_special_parameter() {
        let mut lexer = Lexer::from_memory("$0", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap();
        let text_unit = result.unwrap().unwrap();
        assert_matches!(text_unit, TextUnit::RawParam { param, location } => {
            assert_eq!(param, Param::from(SpecialParam::Zero));
            assert_eq!(*location.code.value.borrow(), "$0");
            assert_eq!(location.code.start_line_number.get(), 1);
            assert_eq!(*location.code.source, Source::Unknown);
            assert_eq!(location.range, 0..2);
        });
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(None));
    }

    #[test]
    fn lexer_dollar_unit_command_substitution() {
        let mut lexer = Lexer::from_memory("$()", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let text_unit = lexer.dollar_unit().now_or_never().unwrap();
        let text_unit = text_unit.unwrap().unwrap();
        assert_matches!(text_unit, TextUnit::CommandSubst { location, content } => {
            assert_eq!(*location.code.value.borrow(), "$()");
            assert_eq!(location.code.start_line_number.get(), 1);
            assert_eq!(*location.code.source, Source::Unknown);
            assert_eq!(location.range, 0..3);
            assert_eq!(&*content, "");
        });
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(None));

        let mut lexer = Lexer::from_memory("$( foo bar )", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap();
        let text_unit = result.unwrap().unwrap();
        assert_matches!(text_unit, TextUnit::CommandSubst { location, content } => {
            assert_eq!(*location.code.value.borrow(), "$( foo bar )");
            assert_eq!(location.code.start_line_number.get(), 1);
            assert_eq!(*location.code.source, Source::Unknown);
            assert_eq!(location.range, 0..12);
            assert_eq!(&*content, " foo bar ");
        });
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(None));
    }

    #[test]
    fn lexer_dollar_unit_arithmetic_expansion() {
        let mut lexer = Lexer::from_memory("$((1))", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap();
        let text_unit = result.unwrap().unwrap();
        assert_matches!(text_unit, TextUnit::Arith { content, location } => {
            assert_eq!(content, Text(vec![Literal('1')]));
            assert_eq!(*location.code.value.borrow(), "$((1))");
            assert_eq!(location.code.start_line_number.get(), 1);
            assert_eq!(*location.code.source, Source::Unknown);
            assert_eq!(location.range, 0..6);
        });
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(None));
    }

    #[test]
    fn lexer_dollar_unit_line_continuation() {
        let mut lexer = Lexer::from_memory("$\\\n\\\n0", Source::Unknown);
        let mut lexer = WordLexer {
            lexer: &mut lexer,
            context: WordContext::Word,
        };
        let result = lexer.dollar_unit().now_or_never().unwrap();
        let text_unit = result.unwrap().unwrap();
        assert_matches!(text_unit, TextUnit::RawParam { param, .. } => {
            assert_eq!(param, Param::from(SpecialParam::Zero));
        });
        assert_eq!(lexer.peek_char().now_or_never().unwrap(), Ok(None));
    }
}