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