sway_parse/item/
item_use.rs

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
use crate::{Parse, ParseBracket, ParseResult, Parser};

use sway_ast::{Braces, ItemUse, UseTree};
use sway_error::parser_error::ParseErrorKind;
use sway_types::Spanned;

impl Parse for UseTree {
    fn parse(parser: &mut Parser) -> ParseResult<UseTree> {
        if let Some(imports) = Braces::try_parse(parser)? {
            return Ok(UseTree::Group { imports });
        }
        if let Some(star_token) = parser.take() {
            return Ok(UseTree::Glob { star_token });
        }
        let name = parser
            .take()
            .ok_or_else(|| parser.emit_error(ParseErrorKind::ExpectedImportNameGroupOrGlob))?;
        if let Some(as_token) = parser.take() {
            let alias = parser.parse()?;
            return Ok(UseTree::Rename {
                name,
                as_token,
                alias,
            });
        }
        if let Some(double_colon_token) = parser.take() {
            if let Ok(suffix) = parser.parse() {
                return Ok(UseTree::Path {
                    prefix: name,
                    double_colon_token,
                    suffix,
                });
            } else {
                // parser recovery for foo::
                return Ok(UseTree::Error {
                    spans: Box::new([name.span(), double_colon_token.span()]),
                });
            }
        }
        Ok(UseTree::Name { name })
    }
}

impl Parse for ItemUse {
    fn parse(parser: &mut Parser) -> ParseResult<ItemUse> {
        let use_token = parser.parse()?;
        let root_import = parser.take();
        let tree = parser.parse()?;
        let semicolon_token = parser.parse()?;
        Ok(ItemUse {
            visibility: None,
            use_token,
            root_import,
            tree,
            semicolon_token,
        })
    }
}