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
use crate::{
    build_config::BuildConfig,
    error::{ok, CompileResult},
    parser::Rule,
    CodeBlock, Expression,
};

use sway_types::span::Span;

use pest::iterators::Pair;

/// A parsed while loop. Contains the `condition`, which is defined from an [Expression], and the `body` from a [CodeBlock].
#[derive(Debug, Clone)]
pub struct WhileLoop {
    pub(crate) condition: Expression,
    pub(crate) body: CodeBlock,
}

impl WhileLoop {
    pub(crate) fn parse_from_pair(
        pair: Pair<Rule>,
        config: Option<&BuildConfig>,
    ) -> CompileResult<Self> {
        let path = config.map(|c| c.path());
        let mut warnings = Vec::new();
        let mut errors = Vec::new();
        let mut iter = pair.into_inner();
        let _while_keyword = iter.next().unwrap();
        let condition = iter.next().unwrap();
        let body = iter.next().unwrap();
        let whole_block_span = Span {
            span: body.as_span(),
            path: path.clone(),
        };

        let condition = check!(
            Expression::parse_from_pair(condition.clone(), config),
            Expression::Tuple {
                fields: vec![],
                span: Span {
                    span: condition.as_span(),
                    path,
                }
            },
            warnings,
            errors
        );

        let body = check!(
            CodeBlock::parse_from_pair(body, config),
            CodeBlock {
                contents: Default::default(),
                whole_block_span,
            },
            warnings,
            errors
        );

        ok(WhileLoop { condition, body }, warnings, errors)
    }
}