Skip to main content

i_slint_compiler/
symbol_counters.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4//! Counter used to generate deterministic unique symbol names while running the
5//! passes.
6
7use std::cell::Cell;
8use std::rc::Rc;
9
10use smol_str::{SmolStr, format_smolstr};
11
12/// A counter, shared across the whole compilation: the
13/// [`crate::typeloader::TypeLoader`] holds it and hands a reference to the passes
14/// that generate names. Sharing it makes the names unique across all the
15/// documents of a compilation, including ones pulled in by inlining, so they
16/// cannot clash once components from different documents end up in the same
17/// generated code.
18#[derive(Default)]
19pub struct SymbolCounters {
20    next: Cell<usize>,
21}
22
23impl SymbolCounters {
24    pub fn shared() -> Rc<Self> {
25        Rc::new(Self::default())
26    }
27
28    /// Return a unique name made of `base` followed by a number, e.g.
29    /// `generate_name("tmpobj_conv_")` -> `tmpobj_conv_0`.
30    pub fn generate_name(&self, base: &str) -> SmolStr {
31        let n = self.next.get();
32        self.next.set(n + 1);
33        format_smolstr!("{base}{n}")
34    }
35}