regast-core 0.1.0

Parse-tree matching backends for regast
Documentation
use std::collections::HashMap;

use crate::{Disambiguation, IrId, IrPool, Value, value_order::compare_values};

pub(crate) type Span = (usize, usize);

pub(crate) struct ValueSet {
    values: HashMap<Span, Value>,
    limit: usize,
}

impl ValueSet {
    pub(crate) fn new(limit: usize) -> Self {
        Self {
            values: HashMap::new(),
            limit,
        }
    }

    pub(crate) fn get(&self, span: &Span) -> Option<&Value> {
        self.values.get(span)
    }

    pub(crate) fn insert(&mut self, span: Span, value: Value) -> Result<(), usize> {
        if !self.values.contains_key(&span) && self.values.len() == self.limit {
            return Err(self.values.len() + 1);
        }
        self.values.insert(span, value);
        Ok(())
    }

    pub(crate) fn select(
        &mut self,
        pool: &IrPool,
        root: IrId,
        span: Span,
        candidate: Value,
        disambiguation: Disambiguation,
    ) -> Result<(), usize> {
        let replace = self.values.get(&span).is_none_or(|current| {
            compare_values(pool, root, &candidate, current, disambiguation).is_gt()
        });
        if replace {
            self.insert(span, candidate)?;
        }
        Ok(())
    }

    pub(crate) fn into_inner(self) -> HashMap<Span, Value> {
        self.values
    }
}