Skip to main content

refix_codegen/
namespace.rs

1mod error;
2
3use std::collections::HashMap;
4use std::collections::hash_map::Entry;
5use std::fmt;
6
7use refix_dictionary::MemberContext;
8
9use crate::Warning;
10pub use error::NameClash;
11
12/// What a generated name stands for.
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub enum Owner {
15    /// A name the generated code defines or imports for itself.
16    Generated,
17    /// A field's accessor.
18    Field(String),
19    /// The enum of a field's values.
20    Enum(String),
21    /// A message's type or module.
22    Message(String),
23    /// A group's type, module or accessor, by the context of its instances.
24    Group(MemberContext),
25    /// One of a field's values.
26    Value {
27        field: String,
28        code: String,
29        description: String,
30    },
31}
32
33impl fmt::Display for Owner {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Owner::Generated => write!(f, "the generated code"),
37            Owner::Field(field) => write!(f, "field '{field}'"),
38            Owner::Enum(field) => write!(f, "the enum of field '{field}'"),
39            Owner::Message(message) => write!(f, "message '{message}'"),
40            Owner::Group(context) => write!(f, "{context}"),
41            Owner::Value {
42                field,
43                code,
44                description,
45            } => write!(f, "value '{description}' (code {code}) of field '{field}'"),
46        }
47    }
48}
49
50/// The names taken in one scope of the generated code.
51#[derive(Debug, Default)]
52pub(crate) struct Namespace {
53    owners: HashMap<String, Owner>,
54}
55
56impl Namespace {
57    /// A namespace in which the generated code already takes `names`.
58    pub(crate) fn with_generated(names: &[&str]) -> Self {
59        let owners = names
60            .iter()
61            .map(|name| ((*name).to_owned(), Owner::Generated))
62            .collect();
63        Self { owners }
64    }
65
66    /// Takes `name` for `owner`, unless something else already has it.
67    pub(crate) fn claim(&mut self, name: &str, owner: Owner) -> Result<(), Box<NameClash>> {
68        match self.owners.entry(name.to_owned()) {
69            Entry::Occupied(taken) => Err(Box::new(NameClash {
70                name: name.to_owned(),
71                first: taken.get().clone(),
72                second: owner,
73            })),
74            Entry::Vacant(free) => {
75                free.insert(owner);
76                Ok(())
77            }
78        }
79    }
80
81    /// Takes the name of a field's enum.
82    ///
83    /// The enum yields to a message or group of its name, taking `Enum`
84    /// after it, with a warning.
85    pub(crate) fn claim_enum(
86        &mut self,
87        field: &str,
88        warnings: &mut Vec<Warning>,
89    ) -> Result<String, Box<NameClash>> {
90        let owner = Owner::Enum(field.to_owned());
91        let clash = match self.claim(field, owner.clone()) {
92            Ok(()) => return Ok(field.to_owned()),
93            Err(clash) if matches!(clash.first, Owner::Message(_) | Owner::Group(_)) => clash,
94            Err(clash) => return Err(clash),
95        };
96        let name = format!("{field}Enum");
97        self.claim(&name, owner)?;
98        warnings.push(Warning::Renamed {
99            clash,
100            name: name.clone(),
101        });
102        Ok(name)
103    }
104
105    /// Takes the name of one of a field's values.
106    ///
107    /// A value named like an earlier one of the field is numbered from 2 by
108    /// `numbered`, with a warning.
109    pub(crate) fn claim_value(
110        &mut self,
111        name: &str,
112        owner: Owner,
113        numbered: impl Fn(&str, u32) -> String,
114        warnings: &mut Vec<Warning>,
115    ) -> Result<String, Box<NameClash>> {
116        let clash = match self.claim(name, owner.clone()) {
117            Ok(()) => return Ok(name.to_owned()),
118            Err(clash) if matches!(clash.first, Owner::Value { .. }) => clash,
119            Err(clash) => return Err(clash),
120        };
121        let mut number = 2;
122        let renamed = loop {
123            let candidate = numbered(name, number);
124            if self.claim(&candidate, owner.clone()).is_ok() {
125                break candidate;
126            }
127            number += 1;
128        };
129        warnings.push(Warning::Renamed {
130            clash,
131            name: renamed.clone(),
132        });
133        Ok(renamed)
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::{NameClash, Namespace, Owner};
140    use crate::Warning;
141    use refix_dictionary::MemberContext;
142
143    #[test]
144    fn a_free_name_can_be_claimed() {
145        let mut namespace = Namespace::default();
146        assert!(
147            namespace
148                .claim("OrdType", Owner::Enum("OrdType".to_owned()))
149                .is_ok()
150        );
151    }
152
153    #[test]
154    fn a_taken_name_reports_both_owners() {
155        let mut namespace = Namespace::default();
156        namespace
157            .claim(
158                "SecurityStatus",
159                Owner::Message("SecurityStatus".to_owned()),
160            )
161            .unwrap();
162
163        assert_eq!(
164            namespace
165                .claim("SecurityStatus", Owner::Enum("SecurityStatus".to_owned()))
166                .unwrap_err(),
167            Box::new(NameClash {
168                name: "SecurityStatus".to_owned(),
169                first: Owner::Message("SecurityStatus".to_owned()),
170                second: Owner::Enum("SecurityStatus".to_owned()),
171            })
172        );
173    }
174
175    #[test]
176    fn generated_names_are_taken_from_the_start() {
177        let mut namespace = Namespace::with_generated(&["raw"]);
178        assert_eq!(
179            namespace
180                .claim("raw", Owner::Field("Raw".to_owned()))
181                .unwrap_err()
182                .first,
183            Owner::Generated
184        );
185    }
186
187    #[test]
188    fn an_enum_yields_to_a_message() {
189        let mut namespace = Namespace::default();
190        namespace
191            .claim(
192                "SecurityStatus",
193                Owner::Message("SecurityStatus".to_owned()),
194            )
195            .unwrap();
196        let mut warnings = Vec::new();
197
198        let name = namespace
199            .claim_enum("SecurityStatus", &mut warnings)
200            .unwrap();
201
202        assert_eq!(name, "SecurityStatusEnum");
203        assert_eq!(
204            warnings,
205            vec![Warning::Renamed {
206                clash: Box::new(NameClash {
207                    name: "SecurityStatus".to_owned(),
208                    first: Owner::Message("SecurityStatus".to_owned()),
209                    second: Owner::Enum("SecurityStatus".to_owned()),
210                }),
211                name: "SecurityStatusEnum".to_owned(),
212            }]
213        );
214    }
215
216    #[test]
217    fn an_enum_yields_to_a_group() {
218        let context = MemberContext::Component("RateSource".to_owned()).group("NoRateSources");
219        let mut namespace = Namespace::default();
220        namespace
221            .claim("RateSource", Owner::Group(context))
222            .unwrap();
223
224        let name = namespace.claim_enum("RateSource", &mut Vec::new()).unwrap();
225
226        assert_eq!(name, "RateSourceEnum");
227    }
228
229    #[test]
230    fn an_enum_does_not_yield_to_the_generated_code() {
231        let mut namespace = Namespace::with_generated(&["Result"]);
232        let mut warnings = Vec::new();
233
234        let clash = namespace.claim_enum("Result", &mut warnings).unwrap_err();
235
236        assert_eq!(clash.first, Owner::Generated);
237        assert!(warnings.is_empty());
238    }
239
240    #[test]
241    fn a_yielding_enum_clashes_when_its_new_name_is_taken() {
242        let mut namespace = Namespace::default();
243        for message in ["SecurityStatus", "SecurityStatusEnum"] {
244            namespace
245                .claim(message, Owner::Message(message.to_owned()))
246                .unwrap();
247        }
248
249        let clash = namespace
250            .claim_enum("SecurityStatus", &mut Vec::new())
251            .unwrap_err();
252
253        assert_eq!(
254            clash,
255            Box::new(NameClash {
256                name: "SecurityStatusEnum".to_owned(),
257                first: Owner::Message("SecurityStatusEnum".to_owned()),
258                second: Owner::Enum("SecurityStatus".to_owned()),
259            })
260        );
261    }
262
263    fn value(code: &str) -> Owner {
264        Owner::Value {
265            field: "BenchmarkCurveName".to_owned(),
266            code: code.to_owned(),
267            description: "EURIBOR".to_owned(),
268        }
269    }
270
271    fn numbered(name: &str, number: u32) -> String {
272        format!("{name}{number}")
273    }
274
275    #[test]
276    fn values_named_alike_are_numbered_in_order() {
277        let mut namespace = Namespace::default();
278        let mut warnings = Vec::new();
279
280        let names: Vec<String> = ["Euribor", "EURIBOR", "euribor"]
281            .into_iter()
282            .map(|code| {
283                namespace
284                    .claim_value("Euribor", value(code), numbered, &mut warnings)
285                    .unwrap()
286            })
287            .collect();
288
289        assert_eq!(names, ["Euribor", "Euribor2", "Euribor3"]);
290        assert_eq!(warnings.len(), 2);
291        assert_eq!(
292            warnings[1],
293            Warning::Renamed {
294                clash: Box::new(NameClash {
295                    name: "Euribor".to_owned(),
296                    first: value("Euribor"),
297                    second: value("euribor"),
298                }),
299                name: "Euribor3".to_owned(),
300            }
301        );
302    }
303
304    #[test]
305    fn a_numbered_value_skips_a_taken_number() {
306        let mut namespace = Namespace::default();
307        namespace.claim("Euribor", value("Euribor")).unwrap();
308        namespace.claim("Euribor2", value("Euribor2")).unwrap();
309
310        let name = namespace
311            .claim_value("Euribor", value("EURIBOR"), numbered, &mut Vec::new())
312            .unwrap();
313
314        assert_eq!(name, "Euribor3");
315    }
316
317    #[test]
318    fn a_value_is_not_numbered_past_the_generated_code() {
319        let mut namespace = Namespace::with_generated(&["Unrecognized"]);
320
321        let clash = namespace
322            .claim_value("Unrecognized", value("U"), numbered, &mut Vec::new())
323            .unwrap_err();
324
325        assert_eq!(clash.first, Owner::Generated);
326    }
327
328    #[test]
329    fn a_clash_names_the_name_and_both_owners() {
330        let clash = NameClash {
331            name: "Euribor".to_owned(),
332            first: Owner::Value {
333                field: "BenchmarkCurveName".to_owned(),
334                code: "Euribor".to_owned(),
335                description: "EURIBOR".to_owned(),
336            },
337            second: Owner::Value {
338                field: "BenchmarkCurveName".to_owned(),
339                code: "EURIBOR".to_owned(),
340                description: "EURIBOR".to_owned(),
341            },
342        };
343        assert_eq!(
344            clash.to_string(),
345            "`Euribor` is taken by both value 'EURIBOR' (code Euribor) of field \
346             'BenchmarkCurveName' and value 'EURIBOR' (code EURIBOR) of field 'BenchmarkCurveName'"
347        );
348    }
349
350    #[test]
351    fn owners_describe_where_a_name_comes_from() {
352        let context = MemberContext::Component("Parties".to_owned()).group("NoPartyIDs");
353        assert_eq!(Owner::Generated.to_string(), "the generated code");
354        assert_eq!(Owner::Field("Raw".to_owned()).to_string(), "field 'Raw'");
355        assert_eq!(
356            Owner::Enum("RateSource".to_owned()).to_string(),
357            "the enum of field 'RateSource'"
358        );
359        assert_eq!(
360            Owner::Message("Logon".to_owned()).to_string(),
361            "message 'Logon'"
362        );
363        assert_eq!(
364            Owner::Group(context).to_string(),
365            "group 'NoPartyIDs' in component 'Parties'"
366        );
367    }
368}