Skip to main content

tvm_tirx/ir/
unique_name_supply.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Unique names. A [`UniqueNameSupply`] hands out names that do not collide with the ones it has
21//! given out or reserved, for building and rewriting IR.
22
23// tvm-ffi-stubgen(file): mod(missing_docs = allow)
24// Names the hand-written wrappers use: the import section keeps them even when no generated block
25// does.
26// tvm-ffi-stubgen(import): tvm_ffi::Result
27// tvm-ffi-stubgen(import): tvm_ffi::String
28// tvm-ffi-stubgen(import): crate::ir::support
29
30// tvm-ffi-stubgen(begin): import-section
31use crate::ir::support;
32use tvm_ffi::Object;
33use tvm_ffi::ObjectArc;
34use tvm_ffi::Result;
35use tvm_ffi::String;
36// tvm-ffi-stubgen(end)
37
38/// A set of names in use, with a prefix, from which [`fresh_name`](Self::fresh_name) derives
39/// names that do not collide.
40///
41/// A supply is mutable: every handle sees the names it has given out or reserved.
42///
43/// # Examples
44///
45/// ```
46/// use tvm_tirx::ir::UniqueNameSupply;
47///
48/// let names = UniqueNameSupply::new("fused");
49/// names.reserve_name("x", false)?;
50///
51/// assert_eq!(names.fresh_name("x", false, true)?, "x_1");
52///
53/// assert_eq!(names.fresh_name("y", true, true)?, "fused_y");
54/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
55/// ```
56// tvm-ffi-stubgen(begin): object/ir.UniqueNameSupply
57#[allow(missing_docs)]
58#[repr(C)]
59#[derive(tvm_ffi::derive::ObjectRef, Clone)]
60pub struct UniqueNameSupply {
61    data_: ObjectArc<UniqueNameSupplyObj>,
62}
63
64/// The object behind [`UniqueNameSupply`].
65// Opaque: bytes [24, 64) of [24, 64) are not accounted for by reflected fields. Fields are read through the C ABI getters.
66#[allow(missing_docs)]
67#[repr(C)]
68#[derive(tvm_ffi::derive::Object)]
69#[object(type_key = "ir.UniqueNameSupply", final)]
70pub struct UniqueNameSupplyObj {
71    base_: Object,
72}
73// tvm-ffi-stubgen(end)
74
75impl UniqueNameSupply {
76    /// Create an empty supply with the prefix `prefix`, which `add_prefix` prepends to a name as
77    /// `<prefix>_<name>` (`ir.UniqueNameSupply`).
78    pub fn new(prefix: &str) -> Self {
79        support::infallible(
80            tvm_ffi::cached_global_func!("ir.UniqueNameSupply")
81                .call_tuple((String::from(prefix),))
82                .and_then(|any| any.try_into()),
83        )
84    }
85
86    /// Return a name derived from `name` that the supply has not given out, and reserve it
87    /// (`ir.UniqueNameSupplyFreshName`).
88    ///
89    /// The name is `name` with `.` replaced by `_`, and a numeric suffix when the supply already
90    /// has it; `add_prefix` prepends the prefix and `add_underscore` puts `_` before the suffix.
91    pub fn fresh_name(&self, name: &str, add_prefix: bool, add_underscore: bool) -> Result<String> {
92        tvm_ffi::cached_global_func!("ir.UniqueNameSupplyFreshName")
93            .call_tuple((self, String::from(name), add_prefix, add_underscore))?
94            .try_into()
95    }
96
97    /// Reserve `name`, with the prefix if `add_prefix`, so that [`fresh_name`](Self::fresh_name)
98    /// does not give it out, and return the reserved name (`ir.UniqueNameSupplyReserveName`).
99    pub fn reserve_name(&self, name: &str, add_prefix: bool) -> Result<String> {
100        tvm_ffi::cached_global_func!("ir.UniqueNameSupplyReserveName")
101            .call_tuple((self, String::from(name), add_prefix))?
102            .try_into()
103    }
104
105    /// Return whether the supply has given out or reserved `name`, with the prefix if `add_prefix`
106    /// (`ir.UniqueNameSupplyContainsName`).
107    pub fn contains_name(&self, name: &str, add_prefix: bool) -> Result<bool> {
108        tvm_ffi::cached_global_func!("ir.UniqueNameSupplyContainsName")
109            .call_tuple((self, String::from(name), add_prefix))?
110            .try_into()
111    }
112}