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

//! Syntax parser for if command

use super::core::Parser;
use super::core::Result;
use super::error::Error;
use super::error::SyntaxError;
use super::fill::MissingHereDoc;
use super::lex::Keyword::{Elif, Else, Fi, If, Then};
use super::lex::TokenId::Token;
use crate::syntax::CompoundCommand;
use crate::syntax::ElifThen;

impl Parser<'_, '_> {
    /// Parses an elif-then clause.
    ///
    /// Returns `Ok(None)` if the next token is not `elif`.
    async fn elif_then_clause(&mut self) -> Result<Option<ElifThen<MissingHereDoc>>> {
        if self.peek_token().await?.id != Token(Some(Elif)) {
            return Ok(None);
        }

        let elif = self.take_token_raw().await?;

        let condition = self.maybe_compound_list_boxed().await?;
        let then = self.take_token_raw().await?;

        // TODO allow empty condition if not POSIXly-correct
        if condition.0.is_empty() {
            let cause = SyntaxError::EmptyElifCondition.into();
            let location = then.word.location;
            return Err(Error { cause, location });
        }
        if then.id != Token(Some(Then)) {
            let elif_location = elif.word.location;
            let cause = SyntaxError::ElifMissingThen { elif_location }.into();
            let location = then.word.location;
            return Err(Error { cause, location });
        }

        let body = self.maybe_compound_list_boxed().await?;
        // TODO allow empty body if not POSIXly-correct
        if body.0.is_empty() {
            let cause = SyntaxError::EmptyElifBody.into();
            let location = self.take_token_raw().await?.word.location;
            return Err(Error { cause, location });
        }

        Ok(Some(ElifThen { condition, body }))
    }

    /// Parses an if conditional construct.
    ///
    /// The next token must be the `if` reserved word.
    ///
    /// # Panics
    ///
    /// If the first token is not `if`.
    pub async fn if_command(&mut self) -> Result<CompoundCommand<MissingHereDoc>> {
        let open = self.take_token_raw().await?;
        assert_eq!(open.id, Token(Some(If)));

        let condition = self.maybe_compound_list_boxed().await?;
        let then = self.take_token_raw().await?;

        // TODO allow empty condition if not POSIXly-correct
        if condition.0.is_empty() {
            let cause = SyntaxError::EmptyIfCondition.into();
            let location = then.word.location;
            return Err(Error { cause, location });
        }
        if then.id != Token(Some(Then)) {
            let if_location = open.word.location;
            let cause = SyntaxError::IfMissingThen { if_location }.into();
            let location = then.word.location;
            return Err(Error { cause, location });
        }

        let body = self.maybe_compound_list_boxed().await?;
        // TODO allow empty body if not POSIXly-correct
        if body.0.is_empty() {
            let cause = SyntaxError::EmptyIfBody.into();
            let location = self.take_token_raw().await?.word.location;
            return Err(Error { cause, location });
        }

        let mut elifs = Vec::new();
        while let Some(elif) = self.elif_then_clause().await? {
            elifs.push(elif);
        }

        let r#else = if self.peek_token().await?.id == Token(Some(Else)) {
            self.take_token_raw().await?;
            let content = self.maybe_compound_list_boxed().await?;
            // TODO allow empty else if not POSIXly-correct
            if content.0.is_empty() {
                let cause = SyntaxError::EmptyElse.into();
                let location = self.take_token_raw().await?.word.location;
                return Err(Error { cause, location });
            }
            Some(content)
        } else {
            None
        };

        let fi = self.take_token_raw().await?;
        if fi.id != Token(Some(Fi)) {
            let opening_location = open.word.location;
            let cause = SyntaxError::UnclosedIf { opening_location }.into();
            let location = fi.word.location;
            return Err(Error { cause, location });
        }

