microcad_lang/parse/
use.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4use crate::{parse::*, parser::*, syntax::*};
5
6impl Parse for UseDeclaration {
7    fn parse(pair: Pair) -> ParseResult<Self> {
8        Parser::ensure_rule(&pair, Rule::use_declaration);
9
10        let visibility = crate::find_rule!(pair, visibility)?;
11        let mut inner = pair.inner();
12        let first = inner.next().expect("Expected use declaration element");
13
14        match first.as_rule() {
15            Rule::qualified_name => Ok(Self::Use(visibility, QualifiedName::parse(first)?)),
16            Rule::use_all => {
17                let inner = first.inner().next().expect("Expected qualified name");
18                Ok(Self::UseAll(visibility, QualifiedName::parse(inner)?))
19            }
20            Rule::use_alias => {
21                let mut inner = first.inner();
22                let name = QualifiedName::parse(inner.next().expect("Expected qualified name"))?;
23                let alias = Identifier::parse(inner.next().expect("Expected identifier"))?;
24                Ok(Self::UseAlias(visibility, name, alias))
25            }
26            _ => unreachable!("Invalid use declaration"),
27        }
28    }
29}
30
31impl Parse for UseStatement {
32    fn parse(pair: Pair) -> ParseResult<Self> {
33        Parser::ensure_rule(&pair, Rule::use_statement);
34
35        let mut visibility = Visibility::default();
36        let mut decl = None;
37
38        for pair in pair.inner() {
39            match pair.as_rule() {
40                Rule::use_declaration => {
41                    decl = Some(UseDeclaration::parse(pair)?);
42                }
43                Rule::visibility => {
44                    visibility = Visibility::parse(pair)?;
45                }
46                _ => unreachable!("Invalid use declaration"),
47            }
48        }
49
50        Ok(Self {
51            visibility,
52            decl: decl.expect("proper use declaration"),
53            src_ref: pair.into(),
54        })
55    }
56}
57
58impl Parse for Visibility {
59    fn parse(pair: Pair) -> ParseResult<Self> {
60        Parser::ensure_rule(&pair, Rule::visibility);
61
62        let s = pair.as_str();
63        match s {
64            "pub" => Ok(Self::Public),
65            "" => Ok(Self::Private),
66            _ => unreachable!("Invalid visibility"),
67        }
68    }
69}