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