1
//! The session's `DEFSTRUCT` layouts. A [`StructId`] is the index of a layout
2
//! in the registry; layouts are never removed, so an id stays valid for the
3
//! life of the session.
4

            
5
use std::collections::{BTreeMap, HashSet};
6

            
7
use crate::ast::StructId;
8
use crate::error::{Error, Result};
9

            
10
use super::table::SymbolTable;
11

            
12
const ID_PREFIX: &str = "struct#";
13

            
14
#[derive(Clone, Debug, PartialEq, Eq)]
15
pub(crate) struct StructLayout {
16
    pub(crate) name: String,
17
    pub(crate) fields: Vec<String>,
18
}
19

            
20
#[derive(Clone, Debug, Default, PartialEq, Eq)]
21
pub(crate) struct StructRegistry {
22
    layouts: Vec<StructLayout>,
23
    ids: BTreeMap<String, StructId>,
24
}
25

            
26
69970
fn duplicate_slot(fields: &[String]) -> Option<&String> {
27
69970
    let mut seen = HashSet::new();
28
74765
    fields.iter().find(|field| !seen.insert(*field))
29
69970
}
30

            
31
impl StructRegistry {
32
    /// Registers `name`. Defining it again with the same fields keeps its id;
33
    /// other fields are an error, as a structure's instances would change shape.
34
69970
    pub(crate) fn define(&mut self, name: String, fields: Vec<String>) -> Result<StructId> {
35
69970
        if let Some(slot) = duplicate_slot(&fields) {
36
209
            return Err(Error::Compile(format!(
37
209
                "DEFSTRUCT {name}: duplicate slot name {slot}"
38
209
            )));
39
69761
        }
40
69761
        let known = self
41
69761
            .id(&name)
42
3751
            .and_then(|id| self.layout(id).map(|layout| (id, layout)));
43
69761
        match known {
44
3751
            Some((id, layout)) if layout.fields == fields => Ok(id),
45
834
            Some((_, layout)) => Err(Error::Compile(format!(
46
834
                "DEFSTRUCT {name}: fields ({}) differ from the defined ({})",
47
834
                fields.join(" "),
48
834
                layout.fields.join(" ")
49
834
            ))),
50
            None => {
51
66010
                let id = u32::try_from(self.layouts.len())
52
66010
                    .map(StructId)
53
                    .map_err(|_| Error::Resource("too many structure layouts".to_string()))?;
54
66010
                self.layouts.push(StructLayout {
55
66010
                    name: name.clone(),
56
66010
                    fields,
57
66010
                });
58
66010
                self.ids.insert(name, id);
59
66010
                Ok(id)
60
            }
61
        }
62
69970
    }
63

            
64
    /// Binds `name` to the layout `id`, which an earlier definition made.
65
57618
    pub(crate) fn restore(&mut self, name: &str, id: StructId) {
66
57618
        self.ids.insert(name.to_string(), id);
67
57618
    }
68

            
69
419
    pub(crate) fn forget(&mut self, name: &str) {
70
419
        self.ids.remove(name);
71
419
    }
72

            
73
6933172
    pub(crate) fn id(&self, name: &str) -> Option<StructId> {
74
6933172
        self.ids.get(name).copied()
75
6933172
    }
76

            
77
2398046
    pub(crate) fn layout(&self, id: StructId) -> Option<&StructLayout> {
78
2398046
        self.layouts.get(id.0 as usize)
79
2398046
    }
80

            
81
    /// `message` with each `struct#N` its types printed replaced by the name
82
    /// of the structure `N` is the id of, an article before it agreeing with
83
    /// the name. A lowercase `struct#<id>` inside an echoed string literal is
84
    /// rewritten too (known, contrived).
85
173369
    pub(crate) fn name_ids(&self, message: &str) -> String {
86
173369
        let mut named = String::with_capacity(message.len());
87
173369
        let mut rest = message;
88
174834
        while let Some((before, after)) = rest.split_once(ID_PREFIX) {
89
1465
            named.push_str(before);
90
1465
            let digits = after
91
2303
                .find(|c: char| !c.is_ascii_digit())
92
1465
                .unwrap_or(after.len());
93
1465
            let (number, tail) = after.split_at(digits);
94
1465
            let layout = number
95
1465
                .parse::<usize>()
96
1465
                .ok()
97
1464
                .and_then(|index| self.layouts.get(index));
98
1465
            match layout {
99
                Some(layout) => {
100
1463
                    agree_article(&mut named, &layout.name);
101
1463
                    named.push_str(&layout.name);
102
                }
103
2
                None => named.extend([ID_PREFIX, number]),
104
            }
105
1465
            rest = tail;
106
        }
107
173369
        named.push_str(rest);
108
173369
        named
109
173369
    }
110
}
111

            
112
/// Turns a trailing article word `a ` of `text` into `an ` when `name` starts
113
/// with a vowel.
114
1463
fn agree_article(text: &mut String, name: &str) {
115
1463
    let article_word = text
116
1463
        .strip_suffix("a ")
117
1252
        .is_some_and(|head| !head.ends_with(|c: char| c.is_alphanumeric()));
118
1463
    let vowel = name
119
1463
        .chars()
120
1463
        .next()
121
1463
        .is_some_and(|c| "aeiou".contains(c.to_ascii_lowercase()));
122
1463
    if article_word && vowel {
123
209
        text.pop();
124
209
        text.push_str("n ");
125
1254
    }
126
1463
}
127

            
128
impl SymbolTable {
129
    /// `err` with the structures its message prints by id named.
130
    #[must_use]
131
211153
    pub(crate) fn name_structs(&self, err: Error) -> Error {
132
211153
        match err {
133
146373
            Error::Compile(message) => Error::Compile(self.structs.name_ids(&message)),
134
1489
            Error::Type { expected, actual } => Error::Type {
135
1489
                expected: self.structs.name_ids(&expected),
136
1489
                actual: self.structs.name_ids(&actual),
137
1489
            },
138
14670
            Error::Resource(message) => Error::Resource(self.structs.name_ids(&message)),
139
9345
            Error::Dimension(message) => Error::Dimension(self.structs.name_ids(&message)),
140
39276
            other => other,
141
        }
142
211153
    }
143
}
144

            
145
#[cfg(test)]
146
#[path = "structs_tests.rs"]
147
mod tests;