Lines
98.85 %
Functions
94.44 %
Branches
100 %
//! The session's `DEFSTRUCT` layouts. A [`StructId`] is the index of a layout
//! in the registry; layouts are never removed, so an id stays valid for the
//! life of the session.
use std::collections::{BTreeMap, HashSet};
use crate::ast::StructId;
use crate::error::{Error, Result};
use super::table::SymbolTable;
const ID_PREFIX: &str = "struct#";
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct StructLayout {
pub(crate) name: String,
pub(crate) fields: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct StructRegistry {
layouts: Vec<StructLayout>,
ids: BTreeMap<String, StructId>,
fn duplicate_slot(fields: &[String]) -> Option<&String> {
let mut seen = HashSet::new();
fields.iter().find(|field| !seen.insert(*field))
impl StructRegistry {
/// Registers `name`. Defining it again with the same fields keeps its id;
/// other fields are an error, as a structure's instances would change shape.
pub(crate) fn define(&mut self, name: String, fields: Vec<String>) -> Result<StructId> {
if let Some(slot) = duplicate_slot(&fields) {
return Err(Error::Compile(format!(
"DEFSTRUCT {name}: duplicate slot name {slot}"
)));
let known = self
.id(&name)
.and_then(|id| self.layout(id).map(|layout| (id, layout)));
match known {
Some((id, layout)) if layout.fields == fields => Ok(id),
Some((_, layout)) => Err(Error::Compile(format!(
"DEFSTRUCT {name}: fields ({}) differ from the defined ({})",
fields.join(" "),
layout.fields.join(" ")
))),
None => {
let id = u32::try_from(self.layouts.len())
.map(StructId)
.map_err(|_| Error::Resource("too many structure layouts".to_string()))?;
self.layouts.push(StructLayout {
name: name.clone(),
fields,
});
self.ids.insert(name, id);
Ok(id)
/// Binds `name` to the layout `id`, which an earlier definition made.
pub(crate) fn restore(&mut self, name: &str, id: StructId) {
self.ids.insert(name.to_string(), id);
pub(crate) fn forget(&mut self, name: &str) {
self.ids.remove(name);
pub(crate) fn id(&self, name: &str) -> Option<StructId> {
self.ids.get(name).copied()
pub(crate) fn layout(&self, id: StructId) -> Option<&StructLayout> {
self.layouts.get(id.0 as usize)
/// `message` with each `struct#N` its types printed replaced by the name
/// of the structure `N` is the id of, an article before it agreeing with
/// the name. A lowercase `struct#<id>` inside an echoed string literal is
/// rewritten too (known, contrived).
pub(crate) fn name_ids(&self, message: &str) -> String {
let mut named = String::with_capacity(message.len());
let mut rest = message;
while let Some((before, after)) = rest.split_once(ID_PREFIX) {
named.push_str(before);
let digits = after
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(after.len());
let (number, tail) = after.split_at(digits);
let layout = number
.parse::<usize>()
.ok()
.and_then(|index| self.layouts.get(index));
match layout {
Some(layout) => {
agree_article(&mut named, &layout.name);
named.push_str(&layout.name);
None => named.extend([ID_PREFIX, number]),
rest = tail;
named.push_str(rest);
named
/// Turns a trailing article word `a ` of `text` into `an ` when `name` starts
/// with a vowel.
fn agree_article(text: &mut String, name: &str) {
let article_word = text
.strip_suffix("a ")
.is_some_and(|head| !head.ends_with(|c: char| c.is_alphanumeric()));
let vowel = name
.chars()
.next()
.is_some_and(|c| "aeiou".contains(c.to_ascii_lowercase()));
if article_word && vowel {
text.pop();
text.push_str("n ");
impl SymbolTable {
/// `err` with the structures its message prints by id named.
#[must_use]
pub(crate) fn name_structs(&self, err: Error) -> Error {
match err {
Error::Compile(message) => Error::Compile(self.structs.name_ids(&message)),
Error::Type { expected, actual } => Error::Type {
expected: self.structs.name_ids(&expected),
actual: self.structs.name_ids(&actual),
},
Error::Resource(message) => Error::Resource(self.structs.name_ids(&message)),
Error::Dimension(message) => Error::Dimension(self.structs.name_ids(&message)),
other => other,
#[cfg(test)]
#[path = "structs_tests.rs"]
mod tests;