asdl/
util.rs

1use std::fmt::Write;
2use std::collections::HashMap;
3
4use crate::ast;
5
6#[derive(Default)]
7pub(crate) struct FieldNames {
8    names_indexes: HashMap<String, u32>,
9}
10
11impl FieldNames {
12    pub(crate) fn get_or_generate(
13        &mut self,
14        id: &Option<ast::Id>,
15        type_id: &ast::TypeId,
16    ) -> String {
17        match id {
18            Option::Some(id) => id.to_string(),
19            Option::None => {
20                let type_id = type_id.to_string();
21                let index = self.names_indexes.entry(type_id.to_string()).or_insert(0);
22                let res = if *index == 0 {
23                    type_id.to_string()
24                } else {
25                    let mut buf = String::new();
26                    write!(&mut buf, "{}{}", type_id, index).unwrap();
27                    buf
28                };
29                *index += 1;
30                res
31            }
32        }
33    }
34}