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/// ```ucad
15/// use std::print;
16/// use std::*;
17/// use std::print as p;
18/// ```
19///
20#[derive(Clone, Debug, IntoStaticStr)]
21pub enum UseDeclaration {
22    /// Import symbols given as qualified names: `use a, b`
23    Use(Visibility, QualifiedName),
24    /// Import all symbols from a module: `use std::*`
25    UseAll(Visibility, QualifiedName),
26    /// Import as alias: `use a as b`
27    UseAlias(Visibility, 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::UseAlias(.., 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(visibility, name) => write!(f, "{visibility}{name}"),
44            UseDeclaration::UseAll(visibility, name) => write!(f, "{visibility}{name}::*"),
45            UseDeclaration::UseAlias(visibility, name, alias) => {
46                write!(f, "{visibility}{name} as {alias}")
47            }
48        }
49    }
50}
51
52impl TreeDisplay for UseDeclaration {
53    fn tree_print(&self, f: &mut std::fmt::Formatter, depth: TreeState) -> std::fmt::Result {
54        // use declaration is transparent
55        match self {
56            UseDeclaration::Use(visibility, name) => {
57                writeln!(f, "{:depth$}{visibility}use {name}", "")
58            }
59            UseDeclaration::UseAll(visibility, name) => {
60                writeln!(f, "{:depth$}{visibility}use {name}::* ({visibility})", "")
61            }
62            UseDeclaration::UseAlias(visibility, name, alias) => {
63                writeln!(
64                    f,
65                    "{:depth$}{visibility}use {name} as {alias} ({visibility})",
66                    ""
67                )
68            }
69        }
70    }
71}