microcad_lang/eval/statements/
use_statement.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4use crate::eval::*;
5
6/// Trait to use symbols on the [Stack].
7pub trait UseLocally {
8    /// Find a symbol in the symbol table and copy it to the locals.
9    ///
10    /// Might load any related external file if not already loaded.
11    ///
12    /// # Arguments
13    /// - `name`: Name of the symbol to search for
14    /// - `id`: if given overwrites the ID from qualified name (use as)
15    fn use_symbol(&mut self, name: &QualifiedName, id: Option<Identifier>) -> EvalResult<Symbol>;
16
17    /// Find a symbol and copy all it's children to the locals.
18    ///
19    /// Might load any related external file if not already loaded.
20    ///
21    /// # Arguments
22    /// - `name`: Name of the symbol to search for
23    fn use_symbols_of(&mut self, name: &QualifiedName) -> EvalResult<Symbol>;
24}
25
26impl Eval<()> for UseStatement {
27    fn eval(&self, context: &mut EvalContext) -> EvalResult<()> {
28        self.grant(context)?;
29
30        if !context.is_module() {
31            log::trace!("Evaluating use statement: {self}");
32            match &self.decl {
33                UseDeclaration::Use(name) => {
34                    if let Err(err) = context.use_symbol(name, None) {
35                        context.error(name, err)?;
36                    }
37                }
38                UseDeclaration::UseAll(name) => {
39                    if let Err(err) = context.use_symbols_of(name) {
40                        context.error(name, err)?
41                    }
42                }
43                UseDeclaration::UseAs(name, alias) => {
44                    if let Err(err) = context.use_symbol(name, Some(alias.clone())) {
45                        context.error(name, err)?;
46                    }
47                }
48            }
49        }
50        Ok(())
51    }
52}