Skip to main content

microcad_lang/syntax/use/
use_declaration.rs

1// Copyright © 2024-2026 The µcad authors <info@microcad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Use statement syntax element.
5
6use crate::syntax::*;
7use microcad_lang_base::{SrcRef, SrcReferrer, TreeDisplay, TreeState};
8use strum::IntoStaticStr;
9
10/// Use declaration.
11///
12/// A use declaration is an element of a use statement.
13/// It can be a single symbol, all symbols from a module, or an alias.
14///
15/// ```mcad
16/// use std::print;
17/// use std::*;
18/// use std::print as p;
19/// ```
20///
21#[derive(Clone, IntoStaticStr)]
22pub enum UseDeclaration {
23    /// Import symbols given as qualified names: `use a, b`
24    Use(QualifiedName),
25    /// Import all symbols from a module: `use std::*`
26    UseAll(QualifiedName),
27    /// Import as alias: `use a as b`
28    UseAs(QualifiedName, Identifier),
29}
30
31impl SrcReferrer for UseDeclaration {
32    fn src_ref(&self) -> SrcRef {
33        match self {
34            Self::Use(.., name) => name.src_ref(),
35            Self::UseAll(.., name) => name.src_ref(),
36            Self::UseAs(.., name, _) => name.src_ref(),
37        }
38    }
39}
40
41impl std::fmt::Display for UseDeclaration {
42    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
43        match self {
44            UseDeclaration::Use(name) => write!(f, "{name}"),
45            UseDeclaration::UseAll(name) => write!(f, "{name}::*"),
46            UseDeclaration::UseAs(name, alias) => {
47                write!(f, "{name} as {alias}")
48            }
49        }
50    }
51}
52
53impl std::fmt::Debug for UseDeclaration {
54    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
55        match self {
56            UseDeclaration::Use(name) => write!(f, "{name:?}"),
57            UseDeclaration::UseAll(name) => write!(f, "{name:?}::*"),
58            UseDeclaration::UseAs(name, alias) => {
59                write!(f, "{name:?} as {alias:?}")
60            }
61        }
62    }
63}
64
65impl TreeDisplay for UseDeclaration {
66    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
67        // use declaration is transparent
68        match self {
69            UseDeclaration::Use(name) => {
70                writeln!(f, "{:depth$}use {name}", "")
71            }
72            UseDeclaration::UseAll(name) => {
73                writeln!(f, "{:depth$}use {name}::*", "")
74            }
75            UseDeclaration::UseAs(name, alias) => {
76                writeln!(f, "{:depth$}use {name} as {alias}", "")
77            }
78        }
79    }
80}