        Ok(CompoundCommand::If {
            condition,
            body,
            elifs,
            r#else,
        })
    }
}

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

    #[test]
    fn parser_if_command_minimum() {
        let mut lexer = Lexer::from_memory("if a; then b; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let result = block_on(parser.compound_command()).unwrap().unwrap();
        assert_matches!(result, CompoundCommand::If { condition, body, elifs, r#else } => {
            assert_eq!(condition.to_string(), "a");
            assert_eq!(body.to_string(), "b");
            assert_eq!(elifs, []);
            assert_eq!(r#else, None);
        });

        let next = block_on(parser.peek_token()).unwrap();
        assert_eq!(next.id, EndOfInput);
    }

    #[test]
    fn parser_if_command_one_elif() {
        let mut lexer = Lexer::from_memory(
            "if\ntrue\nthen\nfalse\n\nelif x; then y& fi",
            Source::Unknown,
        );
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let result = block_on(parser.compound_command()).unwrap().unwrap();
        assert_matches!(result, CompoundCommand::If { condition, body, elifs, r#else } => {
            assert_eq!(condition.to_string(), "true");
            assert_eq!(body.to_string(), "false");
            assert_eq!(elifs.len(), 1);
            assert_eq!(elifs[0].to_string(), "elif x; then y&");
            assert_eq!(r#else, None);
        });

        let next = block_on(parser.peek_token()).unwrap();
        assert_eq!(next.id, EndOfInput);
    }

    #[test]
    fn parser_if_command_many_elifs() {
        let mut lexer = Lexer::from_memory(
            "if a; then b; elif c; then d; elif e 1; e 2& then f 1; f 2& elif g; then h; fi",
            Source::Unknown,
        );
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let result = block_on(parser.compound_command()).unwrap().unwrap();
        assert_matches!(result, CompoundCommand::If { condition, body, elifs, r#else } => {
            assert_eq!(condition.to_string(), "a");
            assert_eq!(body.to_string(), "b");
            assert_eq!(elifs.len(), 3);
            assert_eq!(elifs[0].to_string(), "elif c; then d");
            assert_eq!(elifs[1].to_string(), "elif e 1; e 2& then f 1; f 2&");
            assert_eq!(elifs[2].to_string(), "elif g; then h");
            assert_eq!(r#else, None);
        });

        let next = block_on(parser.peek_token()).unwrap();
        assert_eq!(next.id, EndOfInput);
    }

    #[test]
    fn parser_if_command_else() {
        let mut lexer = Lexer::from_memory("if a; then b; else c; d; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let result = block_on(parser.compound_command()).unwrap().unwrap();
        assert_matches!(result, CompoundCommand::If { condition, body, elifs, r#else } => {
            assert_eq!(condition.to_string(), "a");
            assert_eq!(body.to_string(), "b");
            assert_eq!(elifs, []);
            assert_eq!(r#else.unwrap().to_string(), "c; d");
        });

        let next = block_on(parser.peek_token()).unwrap();
        assert_eq!(next.id, EndOfInput);
    }

    #[test]
    fn parser_if_command_elif_and_else() {
        let mut lexer =
            Lexer::from_memory("if 1; then 2; elif 3; then 4; else 5; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let result = block_on(parser.compound_command()).unwrap().unwrap();
        assert_matches!(result, CompoundCommand::If { condition, body, elifs, r#else } => {
            assert_eq!(condition.to_string(), "1");
            assert_eq!(body.to_string(), "2");
            assert_eq!(elifs.len(), 1);
            assert_eq!(elifs[0].to_string(), "elif 3; then 4");
            assert_eq!(r#else.unwrap().to_string(), "5");
        });

        let next = block_on(parser.peek_token()).unwrap();
        assert_eq!(next.id, EndOfInput);
    }

    #[test]
    fn parser_if_command_without_then_after_if() {
        let mut lexer = Lexer::from_memory(" if :; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_matches!(e.cause, ErrorCause::Syntax(SyntaxError::IfMissingThen { if_location }) => {
            assert_eq!(*if_location.code.value.borrow(), " if :; fi");
            assert_eq!(if_location.code.start_line_number.get(), 1);
            assert_eq!(if_location.code.source, Source::Unknown);
            assert_eq!(if_location.index, 1);
        });
        assert_eq!(*e.location.code.value.borrow(), " if :; fi");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 7);
    }

    #[test]
    fn parser_if_command_without_then_after_elif() {
        let mut lexer = Lexer::from_memory("if a; then b; elif c; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_matches!(e.cause,
            ErrorCause::Syntax(SyntaxError::ElifMissingThen { elif_location }) => {
            assert_eq!(*elif_location.code.value.borrow(), "if a; then b; elif c; fi");
            assert_eq!(elif_location.code.start_line_number.get(), 1);
            assert_eq!(elif_location.code.source, Source::Unknown);
            assert_eq!(elif_location.index, 14);
        });
        assert_eq!(*e.location.code.value.borrow(), "if a; then b; elif c; fi");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 22);
    }

    #[test]
    fn parser_if_command_without_fi() {
        let mut lexer = Lexer::from_memory("  if :; then :; }", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_matches!(e.cause,
            ErrorCause::Syntax(SyntaxError::UnclosedIf { opening_location }) => {
            assert_eq!(*opening_location.code.value.borrow(), "  if :; then :; }");
            assert_eq!(opening_location.code.start_line_number.get(), 1);
            assert_eq!(opening_location.code.source, Source::Unknown);
            assert_eq!(opening_location.index, 2);
        });
        assert_eq!(*e.location.code.value.borrow(), "  if :; then :; }");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 16);
    }

    #[test]
    fn parser_if_command_empty_condition() {
        let mut lexer = Lexer::from_memory("   if then :; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_eq!(e.cause, ErrorCause::Syntax(SyntaxError::EmptyIfCondition));
        assert_eq!(*e.location.code.value.borrow(), "   if then :; fi");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 6);
    }

    #[test]
    fn parser_if_command_empty_body() {
        let mut lexer = Lexer::from_memory("if :; then fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_eq!(e.cause, ErrorCause::Syntax(SyntaxError::EmptyIfBody));
        assert_eq!(*e.location.code.value.borrow(), "if :; then fi");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 11);
    }

    #[test]
    fn parser_if_command_empty_elif_condition() {
        let mut lexer = Lexer::from_memory("if :; then :; elif then :; fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_eq!(e.cause, ErrorCause::Syntax(SyntaxError::EmptyElifCondition));
        assert_eq!(
            *e.location.code.value.borrow(),
            "if :; then :; elif then :; fi"
        );
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 19);
    }

    #[test]
    fn parser_if_command_empty_elif_body() {
        let mut lexer = Lexer::from_memory("if :; then :; elif :; then fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_eq!(e.cause, ErrorCause::Syntax(SyntaxError::EmptyElifBody));
        assert_eq!(
            *e.location.code.value.borrow(),
            "if :; then :; elif :; then fi"
        );
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 27);
    }

    #[test]
    fn parser_if_command_empty_else() {
        let mut lexer = Lexer::from_memory("if :; then :; else fi", Source::Unknown);
        let aliases = Default::default();
        let mut parser = Parser::new(&mut lexer, &aliases);

        let e = block_on(parser.compound_command()).unwrap_err();
        assert_eq!(e.cause, ErrorCause::Syntax(SyntaxError::EmptyElse));
        assert_eq!(*e.location.code.value.borrow(), "if :; then :; else fi");
        assert_eq!(e.location.code.start_line_number.get(), 1);
        assert_eq!(e.location.code.source, Source::Unknown);
        assert_eq!(e.location.index, 19);
    }
}