use crate::parser::{Expression, Item, Literal, Type};
use std::collections::HashMap;
#[derive(Debug, Clone)]
pub(super) struct StringPoolEntry {
pub(super) value: String,
pub(super) count: usize,
pub(super) pool_name: String,
}
pub(super) fn build_string_pool(frequency: HashMap<String, usize>) -> Vec<StringPoolEntry> {
let mut pool = Vec::new();
let mut index = 0;
for (value, count) in frequency {
if count >= 2 {
pool.push(StringPoolEntry {
value: value.clone(),
count,
pool_name: format!("__STRING_POOL_{}", index),
});
index += 1;
}
}
pool.sort_by_key(|b| std::cmp::Reverse(b.count));
pool
}
pub(super) fn create_pool_map(pool: &[StringPoolEntry]) -> HashMap<String, String> {
pool.iter()
.map(|entry| (entry.value.clone(), entry.pool_name.clone()))
.collect()
}
pub(super) fn create_pool_statics<'ast>(
pool: &[StringPoolEntry],
optimizer: &crate::optimizer::Optimizer,
) -> Vec<Item<'ast>> {
pool.iter()
.map(|entry| Item::Static {
name: entry.pool_name.clone(),
mutable: false,
type_: Type::Reference(Box::new(Type::Custom("str".to_string()))),
value: optimizer.alloc_expr(Expression::Literal {
value: Literal::String(entry.value.clone()),
location: None,
}),
location: None,
})
.collect()
}