microcad_lang/syntax/use/
use_declaration.rs

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