rune/shared/
consts.rs

1//! Constants storage.
2//!
3//! This maps the item of a global constant to its value. It's also used to
4//! detect resolution cycles during constant evaluation.
5
6use crate::alloc::{self, HashMap, HashSet};
7use crate::compile::ItemId;
8use crate::runtime::ConstValue;
9
10/// State for constants processing.
11#[derive(Default)]
12pub(crate) struct Consts {
13    /// Const expression that have been resolved.
14    resolved: HashMap<ItemId, ConstValue>,
15    /// Constant expressions being processed.
16    processing: HashSet<ItemId>,
17}
18
19impl Consts {
20    /// Mark that the given constant is being processed.
21    ///
22    /// Returns `true` if the given constant hasn't been marked yet. This is
23    /// used to detect cycles during processing.
24    pub(crate) fn mark(&mut self, item: ItemId) -> alloc::Result<bool> {
25        self.processing.try_insert(item)
26    }
27
28    /// Get the value for the constant at the given item, if present.
29    pub(crate) fn get(&self, item: ItemId) -> Option<&ConstValue> {
30        self.resolved.get(&item)
31    }
32
33    /// Insert a constant value at the given item.
34    pub(crate) fn insert(
35        &mut self,
36        item: ItemId,
37        value: ConstValue,
38    ) -> alloc::Result<Option<ConstValue>> {
39        self.resolved.try_insert(item, value)
40    }
41}