brush_core/
functions.rs

1//! Structures for managing function registrations.
2
3use std::{collections::HashMap, sync::Arc};
4
5/// An environment for defined, named functions.
6#[derive(Clone, Default)]
7pub struct FunctionEnv {
8    functions: HashMap<String, FunctionRegistration>,
9}
10
11impl FunctionEnv {
12    /// Tries to retrieve the registration for a function by name.
13    ///
14    /// # Arguments
15    ///
16    /// * `name` - The name of the function to retrieve.
17    pub fn get(&self, name: &str) -> Option<&FunctionRegistration> {
18        self.functions.get(name)
19    }
20
21    /// Tries to retrieve a mutable reference to the registration for a
22    /// function by name.
23    ///
24    /// # Arguments
25    ///
26    /// * `name` - The name of the function to retrieve.
27    pub fn get_mut(&mut self, name: &str) -> Option<&mut FunctionRegistration> {
28        self.functions.get_mut(name)
29    }
30
31    /// Unregisters a function from the environment.
32    ///
33    /// # Arguments
34    ///
35    /// * `name` - The name of the function to remove.
36    pub fn remove(&mut self, name: &str) -> Option<FunctionRegistration> {
37        self.functions.remove(name)
38    }
39
40    /// Updates a function registration in this environment.
41    ///
42    /// # Arguments
43    ///
44    /// * `name` - The name of the function to update.
45    /// * `registration` - The new registration for the function.
46    pub fn update(&mut self, name: String, registration: FunctionRegistration) {
47        self.functions.insert(name, registration);
48    }
49
50    /// Clear all functions in this environment.
51    pub fn clear(&mut self) {
52        self.functions.clear();
53    }
54
55    /// Returns an iterator over the functions registered in this environment.
56    pub fn iter(&self) -> impl Iterator<Item = (&String, &FunctionRegistration)> {
57        self.functions.iter()
58    }
59}
60
61/// Encapsulates a registration for a defined function.
62#[derive(Clone)]
63pub struct FunctionRegistration {
64    /// The definition of the function.
65    pub(crate) definition: Arc<brush_parser::ast::FunctionDefinition>,
66    /// Whether or not this function definition should be exported to children.
67    exported: bool,
68}
69
70impl From<brush_parser::ast::FunctionDefinition> for FunctionRegistration {
71    fn from(definition: brush_parser::ast::FunctionDefinition) -> Self {
72        Self {
73            definition: Arc::new(definition),
74            exported: false,
75        }
76    }
77}
78
79impl FunctionRegistration {
80    /// Marks the function for export.
81    pub const fn export(&mut self) {
82        self.exported = true;
83    }
84
85    /// Unmarks the function for export.
86    pub const fn unexport(&mut self) {
87        self.exported = false;
88    }
89
90    /// Returns whether this function is exported.
91    pub const fn is_exported(&self) -> bool {
92        self.exported
93    }
94}