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